diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 69fca8c0825b8..75ba73a571bfb 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1883,11 +1883,15 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect("preserves T3 context on the wire and restores it after compaction", () => + it.effect("restores unchanged T3 context before the turn after compaction", () => Effect.scoped( Effect.gen(function* () { const nativeThreadId = "context-thread"; const nativeTurnId = "context-turn"; + const nextModelSelection = { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "reasoningEffort", value: "high" }], + } satisfies ModelSelection; const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ nativeThreadId, codexInput: [{ type: "text", text: "work" }], @@ -1895,10 +1899,25 @@ describe("CodexAdapterV2 post-settle continuation", () => { modelSelection: CODEX_TEST_MODEL_SELECTION, hasT3Mcp: true, }); + const nextParams = yield* CodexAdapterV2.buildCodexTurnStartParams({ + nativeThreadId, + codexInput: [{ type: "text", text: "more" }], + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + modelSelection: nextModelSelection, + hasT3Mcp: true, + }); assert.include( params.additionalContext?.t3_code_orchestration_01?.value ?? "", "delegate_task", ); + // Codex resends changed keys itself, so only unchanged ones need restoring. + assert.notEqual( + params.additionalContext?.t3_code_runtime?.value, + nextParams.additionalContext?.t3_code_runtime?.value, + ); + const restored = Object.entries(nextParams.additionalContext ?? {}).filter( + ([key, entry]) => params.additionalContext?.[key]?.value === entry.value, + ); const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }); const transcript = makeCodexReplayTranscript({ scenario: "restore-context", @@ -1922,6 +1941,17 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, }, + { + type: "emit_inbound", + label: "done", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, { type: "expect_outbound", label: "restore context", @@ -1930,7 +1960,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { method: "thread/inject_items", params: { threadId: nativeThreadId, - items: Object.entries(params.additionalContext ?? {}).map(([key, entry]) => ({ + items: restored.map(([key, entry]) => ({ type: "message", role: "developer", content: [{ type: "input_text", text: `<${key}>${entry.value}` }], @@ -1939,15 +1969,17 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, { type: "emit_inbound", label: "restored", frame: { id: 4, result: {} } }, + { + type: "expect_outbound", + label: "next turn", + frame: { id: 5, method: "turn/start", params: nextParams }, + }, { type: "emit_inbound", - label: "done", + label: "next turn", frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, + id: 5, + result: { turn: makeCodexReplayTurn({ id: "next-turn", status: "inProgress" }) }, }, }, ], @@ -1973,6 +2005,18 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); yield* harness.firstTerminal; assert.equal(harness.terminalEvents()[0]?.status, "completed"); + yield* harness.runtime.startTurn({ + ...makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("context-attempt-2"), + text: "more", + }), + modelSelection: nextModelSelection, + runOrdinal: 2, + providerTurnOrdinal: 2, + }); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -6887,6 +6931,106 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("restores T3 context when Codex continues a goal after compaction", () => + Effect.gen(function* () { + const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ + nativeThreadId, + codexInput: [{ type: "text", text: `Start working toward this goal: ${objective}` }], + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + modelSelection: CODEX_TEST_MODEL_SELECTION, + hasT3Mcp: true, + }); + const goalTurnStart = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "goal-turn-1", + prompt: objective, + }).slice(6); + const transcript = makeCodexReplayTranscript({ + scenario: "goal-continuation-restores-context", + entries: [ + ...sessionStart, + ...request(3, "thread/goal/get", { threadId: nativeThreadId }, { goal: null }), + ...request( + 4, + "thread/goal/set", + { threadId: nativeThreadId, objective, status: "paused" }, + { goal: codexGoal("paused", 0) }, + ), + { + type: "expect_outbound", + label: "goal turn", + frame: { id: 5, method: "turn/start", params }, + }, + ...withReplayRequestId(goalTurnStart, 5), + ...request( + 6, + "thread/goal/set", + { threadId: nativeThreadId, status: "active" }, + { goal: codexGoal("active", 0) }, + ), + notification("goal active", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: "goal-turn-1", + goal: codexGoal("active", 0), + }), + notification("compacted", "item/completed", { + threadId: nativeThreadId, + turnId: "goal-turn-1", + item: { type: "contextCompaction", id: "compact-goal" }, + }), + notification("first turn done", "turn/completed", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "goal-turn-1", status: "completed" }), + }), + notification("continuation", "turn/started", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "goal-turn-2", status: "inProgress" }), + }), + ...request( + 7, + "thread/inject_items", + { + threadId: nativeThreadId, + items: Object.entries(params.additionalContext ?? {}).map(([key, entry]) => ({ + type: "message", + role: "developer", + content: [{ type: "input_text", text: `<${key}>${entry.value}` }], + })), + }, + {}, + ), + notification("goal complete", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: "goal-turn-2", + goal: codexGoal("complete", 1200), + }), + notification("continuation done", "turn/completed", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "goal-turn-2", status: "completed" }), + }), + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* (yield* McpProviderSessions.McpProviderSessions).set({ + environmentId: EnvironmentId.make("test"), + threadId: harness.threadId, + providerSessionId: "goal-session", + providerInstanceId: ProviderInstanceId.make("codex"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer test", + browserToolsAvailable: true, + }); + yield* harness.runtime.startTurn(yield* goalTurnInput(harness, `/goal ${objective}`)); + yield* harness.firstTerminal; + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + it.effect("settles a run held for the next goal turn when Stop arrives in between", () => Effect.gen(function* () { const prompt = "Keep going"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 58cd4a0c0c17b..47c3e5f9c7cbe 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1654,21 +1654,28 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( settings: resolvedRuntime?.config ?? adapterOptions.settings, environment: resolvedRuntime?.environment ?? adapterOptions.environment, }); + type CodexAdditionalContext = NonNullable< + CodexTurnStartParamsWithCollaborationMode["additionalContext"] + >; const additionalContextByThread = yield* Ref.make( - new Map< - string, - NonNullable - >(), + new Map(), ); - // Codex drops client developer messages during compaction but only - // resends additionalContext when it changes. + const compactedThreads = new Set(); + // Codex drops client developer messages during compaction but only resends + // additionalContext keys that change. Restore before the next turn: items + // injected mid-turn become pending input that forces another sampling round. const restoreAdditionalContext = Effect.fn("CodexAdapterV2.restoreAdditionalContext")( - function* (threadId: string) { - const context = (yield* Ref.get(additionalContextByThread)).get(threadId); - if (!context) return; + function* (threadId: string, next: CodexAdditionalContext | undefined) { + if (!compactedThreads.delete(threadId)) return; + const previous = (yield* Ref.get(additionalContextByThread)).get(threadId); + const unchanged = Object.entries(next ?? {}).filter( + ([key, entry]) => + previous?.[key]?.kind === entry.kind && previous[key].value === entry.value, + ); + if (unchanged.length === 0) return; yield* client.request("thread/inject_items", { threadId, - items: Object.entries(context).map(([key, entry]) => + items: unchanged.map(([key, entry]) => entry.kind === "untrusted" ? { type: "message", @@ -4434,6 +4441,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( continuedRuns.set(goalHold.context.providerTurnId, goalRun); continuedRuns.set(next.providerTurnId, goalRun); yield* Deferred.succeed(goalHold.next, next); + // Codex starts goal turns itself, so restore here instead of in startNativeTurn. + const context = (yield* Ref.get(additionalContextByThread)).get(payload.threadId); + yield* restoreAdditionalContext(payload.threadId, context).pipe( + Effect.forkIn(scope, { startImmediately: true }), + ); return; } // Pause orphan goal turns so they cannot work without an owning run. @@ -4774,11 +4786,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* client.handleServerNotification("item/completed", (payload) => Effect.gen(function* () { - if (payload.item.type === "contextCompaction") - // Fork requests off the notification reader so it can read their responses. - yield* restoreAdditionalContext(payload.threadId).pipe( - Effect.forkIn(scope, { startImmediately: true }), - ); + if (payload.item.type === "contextCompaction") compactedThreads.add(payload.threadId); if ( (payload.item.type === "subAgentActivity" || payload.item.type === "collabAgentToolCall") && @@ -6496,6 +6504,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.set(threadId, turnInput); return updated; }); + yield* restoreAdditionalContext(threadId, turnStartParams.additionalContext); yield* Ref.update(additionalContextByThread, (current) => { const next = new Map(current); if (turnStartParams.additionalContext)