Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74d445af4d | ||
|
|
c45ea6d6f9 | ||
|
|
14acdb84e4 | ||
|
|
d898b66374 |
No files matched your search
@@ -1,6 +1,4 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ManagedRuntime, ServiceMap } from "effect";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
@@ -12,31 +10,8 @@ import {
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
|
||||
let runtime: ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, never> | null = null;
|
||||
let services: ServiceMap.ServiceMap<NodeServices.NodeServices> | null = null;
|
||||
|
||||
beforeEach(async () => {
|
||||
runtime = ManagedRuntime.make(NodeServices.layer);
|
||||
services = await runtime.services();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
services = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
function createManager() {
|
||||
if (!services) {
|
||||
throw new Error("Test runtime services not initialized.");
|
||||
}
|
||||
return new CodexAppServerManager(services);
|
||||
}
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = createManager();
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -72,7 +47,7 @@ function createSendTurnHarness() {
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = createManager();
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
@@ -173,7 +148,7 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = createManager();
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -16,10 +18,6 @@ import {
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Cause, Effect, Exit, ServiceMap, Scope, Stream } from "effect";
|
||||
import type { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -42,8 +40,8 @@ interface PendingApprovalRequest {
|
||||
|
||||
interface CodexSessionContext {
|
||||
session: ProviderSession;
|
||||
child: ChildProcessSpawner.ChildProcessHandle;
|
||||
scope: Scope.Closeable;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
nextRequestId: number;
|
||||
@@ -106,6 +104,23 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"does not exist",
|
||||
];
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
model: string | undefined | null,
|
||||
preferredId?: string,
|
||||
@@ -159,21 +174,6 @@ export interface CodexAppServerManagerEvents {
|
||||
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
|
||||
private readonly runPromise: <A, E>(
|
||||
effect: Effect.Effect<A, E, NodeServices.NodeServices>,
|
||||
options?: Effect.RunOptions | undefined,
|
||||
) => Promise<A>;
|
||||
|
||||
constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
|
||||
super();
|
||||
this.runPromise = services
|
||||
? Effect.runPromiseWith(services)
|
||||
: ((effect, options) =>
|
||||
Effect.runPromise(
|
||||
effect as unknown as Effect.Effect<unknown, never>,
|
||||
options,
|
||||
)) as typeof this.runPromise;
|
||||
}
|
||||
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
|
||||
@@ -195,23 +195,21 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
||||
const codexHomePath = input.codexHomePath;
|
||||
const managedProcess = await this.runPromise(
|
||||
spawnManagedCommand(
|
||||
makeRuntimeCommand(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
extendEnv: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
context = {
|
||||
session,
|
||||
child: managedProcess.handle,
|
||||
scope: managedProcess.scope,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
@@ -219,7 +217,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
await this.attachProcessListeners(context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
@@ -234,7 +232,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
},
|
||||
});
|
||||
|
||||
await this.writeMessage(context, { method: "initialized" });
|
||||
this.writeMessage(context, { method: "initialized" });
|
||||
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||
const sessionOverrides = {
|
||||
@@ -450,7 +448,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
context.pendingApprovals.delete(requestId);
|
||||
await this.writeMessage(context, {
|
||||
this.writeMessage(context, {
|
||||
id: pendingRequest.jsonRpcId,
|
||||
result: {
|
||||
decision,
|
||||
@@ -491,7 +489,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
context.pending.clear();
|
||||
context.pendingApprovals.clear();
|
||||
void this.runPromise(Scope.close(context.scope, Exit.void)).catch(() => undefined);
|
||||
|
||||
context.output.close();
|
||||
|
||||
if (!context.child.killed) {
|
||||
killChildTree(context.child);
|
||||
}
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
@@ -530,75 +533,47 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return context;
|
||||
}
|
||||
|
||||
private async attachProcessListeners(context: CodexSessionContext): Promise<void> {
|
||||
await this.runPromise(
|
||||
Effect.gen(
|
||||
function* (this: CodexAppServerManager) {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(Stream.splitLines(Stream.decodeText(context.child.stdout)), (line) =>
|
||||
Effect.sync(() => {
|
||||
this.handleStdoutLine(context, line);
|
||||
}),
|
||||
),
|
||||
);
|
||||
private attachProcessListeners(context: CodexSessionContext): void {
|
||||
context.output.on("line", (line) => {
|
||||
this.handleStdoutLine(context, line);
|
||||
});
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(Stream.decodeText(context.child.stderr), (raw) =>
|
||||
Effect.sync(() => {
|
||||
const lines = raw.split(/\r?\n/g);
|
||||
for (const rawLine of lines) {
|
||||
const classified = classifyCodexStderrLine(rawLine);
|
||||
if (!classified) {
|
||||
continue;
|
||||
}
|
||||
context.child.stderr.on("data", (chunk: Buffer) => {
|
||||
const raw = chunk.toString();
|
||||
const lines = raw.split(/\r?\n/g);
|
||||
for (const rawLine of lines) {
|
||||
const classified = classifyCodexStderrLine(rawLine);
|
||||
if (!classified) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||
}
|
||||
});
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.matchCauseEffect(context.child.exitCode, {
|
||||
onFailure: (cause) =>
|
||||
Effect.sync(() => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
context.child.on("error", (error) => {
|
||||
const message = error.message || "codex app-server process errored.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "process/error", message);
|
||||
});
|
||||
|
||||
const squashed = Cause.squash(cause);
|
||||
const message =
|
||||
squashed instanceof Error
|
||||
? squashed.message
|
||||
: "codex app-server process errored.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
activeTurnId: undefined,
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "process/error", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
}),
|
||||
onSuccess: (code) =>
|
||||
Effect.sync(() => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
context.child.on("exit", (code, signal) => {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = `codex app-server exited (code=${code}).`;
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: code === 0 ? context.session.lastError : message,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/exited", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}.bind(this),
|
||||
).pipe(Scope.provide(context.scope)),
|
||||
);
|
||||
const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
|
||||
this.updateSession(context, {
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
lastError: code === 0 ? context.session.lastError : message,
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/exited", message);
|
||||
this.sessions.delete(context.session.sessionId);
|
||||
});
|
||||
}
|
||||
|
||||
private handleStdoutLine(context: CodexSessionContext, line: string): void {
|
||||
@@ -754,31 +729,19 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
void this.writeMessage(context, {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
result: { answers: {} },
|
||||
}).catch((error) => {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/writeError",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void this.writeMessage(context, {
|
||||
this.writeMessage(context, {
|
||||
id: request.id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: `Unsupported server request: ${request.method}`,
|
||||
},
|
||||
}).catch((error) => {
|
||||
this.emitErrorEvent(
|
||||
context,
|
||||
"protocol/writeError",
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -821,30 +784,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
resolve,
|
||||
reject,
|
||||
});
|
||||
void this.writeMessage(context, {
|
||||
this.writeMessage(context, {
|
||||
method,
|
||||
id,
|
||||
params,
|
||||
}).catch((error) => {
|
||||
clearTimeout(timeout);
|
||||
context.pending.delete(String(id));
|
||||
reject(error instanceof Error ? error : new Error(String(error)));
|
||||
});
|
||||
});
|
||||
|
||||
return result as TResponse;
|
||||
}
|
||||
|
||||
private async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {
|
||||
private writeMessage(context: CodexSessionContext, message: unknown): void {
|
||||
const encoded = JSON.stringify(message);
|
||||
if (context.stopping) {
|
||||
if (!context.child.stdin.writable) {
|
||||
throw new Error("Cannot write to codex app-server stdin.");
|
||||
}
|
||||
await this.runPromise(
|
||||
Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe(
|
||||
Scope.provide(context.scope),
|
||||
),
|
||||
);
|
||||
|
||||
context.child.stdin.write(`${encoded}\n`);
|
||||
}
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
@@ -98,12 +98,31 @@ function sanitizePrTitle(raw: string): string {
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
let text = "";
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
text += Buffer.from(chunk).toString("utf8");
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
return text;
|
||||
});
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
|
||||
const writeTempFile = (
|
||||
@@ -184,59 +203,68 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const runCodexCommand = Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
stdin: prompt,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: CODEX_TIMEOUT_MS,
|
||||
maxBufferBytes: 1_000_000,
|
||||
outputMode: "truncate",
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new TextGenerationError({ operation, detail: "Codex CLI request timed out." });
|
||||
}
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const stdout = result.stdout;
|
||||
const stderr = result.stderr;
|
||||
const exitCode = result.code ?? 0;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
throw new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
catch: (error) =>
|
||||
normalizeCodexError(operation, error, "Failed to execute Codex CLI process"),
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
@@ -247,7 +275,19 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand;
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/**
|
||||
* Git process helpers - runtime-aware git execution with typed errors.
|
||||
* Git process helpers - Effect-native git execution with typed errors.
|
||||
*
|
||||
* Centralizes child-process git invocation for server modules. This module
|
||||
* only executes git commands and reports structured failures.
|
||||
*
|
||||
* @module GitServiceLive
|
||||
*/
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
ExecuteGitInput,
|
||||
@@ -39,7 +39,37 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
const makeGitService = Effect.sync(() => {
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
bytes += chunk.byteLength;
|
||||
if (bytes > maxOutputBytes) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
|
||||
text += decoder.decode();
|
||||
return text;
|
||||
});
|
||||
|
||||
const makeGitService = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
@@ -48,48 +78,62 @@ const makeGitService = Effect.sync(() => {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const result = await runProcess("git", commandInput.args, {
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: maxOutputBytes,
|
||||
outputMode: "error",
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
});
|
||||
}
|
||||
|
||||
const exitCode = result.code ?? 0;
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = result.stderr.trim();
|
||||
throw new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
code: exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
} satisfies ExecuteGitResult;
|
||||
},
|
||||
catch: toGitCommandError(commandInput, "failed to run."),
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
return yield* commandEffect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(timeoutMs),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
+13
-201
@@ -7,7 +7,6 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveBrowserLaunch,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
@@ -19,7 +18,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
@@ -28,7 +27,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
@@ -37,7 +36,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
@@ -50,7 +49,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
@@ -59,7 +58,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
@@ -68,7 +67,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
@@ -77,7 +76,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
@@ -90,7 +89,7 @@ describe("resolveEditorLaunch", () => {
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
{ platform: "darwin" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
@@ -99,7 +98,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
{ platform: "win32" },
|
||||
"win32",
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
@@ -108,7 +107,7 @@ describe("resolveEditorLaunch", () => {
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
{ platform: "linux" },
|
||||
"linux",
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
@@ -116,112 +115,6 @@ describe("resolveEditorLaunch", () => {
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers linux editor shims in wsl-hosted mode when available", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code",
|
||||
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to windows editor executables in wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "code.exe",
|
||||
args: [
|
||||
"--goto",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("translates file-manager targets for wsl-hosted mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "file-manager" },
|
||||
{
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
translateWslPathToWindows: (target) =>
|
||||
target.replace(
|
||||
"/home/julius/project",
|
||||
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("launchDetached", () => {
|
||||
@@ -317,94 +210,13 @@ describe("resolveAvailableEditors", () => {
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts windows editor executables in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const editors = resolveAvailableEditors({
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBrowserLaunch", () => {
|
||||
it("prefers wslview in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "wslview"), "#!/bin/sh\n", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "wslview",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to explorer.exe in wsl-hosted mode", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-explorer-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||
platform: "linux",
|
||||
runtimeEnvironment: {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
},
|
||||
env: {
|
||||
PATH: dir,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(launch, {
|
||||
command: "explorer.exe",
|
||||
args: ["http://localhost:3773"],
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+43
-235
@@ -6,13 +6,12 @@
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
@@ -38,24 +37,7 @@ interface CommandAvailabilityOptions {
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
interface ResolveOpenOptions extends CommandAvailabilityOptions {
|
||||
readonly runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
readonly translateWslPathToWindows?: (target: string) => string;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
function detectRuntimeEnvironment(options: ResolveOpenOptions): ServerRuntimeEnvironment {
|
||||
return (
|
||||
options.runtimeEnvironment ??
|
||||
detectServerRuntimeEnvironment({
|
||||
...(options.platform !== undefined ? { platform: options.platform } : {}),
|
||||
...(options.env !== undefined ? { env: options.env } : {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
@@ -178,20 +160,14 @@ export function isCommandAvailable(
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
options: ResolveOpenOptions = {},
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const launch = resolveOpenCommand(editor.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
if (launch.some((entry) => isCommandAvailable(entry, { platform, env }))) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
@@ -225,223 +201,60 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
function splitPathAndPosition(value: string): {
|
||||
path: string;
|
||||
line: string | undefined;
|
||||
column: string | undefined;
|
||||
} {
|
||||
let path = value;
|
||||
let column: string | undefined;
|
||||
let line: string | undefined;
|
||||
|
||||
const columnMatch = path.match(/:(\d+)$/);
|
||||
if (!columnMatch?.[1]) {
|
||||
return { path, line: undefined, column: undefined };
|
||||
}
|
||||
|
||||
column = columnMatch[1];
|
||||
path = path.slice(0, -columnMatch[0].length);
|
||||
|
||||
const lineMatch = path.match(/:(\d+)$/);
|
||||
if (lineMatch?.[1]) {
|
||||
line = lineMatch[1];
|
||||
path = path.slice(0, -lineMatch[0].length);
|
||||
} else {
|
||||
line = column;
|
||||
column = undefined;
|
||||
}
|
||||
|
||||
return { path, line, column };
|
||||
}
|
||||
|
||||
function stripLineColumnSuffix(value: string): string {
|
||||
const { path } = splitPathAndPosition(value);
|
||||
return path;
|
||||
}
|
||||
|
||||
function formatPathWithPosition(input: {
|
||||
readonly path: string;
|
||||
readonly line?: string;
|
||||
readonly column?: string;
|
||||
}): string {
|
||||
if (!input.line) {
|
||||
return input.path;
|
||||
}
|
||||
return `${input.path}:${input.line}${input.column ? `:${input.column}` : ""}`;
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
function defaultTranslateWslPathToWindows(target: string): string {
|
||||
const parsed = splitPathAndPosition(target);
|
||||
if (parsed.path.length === 0 || !parsed.path.startsWith("/") || isWindowsPath(parsed.path)) {
|
||||
return target;
|
||||
}
|
||||
|
||||
const result = spawnProcessSync("wslpath", ["-w", parsed.path], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
const detail = result.stderr.trim() || result.stdout.trim() || "wslpath failed";
|
||||
throw new Error(detail);
|
||||
}
|
||||
|
||||
const translatedPath = result.stdout.trim();
|
||||
if (translatedPath.length === 0) {
|
||||
throw new Error("wslpath returned an empty path");
|
||||
}
|
||||
|
||||
return formatPathWithPosition({
|
||||
path: translatedPath,
|
||||
...(parsed.line ? { line: parsed.line } : {}),
|
||||
...(parsed.column ? { column: parsed.column } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveOpenCommand(
|
||||
editorId: EditorId,
|
||||
options: ResolveOpenOptions,
|
||||
): ReadonlyArray<string> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === editorId);
|
||||
if (!editorDef) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (editorId === "file-manager") {
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return ["explorer.exe", "xdg-open"];
|
||||
}
|
||||
return [fileManagerCommandForPlatform(platform)];
|
||||
}
|
||||
|
||||
if (!editorDef.command) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
return [editorDef.command, `${editorDef.command}.exe`];
|
||||
}
|
||||
|
||||
return [editorDef.command];
|
||||
}
|
||||
|
||||
export function resolveBrowserLaunch(
|
||||
target: string,
|
||||
options: ResolveOpenOptions = {},
|
||||
): EditorLaunch | null {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||
if (isCommandAvailable("wslview", { platform, env })) {
|
||||
return { command: "wslview", args: [target] };
|
||||
}
|
||||
if (isCommandAvailable("explorer.exe", { platform, env })) {
|
||||
return { command: "explorer.exe", args: [target] };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
options: ResolveOpenOptions = {},
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
const translateWslPathToWindows = options.translateWslPathToWindows ?? defaultTranslateWslPathToWindows;
|
||||
|
||||
if (editorDef.command) {
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${editorDef.command}` });
|
||||
}
|
||||
|
||||
const usesWindowsPath = runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command.endsWith(".exe");
|
||||
const target = usesWindowsPath
|
||||
? yield* Effect.try({
|
||||
try: () => translateWslPathToWindows(input.cwd),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows editor launch",
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
: input.cwd;
|
||||
|
||||
return shouldUseGotoFlag(editorDef.id, target)
|
||||
? { command, args: ["--goto", target] }
|
||||
: { command, args: [target] };
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||
platform,
|
||||
env,
|
||||
runtimeEnvironment,
|
||||
});
|
||||
const command =
|
||||
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||
candidateCommands[0];
|
||||
if (!command) {
|
||||
return yield* new OpenError({ message: "Editor command not found: file-manager" });
|
||||
}
|
||||
|
||||
let target = stripLineColumnSuffix(input.cwd);
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
|
||||
target = yield* Effect.try({
|
||||
try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows file manager launch",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
return { command, args: [target] };
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
throw new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(
|
||||
new OpenError({ message: "failed to spawn detached process", cause: error }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await spawnDetachedProcess(launch.command, [...launch.args]);
|
||||
},
|
||||
catch: (cause) =>
|
||||
Schema.is(OpenError)(cause)
|
||||
? cause
|
||||
: new OpenError({ message: "failed to spawn detached process", cause }),
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
@@ -451,16 +264,11 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
openBrowser: (target) => {
|
||||
const launch = resolveBrowserLaunch(target);
|
||||
if (launch) {
|
||||
return launchDetached(launch);
|
||||
}
|
||||
return Effect.tryPromise({
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
});
|
||||
},
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
describe("runProcess", () => {
|
||||
it("fails when output exceeds max buffer in default mode", async () => {
|
||||
@@ -20,20 +20,4 @@ describe("runProcess", () => {
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
});
|
||||
|
||||
it("runs sync commands through the shared spawn strategy", () => {
|
||||
const result = spawnProcessSync("node", ["-e", "process.stdout.write('ok')"], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout).toBe("ok");
|
||||
});
|
||||
|
||||
it("spawns detached commands through the shared spawn strategy", async () => {
|
||||
await expect(
|
||||
spawnDetachedProcess(process.execPath, ["-e", "process.exit(0)"]),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,44 +1,4 @@
|
||||
import {
|
||||
type ChildProcess as ChildProcessHandle,
|
||||
type ChildProcessWithoutNullStreams,
|
||||
spawn,
|
||||
spawnSync,
|
||||
type StdioOptions,
|
||||
} from "node:child_process";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
import { Effect, Exit, Scope } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface ProcessSpawnBaseOptions {
|
||||
cwd?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface RuntimeShellOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | string | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||
stdio?: StdioOptions | undefined;
|
||||
detached?: boolean | undefined;
|
||||
encoding?: BufferEncoding | undefined;
|
||||
input?: string | undefined;
|
||||
}
|
||||
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -48,8 +8,6 @@ export interface ProcessRunOptions {
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
shell?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunResult {
|
||||
@@ -66,126 +24,6 @@ function commandLabel(command: string, args: readonly string[]): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function resolveRuntimeEnvironment(
|
||||
runtimeEnvironment: ServerRuntimeEnvironment | undefined,
|
||||
): ServerRuntimeEnvironment {
|
||||
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
}
|
||||
|
||||
function shouldUseShell(options: RuntimeShellOptions): boolean | string {
|
||||
if (options.shell !== undefined) {
|
||||
return options.shell;
|
||||
}
|
||||
|
||||
return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";
|
||||
}
|
||||
|
||||
function toSpawnOptions(options: ProcessSpawnOptions) {
|
||||
return {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function toRuntimeCommandOptions(
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.CommandOptions {
|
||||
return {
|
||||
...options,
|
||||
shell: options.shell ?? shouldUseShell(options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeRuntimeCommand(
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: RuntimeCommandOptions = {},
|
||||
): ChildProcess.StandardCommand {
|
||||
return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options));
|
||||
}
|
||||
|
||||
export interface ManagedChildProcess {
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly handle: ChildProcessSpawner.ChildProcessHandle;
|
||||
}
|
||||
|
||||
export const spawnManagedCommand = (command: ChildProcess.Command) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.make("sequential");
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const handle = yield* spawner.spawn(command).pipe(
|
||||
Scope.provide(scope),
|
||||
Effect.tapError(() => Scope.close(scope, Exit.void)),
|
||||
);
|
||||
|
||||
return {
|
||||
scope,
|
||||
handle,
|
||||
} satisfies ManagedChildProcess;
|
||||
});
|
||||
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnOptions = {},
|
||||
): ChildProcessHandle {
|
||||
return spawn(command, args, toSpawnOptions(options));
|
||||
}
|
||||
|
||||
export function spawnPipedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): ChildProcessWithoutNullStreams {
|
||||
return spawnProcess(command, args, {
|
||||
...options,
|
||||
stdio: "pipe",
|
||||
}) as ChildProcessWithoutNullStreams;
|
||||
}
|
||||
|
||||
export function spawnProcessSync(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessSpawnSyncOptions = {},
|
||||
) {
|
||||
return spawnSync(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: shouldUseShell(options),
|
||||
encoding: options.encoding ?? "utf8",
|
||||
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||
...(options.input !== undefined ? { input: options.input } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function spawnDetachedProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||
): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const child = spawnProcess(command, args, {
|
||||
...options,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resolve();
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (error) => {
|
||||
reject(normalizeSpawnError(command, args, error));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||
@@ -199,12 +37,8 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
function isWindowsCommandNotFound(
|
||||
code: number | null,
|
||||
stderr: string,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): boolean {
|
||||
if (resolveRuntimeEnvironment(runtimeEnvironment).platform !== "windows") return false;
|
||||
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
@@ -213,9 +47,8 @@ function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||
): Error {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr, runtimeEnvironment)) {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr)) {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
@@ -252,30 +85,11 @@ const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
export function killProcessTree(
|
||||
child: ChildProcessHandle,
|
||||
options: {
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||
signal?: NodeJS.Signals | undefined;
|
||||
} = {},
|
||||
): void {
|
||||
const signal = options.signal ?? "SIGTERM";
|
||||
if (
|
||||
resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows" &&
|
||||
child.pid !== undefined
|
||||
) {
|
||||
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
const result = spawnProcessSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
||||
stdio: "ignore",
|
||||
shell: false,
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
});
|
||||
if (!result.error && result.status === 0) {
|
||||
return;
|
||||
}
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
@@ -321,7 +135,12 @@ export async function runProcess(
|
||||
const outputMode = options.outputMode ?? "error";
|
||||
|
||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||
const child = spawnPipedProcess(command, args, options);
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
@@ -335,15 +154,9 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
killChild(child, "SIGTERM");
|
||||
forceKillTimer = setTimeout(() => {
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGKILL",
|
||||
});
|
||||
killChild(child, "SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -358,10 +171,7 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
killProcessTree(child, {
|
||||
runtimeEnvironment: options.runtimeEnvironment,
|
||||
signal: "SIGTERM",
|
||||
});
|
||||
killChild(child, "SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
@@ -434,7 +244,7 @@ export async function runProcess(
|
||||
|
||||
finalize(() => {
|
||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
||||
reject(normalizeExitError(command, args, result, options.runtimeEnvironment));
|
||||
reject(normalizeExitError(command, args, result));
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
|
||||
@@ -33,7 +33,6 @@ import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
|
||||
@@ -434,7 +433,6 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const services = yield* Effect.services<NodeServices.NodeServices>();
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
@@ -451,7 +449,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
if (options?.makeManager) {
|
||||
return options.makeManager();
|
||||
}
|
||||
return new CodexAppServerManager(services);
|
||||
return new CodexAppServerManager();
|
||||
}),
|
||||
(manager) =>
|
||||
Effect.sync(() => {
|
||||
@@ -589,25 +587,24 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Effect.gen(function* () {
|
||||
const writeNativeEvent = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
const orchestrationThreadId = yield* Effect.catch(
|
||||
directory
|
||||
.getThreadId(event.sessionId)
|
||||
.pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
directory.getThreadId(event.sessionId).pipe(
|
||||
Effect.map((threadIdOption) =>
|
||||
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||
),
|
||||
),
|
||||
() => Effect.succeed(null),
|
||||
);
|
||||
yield* nativeEventLogger.write(event, orchestrationThreadId);
|
||||
});
|
||||
|
||||
const services = yield* Effect.services<never>();
|
||||
const listener = (event: ProviderEvent) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
|
||||
@@ -1,63 +1,93 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { Effect, Layer, Sink, Stream } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
function mockRunner(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return (args: ReadonlyArray<string>) => Promise.resolve(handler(args));
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout)),
|
||||
stderr: Stream.make(encoder.encode(result.stderr)),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function failingRunner(description: string) {
|
||||
return () => Promise.reject(new Error(description));
|
||||
function mockSpawnerLayer(
|
||||
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const cmd = command as unknown as { args: ReadonlyArray<string> };
|
||||
return Effect.succeed(mockHandle(handler(cmd.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function failingSpawnerLayer(description: string) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
description,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when codex is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(failingRunner("spawn codex ENOENT"));
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
|
||||
}),
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -66,22 +96,25 @@ it.effect("returns unauthenticated when auth probe reports login required", () =
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
"returns unauthenticated when login status output includes 'not logged in'",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -90,21 +123,22 @@ it.effect(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
);
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status")
|
||||
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when login status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkCodexProviderStatus(
|
||||
mockRunner((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
);
|
||||
const status = yield* checkCodexProviderStatus;
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
@@ -113,7 +147,18 @@ it.effect("returns warning when login status command is unsupported", () =>
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
);
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "login status") {
|
||||
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// ── Pure function tests ─────────────────────────────────────────────
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Performs one-time provider readiness probes when the server starts and
|
||||
* keeps the resulting snapshot in memory for `server.getConfig`.
|
||||
*
|
||||
* Uses the shared process runner to run CLI probes natively.
|
||||
* Uses effect's ChildProcessSpawner to run CLI probes natively.
|
||||
*
|
||||
* @module ProviderHealthLive
|
||||
*/
|
||||
@@ -13,43 +13,20 @@ import type {
|
||||
ServerProviderStatus,
|
||||
ServerProviderStatusState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, Effect, Layer, Result } from "effect";
|
||||
import { Effect, Layer, Option, Result, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
|
||||
class ProviderHealthCommandError extends Data.TaggedError("ProviderHealthCommandError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
export interface CommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number;
|
||||
readonly timedOut?: boolean;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"message" in error &&
|
||||
typeof (error as { message?: unknown }).message === "string"
|
||||
) {
|
||||
return (error as { message: string }).message;
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
@@ -59,7 +36,8 @@ function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
}
|
||||
|
||||
function isCommandMissingCause(error: unknown): boolean {
|
||||
const lower = errorMessage(error).toLowerCase();
|
||||
if (!(error instanceof Error)) return false;
|
||||
const lower = error.message.toLowerCase();
|
||||
return (
|
||||
lower.includes("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
@@ -184,115 +162,140 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
};
|
||||
}
|
||||
|
||||
export type RunProviderHealthCommand = (
|
||||
args: ReadonlyArray<string>,
|
||||
) => Promise<CommandResult>;
|
||||
// ── Effect-native command execution ─────────────────────────────────
|
||||
|
||||
const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
|
||||
const result = await runProcess("codex", [...args], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
|
||||
Stream.runFold(
|
||||
stream,
|
||||
() => "",
|
||||
(acc, chunk) => acc + new TextDecoder().decode(chunk),
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
code: result.code ?? 0,
|
||||
timedOut: result.timedOut,
|
||||
} satisfies CommandResult;
|
||||
};
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("codex", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
const child = yield* spawner.spawn(command);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus = (
|
||||
runCodexCommand: RunProviderHealthCommand = defaultRunCodexCommand,
|
||||
): Effect.Effect<ServerProviderStatus> =>
|
||||
Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["--version"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(Effect.result);
|
||||
// Probe 1: `codex --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${errorMessage(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* Effect.tryPromise({
|
||||
try: () => runCodexCommand(["login", "status"]),
|
||||
catch: (error) =>
|
||||
new ProviderHealthCommandError({
|
||||
message: errorMessage(error),
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}).pipe(Effect.result);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
errorMessage(error).length > 0
|
||||
? `Could not verify Codex authentication status: ${errorMessage(error)}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success);
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
message: isCommandMissingCause(error)
|
||||
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Codex CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Codex CLI is installed but failed to run. ${detail}`
|
||||
: "Codex CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `codex login status` — is the user authenticated?
|
||||
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Codex authentication status: ${error.message}.`
|
||||
: "Could not verify Codex authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CODEX_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const codexStatus = yield* checkCodexProviderStatus();
|
||||
const codexStatus = yield* checkCodexProviderStatus;
|
||||
return {
|
||||
getStatuses: Effect.succeed([codexStatus]),
|
||||
} satisfies ProviderHealthShape;
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
describe("detectServerRuntimeEnvironment", () => {
|
||||
it("detects native windows mode", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "win32",
|
||||
env: {},
|
||||
osRelease: "10.0.26100",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from environment variables", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {
|
||||
WSL_DISTRO_NAME: "Ubuntu-24.04",
|
||||
WSL_INTEROP: "/run/WSL/123_interop",
|
||||
},
|
||||
osRelease: "6.6.87.2-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu-24.04",
|
||||
});
|
||||
});
|
||||
|
||||
it("detects wsl-hosted mode from os release when env is unavailable", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "linux",
|
||||
env: {},
|
||||
osRelease: "5.15.167.4-microsoft-standard-WSL2",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves non-wsl posix hosts outside the windows interop modes", () => {
|
||||
expect(
|
||||
detectServerRuntimeEnvironment({
|
||||
platform: "darwin",
|
||||
env: {},
|
||||
osRelease: "24.3.0",
|
||||
}),
|
||||
).toEqual({
|
||||
platform: "macos",
|
||||
pathStyle: "posix",
|
||||
isWsl: false,
|
||||
windowsInteropMode: null,
|
||||
wslDistroName: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
import os from "node:os";
|
||||
|
||||
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||
|
||||
interface DetectServerRuntimeEnvironmentOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly osRelease?: string;
|
||||
}
|
||||
|
||||
function normalizePlatform(platform: NodeJS.Platform): ServerRuntimeEnvironment["platform"] {
|
||||
switch (platform) {
|
||||
case "win32":
|
||||
return "windows";
|
||||
case "darwin":
|
||||
return "macos";
|
||||
default:
|
||||
return "linux";
|
||||
}
|
||||
}
|
||||
|
||||
function detectWsl(options: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly osRelease: string;
|
||||
}): boolean {
|
||||
if (options.platform !== "linux") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.env.WSL_DISTRO_NAME || options.env.WSL_INTEROP) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return options.osRelease.toLowerCase().includes("microsoft");
|
||||
}
|
||||
|
||||
export function detectServerRuntimeEnvironment(
|
||||
options: DetectServerRuntimeEnvironmentOptions = {},
|
||||
): ServerRuntimeEnvironment {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const osRelease = options.osRelease ?? os.release();
|
||||
const normalizedPlatform = normalizePlatform(platform);
|
||||
const isWsl = detectWsl({ platform, env, osRelease });
|
||||
|
||||
return {
|
||||
platform: normalizedPlatform,
|
||||
pathStyle: normalizedPlatform === "windows" ? "windows" : "posix",
|
||||
isWsl,
|
||||
windowsInteropMode: normalizedPlatform === "windows" ? "windows-native" : isWsl ? "wsl-hosted" : null,
|
||||
wslDistroName: isWsl ? env.WSL_DISTRO_NAME?.trim() || null : null,
|
||||
};
|
||||
}
|
||||
@@ -38,7 +38,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | NodeServices.NodeServices
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
|
||||
@@ -4,7 +4,6 @@ import path from "node:path";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -17,11 +16,7 @@ import {
|
||||
type PtyProcess,
|
||||
type PtySpawnInput,
|
||||
} from "../Services/PTY";
|
||||
import {
|
||||
resolveShellCandidates,
|
||||
TerminalManagerRuntime,
|
||||
validateTerminalCwdForRuntime,
|
||||
} from "./Manager";
|
||||
import { TerminalManagerRuntime } from "./Manager";
|
||||
import { Effect, Encoding } from "effect";
|
||||
|
||||
class FakePtyProcess implements PtyProcess {
|
||||
@@ -177,7 +172,6 @@ describe("TerminalManager", () => {
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -192,7 +186,6 @@ describe("TerminalManager", () => {
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.runtimeEnvironment ? { runtimeEnvironment: options.runtimeEnvironment } : {}),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
@@ -676,93 +669,4 @@ describe("TerminalManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("resolves Windows shell candidates from runtime environment instead of host assumptions", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "/bin/bash -l", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("cmd.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).not.toContain("/bin/sh");
|
||||
});
|
||||
|
||||
it("resolves POSIX shell candidates for wsl-hosted runtime even when the requested shell is Windows-style", () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
|
||||
const candidates = resolveShellCandidates(() => "powershell.exe", runtimeEnvironment);
|
||||
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("/bin/bash");
|
||||
expect(candidates.map((candidate) => candidate.shell)).toContain("sh");
|
||||
});
|
||||
|
||||
it("rejects POSIX cwd values for windows-native terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "/home/julius/project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match Windows runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rejects Windows cwd values for wsl-hosted terminal runtimes", async () => {
|
||||
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
};
|
||||
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||
|
||||
await expect(manager.open(openInput({ cwd: "C:\\Users\\julius\\project" }))).rejects.toThrow(
|
||||
"Terminal cwd does not match POSIX runtime path style",
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("validates cwd compatibility as a pure runtime helper", () => {
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("/repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
validateTerminalCwdForRuntime("\\\\wsl.localhost\\Ubuntu\\repo", {
|
||||
platform: "linux",
|
||||
pathStyle: "posix",
|
||||
isWsl: true,
|
||||
windowsInteropMode: "wsl-hosted",
|
||||
wslDistroName: "Ubuntu",
|
||||
}),
|
||||
).toContain("POSIX runtime path style");
|
||||
});
|
||||
});
|
||||
@@ -9,14 +9,12 @@ import {
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalWriteInput,
|
||||
type ServerRuntimeEnvironment,
|
||||
type TerminalEvent,
|
||||
type TerminalSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Encoding, Layer, Path, Schema } from "effect";
|
||||
|
||||
import { createLogger } from "../../logger";
|
||||
import { detectServerRuntimeEnvironment } from "../../runtimeEnvironment";
|
||||
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { ServerConfig } from "../../config";
|
||||
@@ -37,8 +35,6 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
|
||||
const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||
|
||||
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
|
||||
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
|
||||
@@ -48,22 +44,19 @@ const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
function defaultShellResolver(runtimeEnvironment: ServerRuntimeEnvironment): string {
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
function defaultShellResolver(): string {
|
||||
if (process.platform === "win32") {
|
||||
return process.env.ComSpec ?? "cmd.exe";
|
||||
}
|
||||
return process.env.SHELL ?? "bash";
|
||||
}
|
||||
|
||||
function normalizeShellCommand(
|
||||
value: string | undefined,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): string | null {
|
||||
function normalizeShellCommand(value: string | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
if (process.platform === "win32") {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
@@ -72,13 +65,10 @@ function normalizeShellCommand(
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function shellCandidateFromCommand(
|
||||
command: string | null,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
): ShellCandidate | null {
|
||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
||||
if (!command || command.length === 0) return null;
|
||||
const shellName = path.basename(command).toLowerCase();
|
||||
if (runtimeEnvironment.platform !== "windows" && shellName === "zsh") {
|
||||
if (process.platform !== "win32" && shellName === "zsh") {
|
||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
||||
}
|
||||
return { shell: command };
|
||||
@@ -102,36 +92,27 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
|
||||
return ordered;
|
||||
}
|
||||
|
||||
export function resolveShellCandidates(
|
||||
shellResolver: () => string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(
|
||||
normalizeShellCommand(shellResolver(), runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
);
|
||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
||||
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
if (process.platform === "win32") {
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null, runtimeEnvironment),
|
||||
shellCandidateFromCommand("powershell.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand("cmd.exe", runtimeEnvironment),
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
||||
shellCandidateFromCommand("powershell.exe"),
|
||||
shellCandidateFromCommand("cmd.exe"),
|
||||
]);
|
||||
}
|
||||
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(
|
||||
normalizeShellCommand(process.env.SHELL, runtimeEnvironment),
|
||||
runtimeEnvironment,
|
||||
),
|
||||
shellCandidateFromCommand("/bin/zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("/bin/sh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("zsh", runtimeEnvironment),
|
||||
shellCandidateFromCommand("bash", runtimeEnvironment),
|
||||
shellCandidateFromCommand("sh", runtimeEnvironment),
|
||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
||||
shellCandidateFromCommand("/bin/zsh"),
|
||||
shellCandidateFromCommand("/bin/bash"),
|
||||
shellCandidateFromCommand("/bin/sh"),
|
||||
shellCandidateFromCommand("zsh"),
|
||||
shellCandidateFromCommand("bash"),
|
||||
shellCandidateFromCommand("sh"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -197,13 +178,6 @@ async function checkWindowsSubprocessActivity(terminalPid: number): Promise<bool
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
runtimeEnvironment: {
|
||||
platform: "windows",
|
||||
pathStyle: "windows",
|
||||
isWsl: false,
|
||||
windowsInteropMode: "windows-native",
|
||||
wslDistroName: null,
|
||||
},
|
||||
},
|
||||
);
|
||||
return result.code === 0;
|
||||
@@ -256,37 +230,14 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
|
||||
}
|
||||
}
|
||||
|
||||
function createDefaultSubprocessChecker(runtimeEnvironment: ServerRuntimeEnvironment) {
|
||||
return async (terminalPid: number): Promise<boolean> => {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (runtimeEnvironment.platform === "windows") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
};
|
||||
}
|
||||
|
||||
function isWindowsPath(value: string): boolean {
|
||||
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||
}
|
||||
|
||||
export function validateTerminalCwdForRuntime(
|
||||
cwd: string,
|
||||
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||
): string | null {
|
||||
if (runtimeEnvironment.pathStyle === "windows") {
|
||||
if (cwd.startsWith("/")) {
|
||||
return `Terminal cwd does not match Windows runtime path style: ${cwd}`;
|
||||
}
|
||||
return null;
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isWindowsPath(cwd)) {
|
||||
return `Terminal cwd does not match POSIX runtime path style: ${cwd}`;
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return null;
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
@@ -365,7 +316,6 @@ interface TerminalManagerOptions {
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -383,7 +333,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistDebounceMs: number;
|
||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||
private readonly runtimeEnvironment: ServerRuntimeEnvironment;
|
||||
private readonly subprocessPollIntervalMs: number;
|
||||
private readonly processKillGraceMs: number;
|
||||
private readonly maxRetainedInactiveSessions: number;
|
||||
@@ -394,15 +343,12 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
|
||||
constructor(options: TerminalManagerOptions) {
|
||||
super();
|
||||
this.runtimeEnvironment = options.runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
|
||||
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||
this.ptyAdapter = options.ptyAdapter;
|
||||
this.shellResolver =
|
||||
options.shellResolver ?? (() => defaultShellResolver(this.runtimeEnvironment));
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker =
|
||||
options.subprocessChecker ?? createDefaultSubprocessChecker(this.runtimeEnvironment);
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
@@ -643,7 +589,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver, this.runtimeEnvironment);
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
@@ -1105,11 +1051,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
}
|
||||
|
||||
private async assertValidCwd(cwd: string): Promise<void> {
|
||||
const runtimePathError = validateTerminalCwdForRuntime(cwd, this.runtimeEnvironment);
|
||||
if (runtimePathError) {
|
||||
throw new Error(runtimePathError);
|
||||
}
|
||||
|
||||
let stats: fs.Stats;
|
||||
try {
|
||||
stats = await fs.promises.stat(cwd);
|
||||
@@ -1232,11 +1173,10 @@ export const TerminalManagerLive = Layer.effect(
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
const { join } = yield* Path.Path;
|
||||
const logsDir = join(stateDir, "logs", "terminals");
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const ptyAdapter = yield* PtyAdapter;
|
||||
const runtime = yield* Effect.acquireRelease(
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter, runtimeEnvironment })),
|
||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
|
||||
(r) => Effect.sync(() => r.dispose()),
|
||||
);
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
|
||||
interface PendingMessages {
|
||||
queue: unknown[];
|
||||
@@ -86,8 +85,6 @@ const defaultProviderHealthService: ProviderHealthShape = {
|
||||
getStatuses: Effect.succeed(defaultProviderStatuses),
|
||||
};
|
||||
|
||||
const defaultRuntimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
@@ -763,7 +760,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -790,7 +786,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
|
||||
@@ -827,7 +822,6 @@ describe("WebSocket Server", () => {
|
||||
],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||
@@ -863,7 +857,6 @@ describe("WebSocket Server", () => {
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
providers: ReadonlyArray<ServerProviderStatus>;
|
||||
availableEditors: unknown;
|
||||
runtimeEnvironment: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||
@@ -884,7 +877,6 @@ describe("WebSocket Server", () => {
|
||||
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
||||
expect(result.providers).toEqual(defaultProviderStatuses);
|
||||
expectAvailableEditors(result.availableEditors);
|
||||
expect(result.runtimeEnvironment).toEqual(defaultRuntimeEnvironment);
|
||||
});
|
||||
|
||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||
@@ -985,7 +977,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -1034,7 +1025,6 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
|
||||
@@ -59,7 +59,6 @@ import { Open, resolveAvailableEditors } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
@@ -197,7 +196,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
autoBootstrapProjectFromCwd,
|
||||
} = serverConfig;
|
||||
const availableEditors = resolveAvailableEditors();
|
||||
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||
|
||||
const gitManager = yield* GitManager;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
@@ -747,7 +745,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
issues: keybindingsConfig.issues,
|
||||
providers: providerStatuses,
|
||||
availableEditors,
|
||||
runtimeEnvironment,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
|
||||
@@ -63,11 +63,18 @@ import {
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatMessage,
|
||||
type Thread,
|
||||
type TurnDiffFileChange,
|
||||
type TurnDiffSummary,
|
||||
} from "../types";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import {
|
||||
buildTurnDiffTree,
|
||||
normalizeFilePath,
|
||||
summarizeTurnDiffStats,
|
||||
type TurnDiffTreeNode,
|
||||
} from "../lib/turnDiffTree";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import GitActionsControl from "./GitActionsControl";
|
||||
import {
|
||||
@@ -333,6 +340,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
theme: "light" | "dark";
|
||||
className?: string;
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
const iconUrl = useMemo(
|
||||
@@ -343,9 +351,9 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
|
||||
if (failed) {
|
||||
return props.kind === "directory" ? (
|
||||
<FolderIcon className="size-4 text-muted-foreground/80" />
|
||||
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
) : (
|
||||
<FileIcon className="size-4 text-muted-foreground/80" />
|
||||
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -354,7 +362,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0"
|
||||
className={cn("size-4 shrink-0", props.className)}
|
||||
loading="lazy"
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
@@ -2547,6 +2555,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
resolvedTheme={resolvedTheme}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -3126,6 +3135,153 @@ const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: stri
|
||||
);
|
||||
});
|
||||
|
||||
function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean {
|
||||
return stat.additions > 0 || stat.deletions > 0;
|
||||
}
|
||||
|
||||
const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}) {
|
||||
const { additions, deletions } = props;
|
||||
return (
|
||||
<>
|
||||
<span className="text-success">+{additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{deletions}</span>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
|
||||
const paths: string[] = [];
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== "directory") continue;
|
||||
paths.push(node.path);
|
||||
paths.push(...collectDirectoryPaths(node.children));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
function buildDirectoryExpansionState(
|
||||
directoryPaths: ReadonlyArray<string>,
|
||||
expanded: boolean,
|
||||
): Record<string, boolean> {
|
||||
const expandedState: Record<string, boolean> = {};
|
||||
for (const directoryPath of directoryPaths) {
|
||||
expandedState[directoryPath] = expanded;
|
||||
}
|
||||
return expandedState;
|
||||
}
|
||||
|
||||
const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
turnId: TurnId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
|
||||
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
|
||||
const directoryPathsKey = useMemo(() => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes]);
|
||||
const allDirectoryExpansionState = useMemo(
|
||||
() =>
|
||||
buildDirectoryExpansionState(
|
||||
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
|
||||
allDirectoriesExpanded,
|
||||
),
|
||||
[allDirectoriesExpanded, directoryPathsKey],
|
||||
);
|
||||
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(
|
||||
() => buildDirectoryExpansionState((directoryPathsKey ? directoryPathsKey.split("\u0000") : []), true),
|
||||
);
|
||||
useEffect(() => {
|
||||
setExpandedDirectories(allDirectoryExpansionState);
|
||||
}, [allDirectoryExpansionState]);
|
||||
|
||||
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
|
||||
setExpandedDirectories((current) => ({
|
||||
...current,
|
||||
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
|
||||
const leftPadding = 8 + depth * 14;
|
||||
if (node.kind === "directory") {
|
||||
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
|
||||
return (
|
||||
<div key={`dir:${node.path}`}>
|
||||
<button
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => toggleDirectory(node.path, depth === 0)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
|
||||
isExpanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
{isExpanded ? (
|
||||
<FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
|
||||
) : (
|
||||
<FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
|
||||
)}
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
|
||||
{node.name}
|
||||
</span>
|
||||
{hasNonZeroStat(node.stat) && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div className="space-y-0.5">
|
||||
{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
key={`file:${node.path}`}
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => onOpenTurnDiff(turnId, node.path)}
|
||||
>
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
<VscodeEntryIcon
|
||||
pathValue={node.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
className="size-3.5 text-muted-foreground/70"
|
||||
/>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
|
||||
{node.name}
|
||||
</span>
|
||||
{node.stat && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
{treeNodes.map((node) => renderTreeNode(node, 0))}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
interface MessagesTimelineProps {
|
||||
hasMessages: boolean;
|
||||
isWorking: boolean;
|
||||
@@ -3145,6 +3301,7 @@ interface MessagesTimelineProps {
|
||||
isRevertingCheckpoint: boolean;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
markdownCwd: string | undefined;
|
||||
resolvedTheme: "light" | "dark";
|
||||
}
|
||||
|
||||
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
|
||||
@@ -3199,6 +3356,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isRevertingCheckpoint,
|
||||
onImageExpand,
|
||||
markdownCwd,
|
||||
resolvedTheme,
|
||||
}: MessagesTimelineProps) {
|
||||
const rows = useMemo<TimelineRow[]>(() => {
|
||||
const nextRows: TimelineRow[] = [];
|
||||
@@ -3339,6 +3497,15 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
|
||||
const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
|
||||
Record<string, boolean>
|
||||
>({});
|
||||
const onToggleAllDirectories = useCallback((turnId: TurnId) => {
|
||||
setAllDirectoriesExpandedByTurnId((current) => ({
|
||||
...current,
|
||||
[turnId]: !(current[turnId] ?? true),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const renderRowContent = (row: TimelineRow) => (
|
||||
<div className="pb-4">
|
||||
@@ -3507,81 +3674,58 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
if (!turnSummary) return null;
|
||||
const checkpointFiles = turnSummary.files;
|
||||
if (checkpointFiles.length === 0) return null;
|
||||
const summaryStat = checkpointFiles.reduce(
|
||||
(acc, file) => {
|
||||
if (
|
||||
typeof file.additions !== "number" ||
|
||||
typeof file.deletions !== "number"
|
||||
) {
|
||||
return acc;
|
||||
}
|
||||
return {
|
||||
additions: acc.additions + file.additions,
|
||||
deletions: acc.deletions + file.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const changedFileCountLabel = String(checkpointFiles.length);
|
||||
const allDirectoriesExpanded =
|
||||
allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<span className="text-success">+{summaryStat.additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{summaryStat.deletions}</span>
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
deletions={summaryStat.deletions}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{checkpointFiles.map((file) => (
|
||||
<button
|
||||
key={`${turnSummary.turnId}:${file.path}`}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
|
||||
>
|
||||
{(() => {
|
||||
const stat =
|
||||
typeof file.additions === "number" &&
|
||||
typeof file.deletions === "number"
|
||||
? {
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
}
|
||||
: null;
|
||||
if (!stat) {
|
||||
return file.path;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<span>{file.path}</span>
|
||||
<span className="ml-1 text-muted-foreground/70">(</span>
|
||||
<span className="text-success">+{stat.additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{stat.deletions}</span>
|
||||
<span className="text-muted-foreground/70">)</span>
|
||||
</>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
const rawPath = checkpointFiles[0]?.path;
|
||||
onOpenTurnDiff(
|
||||
turnSummary.turnId,
|
||||
rawPath ? normalizeFilePath(rawPath) : undefined,
|
||||
);
|
||||
})()}
|
||||
</button>
|
||||
))}
|
||||
}}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildTurnDiffTree, summarizeTurnDiffStats } from "./turnDiffTree";
|
||||
|
||||
describe("summarizeTurnDiffStats", () => {
|
||||
it("sums only files with numeric additions/deletions", () => {
|
||||
const stat = summarizeTurnDiffStats([
|
||||
{ path: "README.md", additions: 3, deletions: 1 },
|
||||
{ path: "docs/notes.md" },
|
||||
{ path: "src/index.ts", additions: 5, deletions: 2 },
|
||||
]);
|
||||
|
||||
expect(stat).toEqual({ additions: 8, deletions: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTurnDiffTree", () => {
|
||||
it("builds nested directory nodes with aggregated stats", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "src/index.ts", additions: 2, deletions: 1 },
|
||||
{ path: "src/components/Button.tsx", additions: 4, deletions: 2 },
|
||||
{ path: "README.md", additions: 1, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "src",
|
||||
path: "src",
|
||||
stat: { additions: 6, deletions: 3 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "components",
|
||||
path: "src/components",
|
||||
stat: { additions: 4, deletions: 2 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "Button.tsx",
|
||||
path: "src/components/Button.tsx",
|
||||
stat: { additions: 4, deletions: 2 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "README.md",
|
||||
path: "README.md",
|
||||
stat: { additions: 1, deletions: 0 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps files without stat values and excludes them from directory totals", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "docs/notes.md" },
|
||||
{ path: "docs/todo.md", additions: 1, deletions: 1 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "docs",
|
||||
path: "docs",
|
||||
stat: { additions: 1, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "notes.md",
|
||||
path: "docs/notes.md",
|
||||
stat: null,
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "todo.md",
|
||||
path: "docs/todo.md",
|
||||
stat: { additions: 1, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes file paths with windows separators", () => {
|
||||
const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps/web/src",
|
||||
path: "apps/web/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/web/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("compacts only single-directory chains and stops at branch points", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "apps/server/src/index.ts", additions: 2, deletions: 1 },
|
||||
{ path: "apps/server/main.ts", additions: 4, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps/server",
|
||||
path: "apps/server",
|
||||
stat: { additions: 6, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "src",
|
||||
path: "apps/server/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/server/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "main.ts",
|
||||
path: "apps/server/main.ts",
|
||||
stat: { additions: 4, deletions: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves leading/trailing whitespace in path segments", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "a/file.ts", additions: 1, deletions: 0 },
|
||||
{ path: " a/file.ts", additions: 2, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toHaveLength(2);
|
||||
const directoryNodes = tree.filter(
|
||||
(node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",
|
||||
);
|
||||
expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);
|
||||
expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { TurnDiffFileChange } from "../types";
|
||||
|
||||
export interface TurnDiffStat {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
export interface TurnDiffTreeDirectoryNode {
|
||||
kind: "directory";
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat;
|
||||
children: TurnDiffTreeNode[];
|
||||
}
|
||||
|
||||
export interface TurnDiffTreeFileNode {
|
||||
kind: "file";
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat | null;
|
||||
}
|
||||
|
||||
export type TurnDiffTreeNode = TurnDiffTreeDirectoryNode | TurnDiffTreeFileNode;
|
||||
|
||||
interface MutableDirectoryNode {
|
||||
name: string;
|
||||
path: string;
|
||||
stat: TurnDiffStat;
|
||||
directories: Map<string, MutableDirectoryNode>;
|
||||
files: TurnDiffTreeFileNode[];
|
||||
}
|
||||
|
||||
const SORT_LOCALE_OPTIONS: Intl.CollatorOptions = { numeric: true, sensitivity: "base" };
|
||||
|
||||
function normalizePathSegments(pathValue: string): string[] {
|
||||
return pathValue
|
||||
.replaceAll("\\", "/")
|
||||
.split("/")
|
||||
.filter((segment) => segment.length > 0);
|
||||
}
|
||||
|
||||
export function normalizeFilePath(pathValue: string): string {
|
||||
return normalizePathSegments(pathValue).join("/");
|
||||
}
|
||||
|
||||
function compareByName(a: { name: string }, b: { name: string }): number {
|
||||
return a.name.localeCompare(b.name, undefined, SORT_LOCALE_OPTIONS);
|
||||
}
|
||||
|
||||
function readStat(file: TurnDiffFileChange): TurnDiffStat | null {
|
||||
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
};
|
||||
}
|
||||
|
||||
function compactDirectoryNode(node: TurnDiffTreeDirectoryNode): TurnDiffTreeDirectoryNode {
|
||||
const compactedChildren = node.children.map((child) =>
|
||||
child.kind === "directory" ? compactDirectoryNode(child) : child,
|
||||
);
|
||||
|
||||
let compactedNode: TurnDiffTreeDirectoryNode = {
|
||||
...node,
|
||||
children: compactedChildren,
|
||||
};
|
||||
|
||||
while (compactedNode.children.length === 1 && compactedNode.children[0]?.kind === "directory") {
|
||||
const onlyChild = compactedNode.children[0];
|
||||
compactedNode = {
|
||||
kind: "directory",
|
||||
name: `${compactedNode.name}/${onlyChild.name}`,
|
||||
path: onlyChild.path,
|
||||
stat: onlyChild.stat,
|
||||
children: onlyChild.children,
|
||||
};
|
||||
}
|
||||
|
||||
return compactedNode;
|
||||
}
|
||||
|
||||
function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
|
||||
const subdirectories: TurnDiffTreeDirectoryNode[] = Array.from(directory.directories.values())
|
||||
.toSorted(compareByName)
|
||||
.map<TurnDiffTreeDirectoryNode>((subdirectory) => ({
|
||||
kind: "directory",
|
||||
name: subdirectory.name,
|
||||
path: subdirectory.path,
|
||||
stat: {
|
||||
additions: subdirectory.stat.additions,
|
||||
deletions: subdirectory.stat.deletions,
|
||||
},
|
||||
children: toTreeNodes(subdirectory),
|
||||
}))
|
||||
.map((subdirectory) => compactDirectoryNode(subdirectory));
|
||||
|
||||
const files = directory.files.toSorted(compareByName);
|
||||
return [...subdirectories, ...files];
|
||||
}
|
||||
|
||||
export function summarizeTurnDiffStats(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffStat {
|
||||
return files.reduce(
|
||||
(acc, file) => {
|
||||
const stat = readStat(file);
|
||||
if (!stat) return acc;
|
||||
return {
|
||||
additions: acc.additions + stat.additions,
|
||||
deletions: acc.deletions + stat.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
}
|
||||
|
||||
export function buildTurnDiffTree(files: ReadonlyArray<TurnDiffFileChange>): TurnDiffTreeNode[] {
|
||||
const root: MutableDirectoryNode = {
|
||||
name: "",
|
||||
path: "",
|
||||
stat: { additions: 0, deletions: 0 },
|
||||
directories: new Map(),
|
||||
files: [],
|
||||
};
|
||||
|
||||
for (const file of files) {
|
||||
const segments = normalizePathSegments(file.path);
|
||||
if (segments.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const filePath = segments.join("/");
|
||||
const fileName = segments.at(-1);
|
||||
if (!fileName) {
|
||||
continue;
|
||||
}
|
||||
const stat = readStat(file);
|
||||
const ancestors: MutableDirectoryNode[] = [root];
|
||||
let currentDirectory = root;
|
||||
|
||||
for (const segment of segments.slice(0, -1)) {
|
||||
const nextPath = currentDirectory.path ? `${currentDirectory.path}/${segment}` : segment;
|
||||
const existing = currentDirectory.directories.get(segment);
|
||||
if (existing) {
|
||||
currentDirectory = existing;
|
||||
} else {
|
||||
const created: MutableDirectoryNode = {
|
||||
name: segment,
|
||||
path: nextPath,
|
||||
stat: { additions: 0, deletions: 0 },
|
||||
directories: new Map(),
|
||||
files: [],
|
||||
};
|
||||
currentDirectory.directories.set(segment, created);
|
||||
currentDirectory = created;
|
||||
}
|
||||
ancestors.push(currentDirectory);
|
||||
}
|
||||
|
||||
currentDirectory.files.push({
|
||||
kind: "file",
|
||||
name: fileName,
|
||||
path: filePath,
|
||||
stat,
|
||||
});
|
||||
|
||||
if (stat) {
|
||||
for (const ancestor of ancestors) {
|
||||
ancestor.stat.additions += stat.additions;
|
||||
ancestor.stat.deletions += stat.deletions;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return toTreeNodes(root);
|
||||
}
|
||||
@@ -49,24 +49,6 @@ export type ServerProviderStatus = typeof ServerProviderStatus.Type;
|
||||
export const ServerProviderStatuses = Schema.Array(ServerProviderStatus);
|
||||
export type ServerProviderStatuses = typeof ServerProviderStatuses.Type;
|
||||
|
||||
export const ServerRuntimePlatform = Schema.Literals(["windows", "linux", "macos"]);
|
||||
export type ServerRuntimePlatform = typeof ServerRuntimePlatform.Type;
|
||||
|
||||
export const ServerPathStyle = Schema.Literals(["windows", "posix"]);
|
||||
export type ServerPathStyle = typeof ServerPathStyle.Type;
|
||||
|
||||
export const ServerWindowsInteropMode = Schema.Literals(["windows-native", "wsl-hosted"]);
|
||||
export type ServerWindowsInteropMode = typeof ServerWindowsInteropMode.Type;
|
||||
|
||||
export const ServerRuntimeEnvironment = Schema.Struct({
|
||||
platform: ServerRuntimePlatform,
|
||||
pathStyle: ServerPathStyle,
|
||||
isWsl: Schema.Boolean,
|
||||
windowsInteropMode: Schema.NullOr(ServerWindowsInteropMode),
|
||||
wslDistroName: Schema.NullOr(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ServerRuntimeEnvironment = typeof ServerRuntimeEnvironment.Type;
|
||||
|
||||
export const ServerConfig = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
keybindingsConfigPath: TrimmedNonEmptyString,
|
||||
@@ -74,7 +56,6 @@ export const ServerConfig = Schema.Struct({
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
availableEditors: Schema.Array(EditorId),
|
||||
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||
});
|
||||
export type ServerConfig = typeof ServerConfig.Type;
|
||||
|
||||
|
||||
Reference in new issue
Block a user