diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 58214ab95b380..57d5e1928c8d4 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8088,6 +8088,340 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + const awaitedRosters = ( + events: ReadonlyArray, + providerThreadId: OrchestrationV2ProviderThread["id"], + ) => + events.flatMap((event) => + event.type === "provider_thread.updated" && + event.providerThread.id === providerThreadId && + event.providerThread.pendingBackgroundTasks !== undefined + ? [event.providerThread.pendingBackgroundTasks.map((task) => task.taskId)] + : [], + ); + + it.effect( + "lists a command the agent marks awaited, by session id or item id, until it ends", + () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + { + ...backgroundExecTranscript, + entries: backgroundExecTranscript.entries.map((entry) => + entry.type === "emit_inbound" && entry.label === "item/completed/command-late" + ? { ...entry, afterMs: 0 } + : entry, + ), + }, + undefined, + undefined, + undefined, + (entry) => + entry.label === "item/completed/command-late" ? Deferred.await(released) : Effect.void, + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-command-background-wait"), + text: BG_PROMPT, + }); + yield* harness.runtime.startTurn(turnInput); + yield* harness.firstTerminal; + const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; + if (awaitBackgroundTasks === undefined) { + return yield* Effect.die("Codex adapter runtime must expose awaitBackgroundTasks."); + } + const rosters = () => awaitedRosters(harness.events, harness.providerThread.id); + + // Codex shows the agent the terminal's session id; T3 knows the item id. + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["4242", "9999"], + awaited: true, + }), + { matched: ["4242"] }, + ); + yield* harness.until(() => rosters().length === 1); + const listed = harness.events.findLast((event) => event.type === "provider_thread.updated"); + assert.deepEqual( + listed?.type === "provider_thread.updated" + ? listed.providerThread.pendingBackgroundTasks + : undefined, + [ + { + taskId: BG_COMMAND_ITEM, + kind: "command", + command: BG_COMMAND, + description: BG_COMMAND, + runId: turnInput.runId, + awaited: true, + }, + ], + ); + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [BG_COMMAND_ITEM], + awaited: false, + }), + { matched: [BG_COMMAND_ITEM] }, + ); + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [BG_COMMAND_ITEM], + awaited: true, + }); + yield* harness.until(() => rosters().length === 3); + + yield* Deferred.succeed(released, undefined); + yield* harness.until(() => rosters().length === 4); + assert.deepEqual(rosters(), [[BG_COMMAND_ITEM], [], [BG_COMMAND_ITEM], []]); + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["4242"], + awaited: true, + }), + { matched: [] }, + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("lists an awaited command's end after a later turn starts from an older snapshot", () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + const entries = backgroundExecTranscript.entries; + const late = entries.at(-1); + const turnStart = entries.filter( + (entry) => entry.type !== "runtime_exit" && entry.label === "turn/start", + ); + const turnStarted = entries.find( + (entry) => entry.type !== "runtime_exit" && entry.label === "turn/started", + ); + if (late === undefined || turnStart.length !== 2 || turnStarted === undefined) { + return yield* Effect.die("The background exec transcript changed shape."); + } + const NEXT_TURN = "native-codex-bg-turn-2"; + const nextTurn = JSON.parse( + JSON.stringify([...turnStart, turnStarted]) + .replaceAll('"id":3', '"id":5') + .replaceAll(`"${BG_NATIVE_TURN}"`, `"${NEXT_TURN}"`), + ) as Array; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-bg-roster-after-next-turn", + entries: [ + ...entries.slice(0, -1), + { + type: "expect_outbound", + label: "list-background-terminals", + frame: { + id: 4, + method: "thread/backgroundTerminals/list", + params: { threadId: BG_NATIVE_THREAD }, + }, + }, + { + type: "emit_inbound", + label: "list-background-terminals", + frame: { id: 4, result: { data: [{ processId: "4242" }], nextCursor: null } }, + }, + ...nextTurn, + { + type: "emit_inbound", + label: "turn/completed/next", + frame: { + method: "turn/completed", + params: { + threadId: BG_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: NEXT_TURN, status: "completed" }), + }, + }, + }, + { ...late, afterMs: 0 } as CodexReplay.CodexAppServerReplayEntry, + ], + }), + undefined, + undefined, + undefined, + (entry) => + entry.label === "item/completed/command-late" ? Deferred.await(released) : Effect.void, + ); + const startTurn = (attempt: string) => + Effect.flatMap(DateTime.now, (now) => + harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(attempt), + text: BG_PROMPT, + }), + ), + ); + const rosters = () => awaitedRosters(harness.events, harness.providerThread.id); + yield* startTurn("attempt-roster-first"); + yield* harness.firstTerminal; + yield* harness.runtime.awaitBackgroundTasks!({ + providerThread: harness.providerThread, + taskIds: ["4242"], + awaited: true, + }); + yield* harness.until(() => rosters().length === 1); + // The next turn's input predates the roster published above. + yield* startTurn("attempt-roster-next"); + yield* harness.until(() => harness.terminalEvents().length === 2); + + yield* Deferred.succeed(released, undefined); + yield* harness.until(() => rosters().length === 2); + assert.deepEqual(rosters(), [[BG_COMMAND_ITEM], []]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + // A command that waited on approval starts without a process id; Codex sends it on completion. + it.effect("resolves the session id of an approved command Codex started without one", () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + const [started, answer, turnCompleted, late] = backgroundExecTranscript.entries.slice(-4); + const liveTerminal = (id: number) => [ + { + type: "expect_outbound" as const, + label: `list-background-terminals-${id}`, + frame: { + id, + method: "thread/backgroundTerminals/list", + params: { threadId: BG_NATIVE_THREAD }, + }, + }, + { + type: "emit_inbound" as const, + label: `list-background-terminals-${id}`, + frame: { + id, + result: { + data: [ + { + processId: "4242", + itemId: BG_COMMAND_ITEM, + command: BG_COMMAND, + cwd: "/workspace", + }, + ], + nextCursor: null, + }, + }, + }, + ]; + if ( + started?.type !== "emit_inbound" || + late?.type !== "emit_inbound" || + answer === undefined || + turnCompleted === undefined + ) { + return yield* Effect.die("The background exec transcript changed shape."); + } + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-bg-approved-command", + entries: [ + ...backgroundExecTranscript.entries.slice(0, -4), + { + ...started, + frame: { + method: "item/started", + params: { + item: { + ...backgroundCommandItem("inProgress"), + processId: null, + source: "agent", + }, + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + startedAtMs: 1782622440500, + }, + }, + }, + ...liveTerminal(4), + answer, + turnCompleted, + ...liveTerminal(5), + { ...late, afterMs: 0 }, + ], + }), + undefined, + undefined, + undefined, + (entry) => + entry.label === "item/completed/command-late" ? Deferred.await(released) : Effect.void, + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-approved-command-wait"), + text: BG_PROMPT, + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "command_execution", + ), + ); + const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; + if (awaitBackgroundTasks === undefined) { + return yield* Effect.die("Codex adapter runtime must expose awaitBackgroundTasks."); + } + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["4242"], + awaited: true, + }), + { matched: ["4242"] }, + ); + yield* harness.firstTerminal; + yield* Deferred.succeed(released, undefined); + const rosters = () => awaitedRosters(harness.events, harness.providerThread.id); + yield* harness.until(() => rosters().length === 2); + assert.deepEqual(rosters(), [[BG_COMMAND_ITEM], []]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("settles a command Codex never completed once its terminal is gone", () => Effect.gen(function* () { const settled = yield* Deferred.make(); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 28c4312b499a6..8e921541ce4ca 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -75,6 +75,7 @@ import type { OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, ModelSelection, + OrchestrationV2PendingBackgroundTask, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, OrchestrationV2ProviderFailure, @@ -331,6 +332,7 @@ const CodexBackgroundTerminalsListResponse = Schema.Struct({ data: Schema.Array( Schema.Struct({ processId: Schema.String, + itemId: Schema.optionalKey(Schema.String), }), ), nextCursor: Schema.NullOr(Schema.String), @@ -398,6 +400,7 @@ export const CodexProviderCapabilitiesV2 = { emitsToolOutput: true, supportsMcpTools: true, supportsDynamicToolCallbacks: true, + supportsBackgroundWait: true, }, approvals: { supportsCommandApproval: true, @@ -1550,6 +1553,8 @@ interface TrackedRunningCommandItem { readonly command: string; readonly aggregatedOutput?: string; readonly processId?: string; + /** The agent waits on this command (`t3_background_wait`). */ + readonly awaited?: true; } function isPersistentCodexDynamicTool(item: CodexDynamicToolItem): boolean { @@ -2599,6 +2604,23 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const turnTerminalizationPermit = yield* Semaphore.make(1); const goalsByNativeThread = new Map(); const rootProviderThreads = new Map(); + // Turn and resume inputs carry snapshots older than the roster published since. + const publishedAwaitedRosters = new Map< + string, + ReadonlyArray + >(); + const setRootProviderThread = ( + nativeThreadId: string, + providerThread: OrchestrationV2ProviderThread, + ) => { + const roster = publishedAwaitedRosters.get(nativeThreadId); + rootProviderThreads.set( + nativeThreadId, + roster === undefined + ? providerThread + : { ...providerThread, pendingBackgroundTasks: roster }, + ); + }; const goalHolds = new Map(); const continuedRuns = new Map>(); const capacityContinuations = new Map< @@ -2764,7 +2786,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const goal = goalsByNativeThread.get(nativeThreadId) ?? null; if (providerGoalsEqual(providerThread.goal ?? null, goal)) return; const updated = { ...providerThread, goal, updatedAt: yield* DateTime.now }; - rootProviderThreads.set(nativeThreadId, updated); + setRootProviderThread(nativeThreadId, updated); yield* emitProviderEvent({ type: "provider_thread.updated", driver: CODEX_PROVIDER, @@ -2777,7 +2799,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { const nativeThreadId = providerThread.nativeThreadRef?.nativeId; if (nativeThreadId == null) return; - rootProviderThreads.set(nativeThreadId, providerThread); + setRootProviderThread(nativeThreadId, providerThread); yield* emitGoalUpdate(nativeThreadId); }); @@ -3006,6 +3028,70 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return updated; }); + /** + * Commands the agent waits on go on their root provider thread's roster, as other + * adapters list awaited work, so delegated tasks, Settle and restart recovery see them. + */ + const publishAwaitedCommandRosters = Effect.fnUntraced(function* () { + const contexts = new Map([ + ...(yield* Ref.get(settledTurns)), + ...(yield* Ref.get(activeTurns)), + ]); + const rosters = new Map>(); + for (const [nativeTurnId, items] of yield* Ref.get(runningCommandItemsByTurn)) { + const context = contexts.get(nativeTurnId); + const nativeThreadId = context?.providerThread.nativeThreadRef?.nativeId; + if (context === undefined || context.subagent !== null || nativeThreadId == null) + continue; + for (const tracked of items.values()) { + if (tracked.awaited !== true) continue; + const description = tracked.command.trim(); + rosters.set(nativeThreadId, [ + ...(rosters.get(nativeThreadId) ?? []), + { + taskId: tracked.id, + kind: "command", + command: tracked.command, + ...(description.length === 0 ? {} : { description }), + ...(context.projectionRunId === null ? {} : { runId: context.projectionRunId }), + awaited: true, + }, + ]); + } + } + const activeNativeThreadIds = new Set( + [...(yield* Ref.get(activeTurns)).values()].flatMap((context) => + context.subagent === null ? [context.providerThread.nativeThreadRef?.nativeId] : [], + ), + ); + for (const [nativeThreadId, providerThread] of rootProviderThreads) { + const tasks = rosters.get(nativeThreadId) ?? []; + const previous = + publishedAwaitedRosters.get(nativeThreadId) ?? + providerThread.pendingBackgroundTasks ?? + []; + if ( + previous.length === tasks.length && + previous.every((task, index) => task.taskId === tasks[index]?.taskId) + ) + continue; + const updated = { + ...providerThread, + pendingBackgroundTasks: tasks, + updatedAt: yield* DateTime.now, + }; + publishedAwaitedRosters.set(nativeThreadId, tasks); + rootProviderThreads.set(nativeThreadId, updated); + yield* emitProviderEvent({ + type: "provider_thread.updated", + driver: CODEX_PROVIDER, + providerThread: updated, + // No run reads this stream between turns, so the session stores the roster itself. + ...(activeNativeThreadIds.has(nativeThreadId) ? {} : { sessionScoped: true }), + }); + } + }); + const clearRunningCommandItem = (nativeTurnId: string, nativeItemId: string) => Ref.modify(runningCommandItemsByTurn, (current) => { const items = current.get(nativeTurnId); @@ -3021,7 +3107,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.set(nativeTurnId, remaining); } return [remaining.size === 0, updated] as const; - }); + }).pipe(Effect.tap(publishAwaitedCommandRosters)); interface PendingMcpAppCapture { readonly item: Extract; @@ -3262,14 +3348,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.timeout("10 seconds"), ); - /** - * Codex can end a turn without item/completed for a command whose shell already - * exited (openai/codex#53488). Only a live background terminal keeps a command - * running past its turn; the rest settle as cancelled since their result is unknown. - */ - const settleExitedCommandItems = Effect.fn("CodexAdapterV2.settleExitedCommandItems")( - function* (nativeThreadId: string, nativeTurnId: string) { - const liveProcessIds = new Set(); + const listBackgroundTerminals = Effect.fn("CodexAdapterV2.listBackgroundTerminals")( + function* (nativeThreadId: string) { + const terminals: Array = []; let cursor: string | null = null; while (true) { const response: unknown = yield* client.raw.request( @@ -3281,10 +3362,25 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); const page: CodexBackgroundTerminalsListPage = yield* decodeCodexBackgroundTerminalsListResponse(response); - for (const terminal of page.data) liveProcessIds.add(terminal.processId); - if (page.nextCursor === null) break; + terminals.push(...page.data); + if (page.nextCursor === null) return terminals; cursor = page.nextCursor; } + }, + ); + + /** + * Codex can end a turn without item/completed for a command whose shell already + * exited (openai/codex#53488). Only a live background terminal keeps a command + * running past its turn; the rest settle as cancelled since their result is unknown. + */ + const settleExitedCommandItems = Effect.fn("CodexAdapterV2.settleExitedCommandItems")( + function* (nativeThreadId: string, nativeTurnId: string) { + const liveProcessIds = new Set( + (yield* listBackgroundTerminals(nativeThreadId)).map( + (terminal) => terminal.processId, + ), + ); yield* turnTerminalizationPermit.withPermits(1)( Effect.gen(function* () { const context = (yield* Ref.get(settledTurns)).get(nativeTurnId); @@ -5893,6 +5989,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.delete(context.nativeTurnId); return updated; }); + yield* publishAwaitedCommandRosters(); yield* releaseSettledTurnIfIdle(context.nativeTurnId); } }).pipe(Effect.orDie, turnTerminalizationPermit.withPermits(1)), @@ -7139,7 +7236,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const rootProviderThread = nativeThreadId == null ? undefined : rootProviderThreads.get(nativeThreadId); if (nativeThreadId != null && rootProviderThread !== undefined) { - rootProviderThreads.set(nativeThreadId, { ...rootProviderThread, status: "idle" }); + setRootProviderThread(nativeThreadId, { ...rootProviderThread, status: "idle" }); } // Notification handlers block response routing, so the read and terminal get a fiber. if (awaitsReset) { @@ -7722,6 +7819,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.delete(input.nativeTurnId); return updated; }); + yield* publishAwaitedCommandRosters(); yield* Ref.update(runningDynamicToolsByTurn, (current) => { if (!current.has(input.nativeTurnId)) { return current; @@ -8383,7 +8481,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* rejectIfRetired; if (command.type === "set") yield* validateCodexGoalObjective(command.objective); const threadId = yield* getNativeThreadId(turnInput.providerThread); - rootProviderThreads.set(threadId, turnInput.providerThread); + setRootProviderThread(threadId, turnInput.providerThread); const readGoal = client .request("thread/goal/get", { threadId }) .pipe( @@ -8660,6 +8758,91 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } return false; }), + awaitBackgroundTasks: Effect.fn("CodexAdapterV2.awaitBackgroundTasks")(function* ({ + providerThread, + taskIds, + awaited, + }) { + // Only a root command wakes the agent when it ends. + const rootCommandTurnIds = Effect.gen(function* () { + const contexts = new Map([ + ...(yield* Ref.get(settledTurns)), + ...(yield* Ref.get(activeTurns)), + ]); + return new Set( + [...(yield* Ref.get(runningCommandItemsByTurn)).keys()].filter((nativeTurnId) => { + const context = contexts.get(nativeTurnId); + return ( + context?.providerThread.id === providerThread.id && context.subagent === null + ); + }), + ); + }); + // Codex shows the agent a terminal's session id, its processId. A command that waited + // on approval starts without one, so Codex's terminal list maps unseen ids to items. + const turnIds = yield* rootCommandTurnIds; + const running = yield* Ref.get(runningCommandItemsByTurn); + const commands = [...turnIds].flatMap((id) => [...(running.get(id)?.values() ?? [])]); + const unseen = taskIds.filter( + (taskId) => + !commands.some((tracked) => taskId === tracked.id || taskId === tracked.processId), + ); + const nativeThreadId = providerThread.nativeThreadRef?.nativeId; + const learnedProcessIds = new Map(); + if ( + unseen.length > 0 && + nativeThreadId != null && + commands.some((tracked) => tracked.processId === undefined) + ) { + const terminals = yield* listBackgroundTerminals(nativeThreadId).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CODEX_PROVIDER, + detail: "Could not list Codex background terminals.", + cause, + }), + ), + ); + for (const terminal of terminals) { + if (terminal.itemId !== undefined && unseen.includes(terminal.processId)) { + learnedProcessIds.set(terminal.itemId, terminal.processId); + } + } + } + // Item events hold this permit, so a mark never lists a command after its result. + return yield* turnTerminalizationPermit.withPermits(1)( + Effect.gen(function* () { + const eligible = yield* rootCommandTurnIds; + const matched = new Set(); + yield* Ref.update(runningCommandItemsByTurn, (current) => { + const updated = new Map(current); + for (const nativeTurnId of eligible) { + for (const tracked of current.get(nativeTurnId)?.values() ?? []) { + const processId = tracked.processId ?? learnedProcessIds.get(tracked.id); + const named = taskIds.filter( + (taskId) => taskId === tracked.id || taskId === processId, + ); + if (named.length === 0) continue; + for (const taskId of named) matched.add(taskId); + const { awaited: _previous, ...rest } = tracked; + updated.set( + nativeTurnId, + new Map(updated.get(nativeTurnId)).set(tracked.id, { + ...rest, + ...(processId === undefined ? {} : { processId }), + ...(awaited ? { awaited: true as const } : {}), + }), + ); + } + } + return updated; + }); + yield* publishAwaitedCommandRosters(); + return { matched: [...matched] }; + }), + ); + }), ensureThread: (threadInput) => rejectIfRetired.pipe( Effect.andThen(ensureInitialized), @@ -8737,7 +8920,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); // Codex resumes an active goal's turns right after the response; own them before it. const previousRoot = rootProviderThreads.get(nativeThreadId); - rootProviderThreads.set(nativeThreadId, threadInput.providerThread); + setRootProviderThread(nativeThreadId, threadInput.providerThread); goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( Effect.andThen(appThreadId == null ? resume : reportingResume(appThreadId, resume)), @@ -8747,7 +8930,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.onError(() => Effect.suspend(() => { if (previousRoot !== undefined) { - rootProviderThreads.set(nativeThreadId, previousRoot); + setRootProviderThread(nativeThreadId, previousRoot); } return releaseGoalUpdates(nativeThreadId); }), @@ -8766,7 +8949,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef, updatedAt: codexTimestamp(response.thread.updatedAt), } satisfies OrchestrationV2ProviderThread; - rootProviderThreads.set(nativeThreadId, resumed); + setRootProviderThread(nativeThreadId, resumed); yield* releaseGoalUpdates(nativeThreadId); return rootProviderThreads.get(nativeThreadId) ?? resumed; }, @@ -9144,6 +9327,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } return updated; }); + yield* publishAwaitedCommandRosters(); }); const finalizeRemainingInterruptLineage = Effect.gen(function* () { @@ -9332,6 +9516,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.delete(context.nativeTurnId); return updated; }); + yield* publishAwaitedCommandRosters(); yield* clearImageWork(context); yield* releaseSettledTurnIfIdle(context.nativeTurnId); } diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index b447e171a675b..156c21d015dc7 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -2772,7 +2772,14 @@ it.effect( assert.equal(resolved?.thread.threadId, threadId); assert.deepEqual( resolved?.capabilities, - new Set(["preview", "orchestration", "worktree", "pull-requests", "issues"]), + new Set([ + "preview", + "orchestration", + "worktree", + "pull-requests", + "issues", + "background-wait", + ]), ); assert.isFalse(yield* captured!.hasPendingWake!); @@ -2884,7 +2891,7 @@ it.effect( const resolved = yield* registry.resolve(token!); assert.deepEqual( resolved?.capabilities, - new Set(["orchestration", "worktree", "pull-requests", "issues"]), + new Set(["orchestration", "worktree", "pull-requests", "issues", "background-wait"]), ); yield* manager.close(providerSessionId); diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 12b35b3c0aaf8..3babc92588308 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -31,6 +31,10 @@ const toolInstructions = (tools: T3CodeToolAvailability): string => .filter(Boolean) .join("\n\n"); +// Codex wakes the agent when any background command ends, so T3 can't tell a wait from a dev server. +const CODEX_BACKGROUND_WAIT_INSTRUCTIONS = + "To wait for a background command you started (tests, a build), pass its session ID to `t3_background_wait` before you end your turn. Do not mark work you leave running, or PRs."; + export interface CodexRuntimeInfo { readonly agentFeedback?: AgentFeedbackMode; readonly model: string; @@ -58,5 +62,6 @@ export function buildCodexAdditionalContext( value: buildRuntimeInstructions({ harness: "Codex", ...runtime }), }, ...(tools ? { t3_code_tools: { kind: "application", value: tools } } : {}), + t3_code_background_wait: { kind: "application", value: CODEX_BACKGROUND_WAIT_INSTRUCTIONS }, }; } diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index f962a7b44a4f9..92fe1b6c50565 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6347, - "codexAdditionalContextBytes": 7916, + "codexAdditionalContextBytes": 8092, "mcpToolListJsonBytes": 63718 } diff --git a/evals/mcp-tool-use/cases/background-wait.ndjson b/evals/mcp-tool-use/cases/background-wait.ndjson index f6fcebc9325bb..8b21e00f896b6 100644 --- a/evals/mcp-tool-use/cases/background-wait.ndjson +++ b/evals/mcp-tool-use/cases/background-wait.ndjson @@ -1,2 +1,4 @@ {"id":"background-wait-opencode-tests","area":"background-wait","kind":"bad","pattern":"OpenCode awaits a background validation result -> mark only that shell awaited","experience":"OpenCode background shells outlived successful turns without a supported explicit wait marker, so T3 presented validation as finished.","privacy":"commit-safe","setup":{"role":"top","context":"You are running through the OpenCode provider in T3. Two native background shells have already launched: sh_tests runs the requested validation; sh_dev serves the development app and should stay running after the work is done. Their completion notifications will wake you automatically. There is no other work to do until validation ends.","mocks":{"t3_background_wait":{"matched":["sh_tests"],"unmatched":[]}}},"prompt":"Wait for the validation shell sh_tests, then inspect its result when it finishes. Leave sh_dev running. Do not poll or stop either shell.","expect":{"calls":[{"tool":"t3_background_wait","args":{"taskIds":["sh_tests"]}}],"callsMustNot":[{"tool":"t3_background_wait","args":{"taskIds":["sh_dev"]}},{"tool":"t3_background_wait","args":{"waiting":false}}]},"maxSteps":5,"source":{"issue":"https://github.com/pingdotgg/t3code/issues/35214"},"notes":"API replay exercises the provider-neutral tool description with OpenCode context, not an OpenCode harness capture or the adapter's injected instructions."} {"id":"background-wait-opencode-dev-server","area":"background-wait","kind":"guard","pattern":"intentionally detached OpenCode dev server -> no wait mark","experience":"The old customization kept finished threads in Working merely because their dev servers were still running.","privacy":"commit-safe","setup":{"role":"top","context":"You are running through the OpenCode provider in T3. Validation passed. The only background work is sh_dev, the development server, which is ready at http://localhost:3000. No further agent work depends on its exit."},"prompt":"We're done. Leave the dev server running and give me a short summary. Don't inspect the browser.","expect":{"callsMustNot":[{"tool":"t3_background_wait"}]},"maxSteps":3,"source":{"decision":"https://github.com/pingdotgg/t3code/pull/24610"}} +{"id":"background-wait-codex-tests","area":"background-wait","kind":"bad","pattern":"Codex leaves a test run in a background terminal and ends its turn -> mark only that session awaited","experience":"Codex background terminals never held a thread: T3 listed a Codex thread waiting on its tests as done, and the sidebar and attention showed nothing to wait for until the wake arrived.","privacy":"commit-safe","setup":{"role":"top","harness":"codex","context":"Earlier in this turn you started two commands with exec_command and they are still running in background terminals: session 41 runs `vp test run`, the full suite the user asked for, which takes about 15 minutes; session 42 runs `vp run dev`, the development server, ready at http://localhost:3000, which should stay running afterwards. When a background command exits, T3 starts a new turn for you with its result.","world":{"backgroundTasks":["41","42"],"tests":"The suite started a minute ago. 38 test files have passed and none have failed yet."}},"prompt":"I'm heading out for a bit. Tell me what failed when the tests are done.","expect":{"calls":[{"tool":"t3_background_wait","args":{"taskIds":["41"]}}],"callsMustNot":[{"tool":"t3_background_wait","args":{"taskIds":["42"]}},{"tool":"t3_background_wait","args":{"waiting":false}}]},"maxSteps":6,"source":{"decision":"https://github.com/pingdotgg/t3code/pull/24610"},"notes":"T3 answers the wait from its own handler over sessions 41 and 42. The context stands in for the exec_command calls, as the OpenCode cases do."} +{"id":"background-wait-codex-dev-server","area":"background-wait","kind":"guard","pattern":"Codex leaves a dev server running on purpose -> no wait mark","experience":"Before #24610, finished threads stayed in Working only because their dev servers were still running.","privacy":"commit-safe","setup":{"role":"top","harness":"codex","context":"Validation passed. The only command still running is in background terminal session 42: `vp run dev`, the development server, ready at http://localhost:3000. Nothing else depends on it exiting.","world":{"backgroundTasks":["42"]}},"prompt":"We're done. Leave the dev server running and give me a short summary. Don't inspect the browser.","expect":{"callsMustNot":[{"tool":"t3_background_wait"}]},"maxSteps":3,"source":{"decision":"https://github.com/pingdotgg/t3code/pull/24610"}} diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts index 5b8f67e1fae1a..faaf9aea24a6e 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts @@ -387,6 +387,46 @@ describe("derivePendingBackgroundWork kinds", () => { ]); }); + it("holds for a command the provider lists awaited, over its running turn item", () => { + const tasks = derivePendingBackgroundWork({ + latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" }, + providerThreads: [ + { + id: "provider-thread-1" as never, + pendingBackgroundTasks: [ + { taskId: "tests", kind: "command", description: "npm test", awaited: true }, + ], + }, + ], + turnItems: [ + { + id: "item-tests" as never, + type: "command_execution", + status: "running", + title: null, + nativeItemRef: { nativeId: "tests" }, + input: "npm test", + }, + { + id: "item-dev" as never, + type: "command_execution", + status: "running", + title: null, + nativeItemRef: { nativeId: "dev" }, + input: "npm run dev", + }, + ], + }); + expect(tasks).toEqual([ + { taskId: "tests", description: "npm test", kind: "command", awaited: true }, + { taskId: "dev", description: "npm run dev", kind: "command" }, + ]); + expect(backgroundWorkHoldsCompletion(tasks)).toBe(true); + expect(backgroundWorkHoldsCompletion(tasks.filter((task) => task.taskId === "dev"))).toBe( + false, + ); + }); + describe("pull request watches", () => { const watch = { startedAt: "2026-10-05T00:00:00.000Z",