Compare commits

..
Author SHA1 Message Date
Julius Marminge aae0832ccb Harden Codex session shutdown and WSL interop handling
- Guard writes when app-server stdin is unavailable
- Close session scopes reliably on unexpected exits and during stopAll
- Stream stderr by line and make managed command spawn uninterruptible
- Fix explorer.exe WSL path translation to preserve valid Windows targets
2026-03-05 17:41:55 -08:00
Julius Marminge 870d6943ed Run Windows batch launchers via shell and harden test cleanup
- Launch Windows .bat/.cmd wrappers directly with `shell` set to COMSPEC to preserve argument/path handling (including spaced paths)
- Update process runner tests to cover the new Windows launch behavior
- Add `removeDirectoryBestEffort` and use it in integration/tests to reduce flaky temp-dir cleanup failures
2026-03-05 16:14:36 -08:00
Julius Marminge e5cea81fea Harden server tests for Windows and WSL interop
- make fake codex test launcher cross-platform (`.cmd` + Node script, PATH delimiter aware)
- stabilize git/integration temp repo behavior (`core.autocrlf=false`, retrying `rmSync` cleanup)
- remove OS-fragile assertions in CLI, keybindings, and terminal manager tests
2026-03-05 14:50:56 -08:00
12 changed files with 508 additions and 203 deletions

No files matched your search

