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
This commit is contained in:
1 parent
870d6943ed
commit
aae0832ccb
4 files changed
+277
-63
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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),
|
||||
@@ -850,6 +836,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
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(
|
||||
Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe(
|
||||
Scope.provide(context.scope),
|
||||
@@ -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()),
|
||||
|
||||
@@ -354,7 +354,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
let target = stripLineColumnSuffix(input.cwd);
|
||||
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
|
||||
target = yield* Effect.try({
|
||||
try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
|
||||
try: () => translateWslPathToWindows(target),
|
||||
catch: (cause) =>
|
||||
new OpenError({
|
||||
message: "Failed to translate WSL path for Windows file manager launch",
|
||||
|
||||
@@ -267,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,
|
||||
@@ -344,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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user