Skip to content
TypeScript

fix(server): clear Codex commands when their native thread closes (#19936)

Itay Avraham Cohen45bcde1441e0
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 49c3e53375a..0c99652a302 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -4973,6 +4973,134 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ it.effect.each([false, true])(
+ "keeps commands interrupted after native thread closure (persistent tool: %s)",
+ (retainContext) =>
+ Effect.gen(function* () {
+ const notification = (method: string, params: unknown) => ({
+ type: "emit_inbound" as const,
+ label: method,
+ frame: { method, params },
+ });
+ const monitor = (status: "inProgress" | "completed") =>
+ notification(status === "inProgress" ? "item/started" : "item/completed", {
+ threadId: BG_NATIVE_THREAD,
+ turnId: BG_NATIVE_TURN,
+ item: {
+ type: "dynamicToolCall",
+ id: "persistent-monitor",
+ namespace: "grok",
+ tool: "monitor",
+ status,
+ arguments: { persistent: true, command: "tail -f" },
+ },
+ });
+ // Replies fence notification handling on the same protocol reader.
+ const unsubscribe = (id: number, notifications: ReturnType<typeof notification>[] = []) => [
+ {
+ type: "expect_outbound" as const,
+ label: `unsubscribe-${id}`,
+ frame: { id, method: "thread/unsubscribe", params: { threadId: BG_NATIVE_THREAD } },
+ },
+ ...notifications,
+ {
+ type: "emit_inbound" as const,
+ label: `unsubscribe-result-${id}`,
+ frame: { id, result: { status: "notSubscribed" } },
+ },
+ ];
+ const closed = notification("thread/closed", { threadId: BG_NATIVE_THREAD });
+ const transcript = makeCodexReplayTranscript({
+ scenario: `codex-background-thread-closed-${retainContext}`,
+ entries: [
+ ...backgroundExecTranscript.entries.slice(0, -2),
+ ...(retainContext ? [monitor("inProgress")] : []),
+ backgroundExecTranscript.entries.at(-2)!,
+ ...unsubscribe(4),
+ ...unsubscribe(5, [notification("thread/closed", { threadId: "unrelated-thread" })]),
+ ...unsubscribe(6, [closed]),
+ ...unsubscribe(7, [
+ closed,
+ notification("item/completed", {
+ threadId: BG_NATIVE_THREAD,
+ turnId: BG_NATIVE_TURN,
+ item: backgroundCommandItem("completed"),
+ }),
+ ...(retainContext ? [monitor("completed")] : []),
+ ]),
+ ],
+ });
+ const interrupted = yield* Deferred.make<void>();
+ const monitorCompleted = yield* Deferred.make<void>();
+ const harness = yield* makeCodexReplayHarness(transcript, (event) => {
+ if (event.type !== "turn_item.updated") return Effect.void;
+ if (
+ event.turnItem.nativeItemRef?.nativeId === BG_COMMAND_ITEM &&
+ event.turnItem.status === "interrupted"
+ ) {
+ return Deferred.succeed(interrupted, undefined);
+ }
+ return event.turnItem.nativeItemRef?.nativeId === "persistent-monitor" &&
+ event.turnItem.status === "completed"
+ ? Deferred.succeed(monitorCompleted, undefined)
+ : Effect.void;
+ });
+ yield* harness.runtime.startTurn(
+ makeCodexTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-codex-thread-closed"),
+ text: BG_PROMPT,
+ }),
+ );
+ yield* harness.firstTerminal;
+ const unload = harness.runtime.unloadThread!({ providerThread: harness.providerThread });
+ yield* unload;
+ assert.isTrue(yield* harness.hasPendingBackgroundWork);
+ yield* unload;
+ assert.isTrue(yield* harness.hasPendingBackgroundWork);
+ yield* unload;
+ assert.equal(yield* harness.hasPendingBackgroundWork, retainContext);
+ yield* Deferred.await(interrupted);
+ yield* unload;
+ if (retainContext) yield* Deferred.await(monitorCompleted);
+ assert.deepEqual(
+ {
+ items: harness.events.flatMap((event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId === BG_COMMAND_ITEM
+ ? [event.turnItem.status]
+ : [],
+ ),
+ nodes: harness.events.flatMap((event) =>
+ event.type === "node.updated" &&
+ event.node.nativeItemRef?.nativeId === BG_COMMAND_ITEM
+ ? [event.node.status]
+ : [],
+ ),
+ roots: harness.terminalEvents().map((event) => event.status),
+ continuations: harness.continuationRequests.length,
+ },
+ {
+ items: ["running", "interrupted"],
+ nodes: ["running", "interrupted"],
+ roots: ["completed"],
+ continuations: 0,
+ },
+ );
+ assert.isFalse(yield* harness.hasPendingBackgroundWork);
+ assert.isFalse(
+ yield* harness.runtime.hasPendingBackgroundWorkForThread!(harness.providerThread),
+ );
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
const backgroundStopCases = [true, false, "still_running", "thread_unloaded"] as const;
const makeBackgroundStopTranscript = (terminated: (typeof backgroundStopCases)[number]) => {
const stillRunning = terminated === "still_running";
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index 5664fdb230d..5df2960ab16 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -1137,6 +1137,7 @@ function codexUsageLimitError(
}
interface ActiveCodexTurnContext {
+ closedCommandItemIds?: ReadonlySet<string>;
latestProviderFailure?: {
readonly nativeMessage: string;
readonly failure: OrchestrationV2ProviderFailure;
@@ -4674,6 +4675,35 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
});
});
+ // Unloading an idle thread kills its terminals without completing
+ // their command items, while the shared provider session stays alive.
+ yield* client.handleServerNotification("thread/closed", (payload) =>
+ Effect.gen(function* () {
+ const completedAt = yield* DateTime.now;
+ for (const context of (yield* Ref.get(settledTurns)).values()) {
+ if (context.providerThread.nativeThreadRef?.nativeId !== payload.threadId) continue;
+ const commands = (yield* Ref.get(runningCommandItemsByTurn)).get(
+ context.nativeTurnId,
+ );
+ if (commands !== undefined) {
+ context.closedCommandItemIds = new Set(commands.keys());
+ }
+ yield* terminalizeRunningCommandItems(
+ context,
+ context.nativeTurnId,
+ "interrupted",
+ completedAt,
+ );
+ yield* Ref.update(runningCommandItemsByTurn, (current) => {
+ const updated = new Map(current);
+ updated.delete(context.nativeTurnId);
+ return updated;
+ });
+ yield* releaseSettledTurnIfIdle(context.nativeTurnId);
+ }
+ }).pipe(Effect.orDie, turnTerminalizationPermit.withPermits(1)),
+ );
+
yield* client.handleServerNotification("item/started", (payload) =>
Effect.gen(function* () {
const context = yield* awaitActiveTurn(payload.turnId);
@@ -4858,6 +4888,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
}
if (payload.item.type === "commandExecution") {
+ // Other tools can retain the context after thread closure.
+ if (context.closedCommandItemIds?.has(payload.item.id)) return;
const turnDrained = yield* clearRunningCommandItem(payload.turnId, payload.item.id);
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
yield* emitProviderEvent({