@@ -57,6 +57,7 @@ import {
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { ServerConfig } from "../src/config.ts";
import { removeDirectoryBestEffort } from "../src/testUtils/removeDirectoryBestEffort.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -70,6 +71,7 @@ function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
runGit(cwd, ["config", "core.autocrlf", "false"]);
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
@@ -387,9 +389,7 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
Effect.promise(() => removeDirectoryBestEffort(rootDir)),
),
);
});
+154 -2
View File
@@ -1,6 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Cause } from "effect";
import { ManagedRuntime, ServiceMap } from "effect";
import { Cause, Effect, ManagedRuntime, ServiceMap } from "effect";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ProviderSessionId } from "@t3tools/contracts";
@@ -103,6 +102,58 @@ function createThreadControlHarness() {
return { manager, context, requireSession, sendRequest, updateSession };
}
function createMinimalSessionContext(sessionId = asSessionId("sess_1")) {
return {
session: {
sessionId,
provider: "codex",
status: "ready",
threadId: "thread_1",
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
child: {
stdin: {},
isRunning: Effect.succeed(true),
},
scope: {},
scopeClosePromise: null,
pending: new Map(),
pendingApprovals: new Map(),
nextRequestId: 1,
stopping: false,
} as unknown as {
session: {
sessionId: ProviderSessionId;
provider: "codex";
status: "ready" | "closed";
threadId: string;
createdAt: string;
updatedAt: string;
activeTurnId?: string;
lastError?: string;
};
child: {
stdin: unknown;
isRunning: Effect.Effect<boolean, never>;
};
scope: unknown;
scopeClosePromise: Promise<void> | null;
pending: Map<
string,
{
method: string;
timeout: ReturnType<typeof setTimeout>;
resolve: (value: unknown) => void;
reject: (error: Error) => void;
}
>;
pendingApprovals: Map<string, unknown>;
nextRequestId: number;
stopping: boolean;
};
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -186,6 +237,107 @@ describe("constructor", () => {
});
});
describe("session lifecycle guards", () => {
it("rejects writes when the codex process is not running", async () => {
const manager = createManager();
const context = createMinimalSessionContext();
context.child.isRunning = Effect.succeed(false);
const runPromise = vi
.spyOn(manager as unknown as { runPromise: (...args: unknown[]) => Promise<unknown> }, "runPromise")
.mockResolvedValue(false);
await expect(
(
manager as unknown as { writeMessage: (ctx: unknown, message: unknown) => Promise<void> }
).writeMessage(context, {
method: "initialized",
}),
).rejects.toThrow("Cannot write to codex app-server stdin.");
expect(runPromise).toHaveBeenCalledTimes(1);
});
it("closes session scope on unexpected process exit", async () => {
const manager = createManager();
const context = createMinimalSessionContext();
const pendingReject = vi.fn();
context.pending.set("1", {
method: "thread/start",
timeout: setTimeout(() => undefined, 1000),
resolve: () => undefined,
reject: pendingReject,
});
(
manager as unknown as {
sessions: Map<ProviderSessionId, unknown>;
}
).sessions.set(context.session.sessionId, context);
const runPromise = vi
.spyOn(manager as unknown as { runPromise: (...args: unknown[]) => Promise<unknown> }, "runPromise")
.mockResolvedValue(undefined);
await (
manager as unknown as {
handleUnexpectedProcessExit: (
ctx: unknown,
outcome: { kind: "failure"; message: string } | { kind: "exit"; code: number },
) => Promise<void>;
}
).handleUnexpectedProcessExit(context, { kind: "exit", code: 1 });
expect(pendingReject).toHaveBeenCalledWith(
expect.objectContaining({
message: "Session terminated before request completed.",
}),
);
expect(context.session.status).toBe("closed");
expect(context.session.lastError).toBe("codex app-server exited (code=1).");
expect(runPromise).toHaveBeenCalledTimes(1);
expect(
(
manager as unknown as {
sessions: Map<ProviderSessionId, unknown>;
}
).sessions.has(context.session.sessionId),
).toBe(false);
});
it("waits for active scope closes before disposing owned runtime", async () => {
const manager = new CodexAppServerManager();
const context = createMinimalSessionContext();
(
manager as unknown as {
sessions: Map<ProviderSessionId, unknown>;
}
).sessions.set(context.session.sessionId, context);
let resolveClose: (() => void) | undefined;
const closePromise = new Promise<void>((resolve) => {
resolveClose = resolve;
});
vi.spyOn(
manager as unknown as { runPromise: (...args: unknown[]) => Promise<unknown> },
"runPromise",
).mockReturnValue(closePromise);
const ownedRuntime = (
manager as unknown as {
ownedRuntime: { dispose: () => Promise<void> } | null;
}
).ownedRuntime;
if (!ownedRuntime) {
throw new Error("Expected manager to own a runtime.");
}
const disposeSpy = vi.spyOn(ownedRuntime, "dispose").mockResolvedValue(undefined);
manager.stopAll();
expect(disposeSpy).not.toHaveBeenCalled();
resolveClose?.();
await closePromise;
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(disposeSpy).toHaveBeenCalledTimes(1);
});
});
describe("startSession", () => {
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = createManager();
+97 -46
View File
@@ -44,6 +44,7 @@ interface CodexSessionContext {
session: ProviderSession;
child: ChildProcessSpawner.ChildProcessHandle;
scope: Scope.Closeable;
scopeClosePromise: Promise<void> | null;
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
nextRequestId: number;
@@ -164,6 +165,7 @@ export interface CodexAppServerManagerEvents {
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
private readonly pendingScopeCloses = new Set<Promise<void>>();
private readonly ownedRuntime:
| ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, unknown>
| null;
@@ -222,6 +224,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
session,
child: managedProcess.handle,
scope: managedProcess.scope,
scopeClosePromise: null,
pending: new Map(),
pendingApprovals: new Map(),
nextRequestId: 1,
@@ -494,14 +497,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
context.stopping = true;
for (const pending of context.pending.values()) {
clearTimeout(pending.timeout);
pending.reject(new Error("Session stopped before request completed."));
}
context.pending.clear();
this.rejectPendingRequests(context, "Session stopped before request completed.");
context.pendingApprovals.clear();
void this.runPromise(Scope.close(context.scope, Exit.void)).catch(() => undefined);
void this.closeSessionScope(context);
this.updateSession(context, {
status: "closed",
@@ -527,7 +525,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (this.ownedRuntime) {
void this.ownedRuntime.dispose();
const pendingScopeCloses = Array.from(this.pendingScopeCloses);
const closeComplete =
pendingScopeCloses.length > 0
? Promise.allSettled(pendingScopeCloses).then(() => undefined)
: Promise.resolve();
void closeComplete.finally(() => {
void this.ownedRuntime?.dispose();
});
}
}
@@ -557,17 +562,14 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
);
yield* Effect.forkScoped(
Stream.runForEach(Stream.decodeText(context.child.stderr), (raw) =>
Stream.runForEach(Stream.splitLines(Stream.decodeText(context.child.stderr)), (rawLine) =>
Effect.sync(() => {
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);
const classified = classifyCodexStderrLine(rawLine);
if (!classified) {
return;
}
this.emitErrorEvent(context, "process/stderr", classified.message);
}),
),
);
@@ -575,35 +577,19 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
yield* Effect.forkScoped(
Effect.matchCauseEffect(context.child.exitCode, {
onFailure: (cause) =>
Effect.sync(() => {
if (context.stopping) {
return;
}
const message = messageFromCodexProcessCause(cause);
this.updateSession(context, {
status: "error",
activeTurnId: undefined,
lastError: message,
});
this.emitErrorEvent(context, "process/error", message);
this.sessions.delete(context.session.sessionId);
}),
Effect.promise(() =>
this.handleUnexpectedProcessExit(context, {
kind: "failure",
message: messageFromCodexProcessCause(cause),
}),
),
onSuccess: (code) =>
Effect.sync(() => {
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);
}),
Effect.promise(() =>
this.handleUnexpectedProcessExit(context, {
kind: "exit",
code,
}),
),
}),
);
}.bind(this),
@@ -847,7 +833,13 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
private async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {
const encoded = JSON.stringify(message);
if (context.stopping || !this.sessions.has(context.session.sessionId)) {
if (context.stopping) {
throw new Error("Cannot write to codex app-server stdin.");
}
const isRunning = await this.runPromise(
context.child.isRunning.pipe(Effect.catch(() => Effect.succeed(false))),
);
if (!isRunning) {
throw new Error("Cannot write to codex app-server stdin.");
}
await this.runPromise(
@@ -857,6 +849,65 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
);
}
private rejectPendingRequests(context: CodexSessionContext, message: string): void {
for (const pending of context.pending.values()) {
clearTimeout(pending.timeout);
pending.reject(new Error(message));
}
context.pending.clear();
}
private closeSessionScope(context: CodexSessionContext): Promise<void> {
if (context.scopeClosePromise) {
return context.scopeClosePromise;
}
const closePromise = this.runPromise(Scope.close(context.scope, Exit.void))
.catch(() => undefined)
.finally(() => {
if (context.scopeClosePromise === closePromise) {
context.scopeClosePromise = null;
}
this.pendingScopeCloses.delete(closePromise);
});
context.scopeClosePromise = closePromise;
this.pendingScopeCloses.add(closePromise);
return closePromise;
}
private async handleUnexpectedProcessExit(
context: CodexSessionContext,
outcome: { kind: "failure"; message: string } | { kind: "exit"; code: number },
): Promise<void> {
if (context.stopping) {
return;
}
context.stopping = true;
this.rejectPendingRequests(context, "Session terminated before request completed.");
context.pendingApprovals.clear();
if (outcome.kind === "failure") {
this.updateSession(context, {
status: "error",
activeTurnId: undefined,
lastError: outcome.message,
});
this.emitErrorEvent(context, "process/error", outcome.message);
} else {
const message = `codex app-server exited (code=${outcome.code}).`;
this.updateSession(context, {
status: "closed",
activeTurnId: undefined,
lastError: outcome.code === 0 ? context.session.lastError : message,
});
this.emitLifecycleEvent(context, "session/exited", message);
}
this.sessions.delete(context.session.sessionId);
await this.closeSessionScope(context);
}
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
@@ -19,56 +19,78 @@ function makeFakeCodexBinary(dir: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const codexPath = path.join(binDir, "codex");
const launcherPath = path.join(binDir, process.platform === "win32" ? "codex.cmd" : "codex");
const scriptPath = path.join(binDir, "codex.cjs");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* fs.writeFileString(
codexPath,
scriptPath,
[
"#!/bin/sh",
'output_path=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
" shift",
' if [ -n "$1" ]; then',
' seen_image="1"',
" fi",
" continue",
" fi",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
" fi",
" shift",
"done",
'stdin_content="$(cat)"',
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
" exit 2",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 3",
'const fs = require("node:fs");',
"",
"async function readStdin() {",
" const chunks = [];",
" for await (const chunk of process.stdin) {",
" chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));",
" }",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "stdin contained forbidden content" >&2',
" exit 4",
" fi",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
"fi",
'if [ -n "$output_path" ]; then',
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
"fi",
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
' return Buffer.concat(chunks).toString("utf8");',
"}",
"",
"(async () => {",
' let outputPath = "";',
" let seenImage = false;",
" for (let index = 2; index < process.argv.length; index += 1) {",
" const arg = process.argv[index];",
' if (arg === "--image") {',
" const imagePath = process.argv[index + 1];",
" if (imagePath) {",
" seenImage = true;",
" index += 1;",
" }",
" continue;",
" }",
' if (arg === "--output-last-message") {',
' outputPath = process.argv[index + 1] ?? "";',
" index += 1;",
" }",
" }",
" const stdinContent = await readStdin();",
' if (process.env.T3_FAKE_CODEX_REQUIRE_IMAGE === "1" && !seenImage) {',
' process.stderr.write("missing --image input\\n");',
" process.exit(2);",
" }",
" const mustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;",
' if (mustContain && !stdinContent.includes(mustContain)) {',
' process.stderr.write("stdin missing expected content\\n");',
" process.exit(3);",
" }",
" const mustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;",
' if (mustNotContain && stdinContent.includes(mustNotContain)) {',
' process.stderr.write("stdin contained forbidden content\\n");',
" process.exit(4);",
" }",
" if (process.env.T3_FAKE_CODEX_STDERR) {",
' process.stderr.write(`${process.env.T3_FAKE_CODEX_STDERR}\\n`);',
" }",
" if (outputPath) {",
' fs.writeFileSync(outputPath, Buffer.from(process.env.T3_FAKE_CODEX_OUTPUT_B64 ?? "e30=", "base64"));',
" }",
' process.exit(Number(process.env.T3_FAKE_CODEX_EXIT_CODE ?? "0"));',
"})().catch((error) => {",
' process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);',
" process.exit(1);",
"});",
"",
].join("\n"),
);
yield* fs.chmod(codexPath, 0o755);
yield* fs.writeFileString(
launcherPath,
process.platform === "win32"
? `@echo off\r\n"${process.execPath}" "${scriptPath}" %*\r\n`
: `#!/bin/sh\nexec "${process.execPath}" "${scriptPath}" "$@"\n`,
);
yield* fs.chmod(launcherPath, 0o755);
return binDir;
});
}
@@ -96,9 +118,11 @@ function withFakeCodexEnv<A, E, R>(
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
const pathDelimiter = process.platform === "win32" ? ";" : ":";
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.PATH =
previousPath && previousPath.length > 0 ? `${binDir}${pathDelimiter}${previousPath}` : binDir;
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
if (input.exitCode !== undefined) {
+25 -39
View File
@@ -1,17 +1,19 @@
import { existsSync } from "node:fs";
import { existsSync, mkdtempSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect, vi } from "vitest";
import { Effect, FileSystem, Layer, PlatformError } from "effect";
import { afterEach, describe, expect, vi } from "vitest";
import { GitServiceLive } from "./GitService.ts";
import { GitService, type GitServiceShape } from "../Services/GitService.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
import { GitCommandError } from "../Errors.ts";
import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
import { runProcess } from "../../processRunner.ts";
import { removeDirectoryBestEffort } from "../../testUtils/removeDirectoryBestEffort.ts";
// ── Helpers ──
@@ -21,13 +23,20 @@ const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitServiceTestLayer, GitCoreTestLayer);
const tempDirs = new Set<string>();
function makeTmpDir(
prefix = "git-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
afterEach(async () => {
for (const dir of tempDirs) {
await removeDirectoryBestEffort(dir);
}
tempDirs.clear();
});
function makeTmpDir(prefix = "git-test-"): Effect.Effect<string> {
return Effect.sync(() => {
const dir = mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.add(dir);
return dir;
});
}
@@ -60,31 +69,6 @@ function git(
});
}
function runShellCommand(input: {
command: string;
cwd: string;
timeoutMs?: number;
maxOutputBytes?: number;
}): Effect.Effect<ProcessRunResult, Error> {
return Effect.promise(() => {
const shellPath =
process.platform === "win32"
? (process.env.ComSpec ?? "cmd.exe")
: (process.env.SHELL ?? "/bin/sh");
const args =
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
return runProcess(shellPath, args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? 30_000,
allowNonZeroExit: true,
maxBufferBytes: input.maxOutputBytes ?? 1_000_000,
outputMode: "truncate",
});
});
}
const makeIsolatedGitCore = (gitService: GitServiceShape) =>
Effect.promise(async () => {
const gitServiceLayer = Layer.succeed(GitService, gitService);
@@ -182,6 +166,7 @@ function initRepoWithCommit(
yield* initGitRepo({ cwd });
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* git(cwd, ["config", "core.autocrlf", "false"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
@@ -215,12 +200,13 @@ function commitWithDate(
it.layer(TestLayer)("git integration", (it) => {
describe("shell process execution", () => {
it.effect("caps captured output when maxOutputBytes is exceeded", () =>
Effect.gen(function* () {
const result = yield* runShellCommand({
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
Effect.promise(async () => {
const result = await runProcess(process.execPath, ["-e", "process.stdout.write('x'.repeat(2000))"], {
cwd: process.cwd(),
timeoutMs: 10_000,
maxOutputBytes: 128,
allowNonZeroExit: true,
maxBufferBytes: 128,
outputMode: "truncate",
});
expect(result.code).toBe(0);
+45 -20
View File
@@ -17,22 +17,46 @@ import {
} from "./keybindings";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const makeKeybindingsLayer = () =>
KeybindingsLive.pipe(
Layer.provideMerge(
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
const configPath = join(dir, "keybindings.json");
return { keybindingsConfigPath: configPath } as ServerConfigShape;
}),
),
),
const makeKeybindingsLayer = (options?: {
readonly fileSystemLayer?: Layer.Layer<FileSystem.FileSystem>;
}) => {
const serverConfigLayer = Layer.effect(
ServerConfig,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
const configPath = join(dir, "keybindings.json");
return { keybindingsConfigPath: configPath } as ServerConfigShape;
}),
);
return options?.fileSystemLayer
? KeybindingsLive.pipe(
Layer.provideMerge(options.fileSystemLayer),
Layer.provideMerge(serverConfigLayer),
)
: KeybindingsLive.pipe(Layer.provideMerge(serverConfigLayer));
};
const makeTempWriteFailingFileSystemLayer = () =>
Layer.effect(
FileSystem.FileSystem,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return {
...fs,
writeFileString: ((filePath: string, ...args: [string, ...unknown[]]) =>
filePath.endsWith(".tmp")
? Effect.fail(new Error("simulated temp write failure"))
: (fs.writeFileString as (...allArgs: [string, ...unknown[]]) => ReturnType<typeof fs.writeFileString>)(
filePath,
...args,
)) as typeof fs.writeFileString,
} satisfies typeof fs;
}),
).pipe(Layer.provide(NodeServices.layer));
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
effect.pipe(
Effect.mapError((error) => error.detail),
@@ -392,13 +416,10 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
it.effect("fails when config directory is not writable", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { keybindingsConfigPath } = yield* ServerConfig;
const { dirname } = yield* Path.Path;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+j", command: "terminal.toggle" },
]);
yield* fs.chmod(dirname(keybindingsConfigPath), 0o500);
const result = yield* Effect.gen(function* () {
const keybindings = yield* Keybindings;
@@ -409,12 +430,16 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(toDetailResult);
assertFailure(result, "failed to write keybindings config");
yield* fs.chmod(dirname(keybindingsConfigPath), 0o700);
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [{ key: "mod+j", command: "terminal.toggle" }]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
}).pipe(
Effect.provide(
makeKeybindingsLayer({
fileSystemLayer: makeTempWriteFailingFileSystemLayer(),
}),
),
),
);
it.effect("caches loaded resolved config across repeated reads", () =>
+4 -2
View File
@@ -1,4 +1,5 @@
import * as Http from "node:http";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, vi } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
@@ -25,6 +26,7 @@ const serverStart = Effect.acquireRelease(
() => Effect.sync(() => stop()),
);
const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred));
const resolveExpectedStateDir = (value: string) => path.resolve(value);
// Shared service layer used by this CLI test suite.
const testLayer = Layer.mergeAll(
@@ -100,7 +102,7 @@ it.layer(testLayer)("server cli", (it) => {
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4010);
assert.equal(resolvedConfig?.host, "0.0.0.0");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state");
assert.equal(resolvedConfig?.stateDir, resolveExpectedStateDir("/tmp/t3-cli-state"));
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "auth-secret");
@@ -135,7 +137,7 @@ it.layer(testLayer)("server cli", (it) => {
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4999);
assert.equal(resolvedConfig?.host, "100.88.10.4");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state");
assert.equal(resolvedConfig?.stateDir, resolveExpectedStateDir("/tmp/t3-env-state"));
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "env-token");
@@ -38,6 +38,7 @@ import {
} from "../../provider/Services/ProviderService.ts";
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
import { removeDirectoryBestEffort } from "../../testUtils/removeDirectoryBestEffort.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
@@ -155,6 +156,7 @@ function createGitRepository() {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
runGit(cwd, ["config", "core.autocrlf", "false"]);
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
@@ -209,7 +211,7 @@ describe("CheckpointReactor", () => {
while (tempDirs.length > 0) {
const dir = tempDirs.pop();
if (dir) {
fs.rmSync(dir, { recursive: true, force: true });
await removeDirectoryBestEffort(dir);
}
}
});
+38 -9
View File
@@ -102,10 +102,9 @@ describe("resolveProcessLaunchPlan", () => {
},
});
expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(plan.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]);
expect(plan.args[3]).toBe(`"${wrapperPath}" "C:\\repo\\a&b.ts"`);
expect(plan.shell).toBe(false);
expect(plan.command).toBe(wrapperPath);
expect(plan.args).toEqual(["C:\\repo\\a&b.ts"]);
expect(plan.shell).toBe("C:\\Windows\\System32\\cmd.exe");
});
});
@@ -130,8 +129,38 @@ describe("resolveProcessLaunchPlan", () => {
},
});
expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(plan.args[3]).toBe(`"${wrapperPath}" "pkg@^1.0"`);
expect(plan.command).toBe(wrapperPath);
expect(plan.args).toEqual(["pkg@^1.0"]);
expect(plan.shell).toBe("C:\\Windows\\System32\\cmd.exe");
});
});
it("preserves spaced batch launcher paths on windows", () => {
withTempDir((rootDir) => {
const dir = path.join(rootDir, "runner admin");
fs.mkdirSync(dir);
const wrapperPath = path.join(dir, "code.CMD");
fs.writeFileSync(wrapperPath, "@echo off\r\n");
const plan = resolveProcessLaunchPlan("code", ["--status"], {
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
COMSPEC: "C:\\Windows\\System32\\cmd.exe",
},
inheritParentEnv: false,
runtimeEnvironment: {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
},
});
expect(plan.command).toBe(wrapperPath);
expect(plan.args).toEqual(["--status"]);
expect(plan.shell).toBe("C:\\Windows\\System32\\cmd.exe");
});
});
@@ -191,9 +220,9 @@ describe("makeRuntimeCommand", () => {
},
});
expect(command.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(command.args).toEqual(["/d", "/s", "/c", `"${wrapperPath}" "C:\\repo\\a&b.ts"`]);
expect(command.options.shell).toBe(false);
expect(command.command).toBe(wrapperPath);
expect(command.args).toEqual(["C:\\repo\\a&b.ts"]);
expect(command.options.shell).toBe("C:\\Windows\\System32\\cmd.exe");
});
});
});
+29 -37
View File
@@ -164,25 +164,6 @@ function resolveWindowsCommand(
return null;
}
function quoteWindowsBatchArgument(argument: string): string {
if (argument.length === 0) {
return '""';
}
const escaped = argument
.replaceAll("%", "%%")
.replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`)
.replace(/(\\+)$/g, "$1$1");
return `"${escaped}"`;
}
function buildWindowsBatchCommandLine(
command: string,
args: ReadonlyArray<string>,
): string {
return [quoteWindowsBatchArgument(command), ...args.map(quoteWindowsBatchArgument)].join(" ");
}
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? process.env.ComSpec ?? process.env.COMSPEC ?? "cmd.exe";
}
@@ -224,9 +205,9 @@ export function resolveProcessLaunchPlan(
if (resolved.kind === "batch") {
return {
command: resolveWindowsCommandShell(env),
args: ["/d", "/s", "/c", buildWindowsBatchCommandLine(resolved.path, args)],
shell: false,
command: resolved.path,
args: [...args],
shell: resolveWindowsCommandShell(env),
runtimeEnvironment,
};
}
@@ -286,19 +267,21 @@ interface ManagedChildProcess {
}
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)),
);
Effect.uninterruptible(
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;
});
return {
scope,
handle,
} satisfies ManagedChildProcess;
}),
);
function spawnProcess(
command: string,
@@ -363,15 +346,24 @@ export function spawnDetachedProcess(
stdio: "ignore",
});
const cleanup = () => {
child.off("spawn", handleSpawn);
child.off("error", handleError);
};
const handleSpawn = () => {
cleanup();
child.unref();
resolve();
};
child.once("spawn", handleSpawn);
child.once("error", (error) => {
const handleError = (error: Error) => {
cleanup();
reject(normalizeSpawnError(command, args, error));
});
};
child.once("spawn", handleSpawn);
child.once("error", handleError);
});
}
@@ -575,7 +575,9 @@ describe("TerminalManager", () => {
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell");
expect(ptyAdapter.spawnInputs[0]?.shell).toBe(
process.platform === "win32" ? "/definitely/missing-shell -l" : "/definitely/missing-shell",
);
if (process.platform === "win32") {
expect(
@@ -0,0 +1,40 @@
import fs from "node:fs";
const RETRYABLE_REMOVE_ERROR_CODES = new Set(["EBUSY", "ENOTEMPTY", "EPERM"]);
function isRetryableRemoveError(error: unknown): boolean {
if (!error || typeof error !== "object") {
return false;
}
const code = "code" in error ? error.code : undefined;
return typeof code === "string" && RETRYABLE_REMOVE_ERROR_CODES.has(code);
}
export async function removeDirectoryBestEffort(
dir: string,
options?: {
readonly maxRetries?: number;
readonly retryDelayMs?: number;
},
): Promise<void> {
const maxRetries = options?.maxRetries ?? 20;
const retryDelayMs = options?.retryDelayMs ?? 100;
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
try {
fs.rmSync(dir, { recursive: true, force: true });
return;
} catch (error) {
if (!isRetryableRemoveError(error)) {
throw error;
}
if (attempt === maxRetries) {
return;
}
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
}
}
}