From 1397d7637725b310430597c61face031beac84bf Mon Sep 17 00:00:00 2001 From: qi-hey <63509385+qi-hey@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:34:36 +0800 Subject: [PATCH 1/6] fix(server): append new messages when re-importing Codex history --- .../src/project/AgentSessionImporter.test.ts | 69 ++++++++++++------- .../src/project/AgentSessionImporter.ts | 69 +++++++++++++++---- docs/user/welcome-page.md | 6 +- 3 files changed, 105 insertions(+), 39 deletions(-) diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 18c0946144d4a..20ada501a987e 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -543,7 +543,7 @@ it.effect("counts only new threads when re-importing cached and recovered transc }).pipe(Effect.scoped, Effect.provide(persistence)), ); -it.effect("does not certify new native history after a partial import retry", () => +it.effect("retries a partial Codex import only when the transcript matches the stored prefix", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -562,58 +562,77 @@ it.effect("does not certify new native history after a partial import retry", () { role: "user", text: "Continue outside T3", createdAt: timestamp }, { role: "assistant", text: "Native continuation", createdAt: timestamp }, ); - // The thread holds only the original messages, so the continued transcript stays unrecorded. - expect(yield* (yield* makeImporter([continued])).run).toEqual({ - importedCount: 0, - skippedCount: 1, - }); + continued.thread.messages[0] = { + role: "user", + text: "Different request", + createdAt: timestamp, + }; + const retry = yield* makeImporter([continued]); + expect(yield* retry.run).toEqual({ importedCount: 0, skippedCount: 1 }); expect(yield* runtimes.list()).toEqual([]); expect( (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( (message) => message.text, ), ).toEqual(["Fix it", "Fixed"]); + + continued.thread.messages[0] = { role: "user", text: "Fix it", createdAt: timestamp }; + continued.thread.omittedMessageCount = 1; + expect(yield* retry.run).toEqual({ importedCount: 0, skippedCount: 1 }); + expect(yield* runtimes.list()).toEqual([]); + + continued.thread.omittedMessageCount = 0; + expect(yield* retry.run).toEqual({ importedCount: 1, skippedCount: 0 }); + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ + runtimePayload: { importedTranscripts: [continued.source] }, + }); + expect( + (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( + (message) => message.text, + ), + ).toEqual(["Fix it", "Fixed", "Continue outside T3", "Native continuation"]); }).pipe(Effect.scoped, Effect.provide(persistence)), ); -it.effect("does not record a changed transcript as imported without its new messages", () => +it.effect("appends new Codex messages to the existing import exactly once", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - const first = candidate( - CLAUDE_MODEL_SELECTION, - "6f1c2a7e-3b4d-4e5f-9a8b-1c2d3e4f5a6b", - "claudeAgent", - ); + const first = candidate(CODEX_MODEL_SELECTION, "continued-in-codex"); const threadId = importId(first); expect(yield* (yield* makeImporter([first])).run).toEqual({ importedCount: 1, skippedCount: 0, }); + const before = yield* projections.getThreadRecords(threadId, ["messages"]); - const continued = candidate( - CLAUDE_MODEL_SELECTION, - first.source.providerSessionId, - "claudeAgent", - ); + const continued = candidate(CODEX_MODEL_SELECTION, first.source.providerSessionId); continued.source.size = 200; continued.source.mtimeMs = 3; continued.thread.messages.push( { role: "user", text: "Continue", createdAt: timestamp }, { role: "assistant", text: "Continued", createdAt: timestamp }, ); - yield* (yield* makeImporter([continued])).run; + const importer = yield* makeImporter([continued]); + const results = yield* Effect.all([importer.run, importer.run], { concurrency: 2 }); + expect(results.map(({ importedCount }) => importedCount).sort()).toEqual([0, 1]); + expect(results.map(({ skippedCount }) => skippedCount)).toEqual([0, 0]); + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); const recorded = AgentSessionScanner.decodeImportedTranscriptPayload( Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimePayload, ).pipe(Option.getOrThrow).importedTranscripts; - const texts = (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( - (message) => message.text, - ); - expect({ - recordsChangedTranscript: recorded?.some((source) => source.size === 200) ?? false, - showsNewMessages: texts.includes("Continued"), - }).not.toEqual({ recordsChangedTranscript: true, showsNewMessages: false }); + const after = yield* projections.getThreadRecords(threadId, ["messages", "turnItems"]); + expect(recorded).toEqual([continued.source]); + expect(after.thread).toEqual(before.thread); + expect(after.messages.slice(0, 2)).toEqual(before.messages); + expect(after.messages.map((message) => message.text)).toEqual([ + "Fix it", + "Fixed", + "Continue", + "Continued", + ]); + expect(after.turnItems.map((item) => item.ordinal)).toEqual([1, 2, 3, 4]); }).pipe(Effect.scoped, Effect.provide(persistence)), ); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 0f8736986a2df..ed0982eaaeb2f 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -303,6 +303,9 @@ const make = Effect.gen(function* () { // Pi resumes by session file path; its session UUID only names the thread. const nativeThreadId = thread.source === "pi" ? source.filePath : thread.providerSessionId; + const truncatedHistoryId = TurnItemId.make( + `${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`, + ); const persistRuntime = runtimes.upsert( { threadId, @@ -320,25 +323,26 @@ const make = Effect.gen(function* () { }, { onConflict: "ignore" }, ); - const existing = yield* Effect.option( - orchestrator.getThreadRecords(threadId, ["messages"]), + const existing = yield* orchestrator.getThreadRecords(threadId, ["messages"]).pipe( + Effect.asSome, + Effect.catchIf( + (cause) => isProjectionStoreThreadNotFoundError(cause.cause), + () => Effect.succeedNone, + ), ); if (Option.isSome(existing)) { - if (existing.value.thread.projectId !== input.projectId) { + const { thread: current, messages: stored } = existing.value; + if (current.projectId !== input.projectId) { return yield* new AgentSessionThreadProjectConflictError({ threadId, expectedProjectId: input.projectId, - actualProjectId: existing.value.thread.projectId, + actualProjectId: current.projectId, }); } - if (existing.value.thread.historyOrigin !== "v1_import") { + if (current.historyOrigin !== "v1_import") { return yield* new AgentSessionThreadModifiedError({ threadId }); } - // A transcript can change after the import, so record it only when the - // thread already holds exactly its messages. - const stored = existing.value.messages; if ( - stored.length !== thread.messages.length || stored.some( (message, index) => message.role !== thread.messages[index]?.role || @@ -347,10 +351,50 @@ const make = Effect.gen(function* () { ) { return false; } + const appended = thread.messages.slice(stored.length); + if (appended.length > 0) { + if ( + thread.source !== "codex" || + thread.omittedMessageCount > 0 || + stored.length === 0 || + current.deletedAt !== null || + stored.some((message) => message.runId !== null) + ) { + return false; + } + // Imported items are ordered before local runs, so only extend an intact import. + const { runs, turnItems, providerThreads } = yield* orchestrator.getThreadRecords( + threadId, + ["runs", "turnItems", "providerThreads"], + { turnItemTypes: ["system_notice"] }, + ); + const owner = providerThreads.find( + (providerThread) => + providerThread.id === current.activeProviderThreadId && + providerThread.appThreadId === threadId && + providerThread.driver === driver && + providerThread.providerInstanceId === thread.providerInstanceId && + providerThread.nativeThreadRef?.nativeId === nativeThreadId, + ); + if ( + owner === undefined || + runs.length > 0 || + turnItems.some((item) => item.id === truncatedHistoryId) + ) { + return false; + } + const committed = yield* eventSink.write({ + unlessNativeThreadOwned: owner, + events: appended.flatMap((message, index) => + messageEvents({ threadId, index: stored.length + index, message }), + ), + }); + if (committed.length === 0) return false; + } yield* persistRuntime; yield* runtimes.recordImportedTranscript({ threadId, source }); importedThreadIds.add(threadId); - return null; + return appended.length > 0 ? true : null; } const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL; @@ -434,12 +478,12 @@ const make = Effect.gen(function* () { ...(thread.omittedMessageCount > 0 ? [ { - id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + id: EventId.make(truncatedHistoryId), type: "turn-item.updated" as const, threadId, occurredAt: createdAt, payload: { - id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + id: truncatedHistoryId, threadId, runId: null, nodeId: null, @@ -478,6 +522,7 @@ const make = Effect.gen(function* () { yield* runtimes.recordImportedTranscript({ threadId, source }); return true; }).pipe( + (effect) => threadCommands.withLock(threadId, effect), Effect.catch((cause) => Effect.logWarning("Could not import an agent session", { provider: outcome.thread.source, diff --git a/docs/user/welcome-page.md b/docs/user/welcome-page.md index ed8e75c28c74c..cd7c518b3dea6 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -109,8 +109,10 @@ in an editor but never used. It skips unreadable or unparseable conversations. Each import attempt reads up to 100 conversations and 4 GiB per project. Conversations with no messages count toward the 4 GiB but not the 100. To continue a large batch, open the Welcome page again and pick the project in -**Review all**. Completed conversations are not imported again. You can continue -without the remaining history. +**Review all**. Unchanged conversations are skipped. Re-importing a Codex +conversation adds new messages to the existing thread when the original history +is intact and the thread has no turns run in T3 Code. You can continue without +the remaining history. You can start without importing. While an import runs, T3 Code stays on the Welcome page. If you quit, open the Welcome page again from **Settings → About**; the From aeca8a3f9ff3e2914d667d25c3c1ad122de2ef11 Mon Sep 17 00:00:00 2001 From: qi-hey <63509385+qi-hey@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:27:26 +0800 Subject: [PATCH 2/6] fix(codex): refresh native messages when returning to a chat --- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../Adapters/CodexAdapterV2.test.ts | 78 +++++ .../Adapters/CodexAdapterV2.ts | 58 ++++ .../src/project/AgentSessionImporter.test.ts | 163 ++++++++++ .../src/project/AgentSessionImporter.ts | 288 +++++++++++++++++- apps/server/src/ws.ts | 2 + apps/web/src/components/ChatView.tsx | 9 +- .../components/chat/ThreadVisitWatermark.tsx | 39 ++- docs/user/welcome-page.md | 4 + .../src/state/commandPermissions.test.ts | 10 +- packages/contracts/src/agentSessions.ts | 10 +- .../contracts/src/clientRpcPermissions.ts | 1 + packages/contracts/src/rpc.ts | 12 + .../src/server/ProviderAdapter.ts | 16 + 15 files changed, 672 insertions(+), 20 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 2e73a401caaff..d8004826cde85 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -173,6 +173,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.filesystemGetMetadata]: AuthFilesystemReadScope, [WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope, [WS_METHODS.agentSessionsImport]: AuthOrchestrationOperateScope, + [WS_METHODS.agentSessionsRefreshCodexHistory]: AuthOrchestrationOperateScope, [WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope, [WS_METHODS.assetsPersistChatAttachments]: AuthOrchestrationOperateScope, [WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a2b698657afcb..6719ebd76461b 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -185,6 +185,7 @@ const RPC_AGGREGATES = { [WS_METHODS.filesystemGetMetadata]: "workspace", [WS_METHODS.agentSessionsScan]: "workspace", [WS_METHODS.agentSessionsImport]: "workspace", + [WS_METHODS.agentSessionsRefreshCodexHistory]: "workspace", [WS_METHODS.assetsCreateUrl]: "workspace", [WS_METHODS.assetsPersistChatAttachments]: "orchestration", [WS_METHODS.attachmentsCreateUploadUrl]: "workspace", diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index fd5f89b86a0c1..ce2fa505f0332 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -4925,6 +4925,84 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("reads the Codex turn suffix across pages in conversation order", () => + Effect.gen(function* () { + const nativeThreadId = "external-history"; + const nativeTurnId = "anchor"; + const turn = (id: string) => ({ + id, + status: "completed", + items: [ + { type: "userMessage", id: `${id}:user`, content: [{ type: "text", text: id }] }, + { type: "agentMessage", id: `${id}:assistant`, text: `Reply to ${id}` }, + ], + }); + const listPage = ( + id: number, + cursor: string | null, + data: Array>, + nextCursor: string | null, + ): Array => [ + { + type: "expect_outbound", + label: "thread/turns/list", + frame: { + id, + method: "thread/turns/list", + params: { + threadId: nativeThreadId, + cursor, + limit: 32, + itemsView: "summary", + sortDirection: "desc", + }, + }, + }, + { + type: "emit_inbound", + label: "thread/turns/list", + frame: { id, result: { data, nextCursor } }, + }, + ]; + const { runtime, providerThread } = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-external-history", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Start" }).slice(0, 5), + ...listPage(3, null, [turn("newest")], "before-newest"), + ...listPage( + 4, + "before-newest", + [turn("older"), turn(nativeTurnId), turn("past")], + null, + ), + ...listPage(5, null, [turn("newest"), turn("older")], null), + ], + }), + ); + const readHistory = runtime.readHistoryAfter!; + const appended = yield* readHistory({ providerThread, nativeTurnId }); + assert.deepEqual( + appended.map((turn) => turn.id), + ["older", "newest"], + ); + assert.deepEqual(appended[0]?.messages, [ + { role: "user", text: "older" }, + { role: "assistant", text: "Reply to older" }, + ]); + assert.deepEqual(yield* readHistory({ providerThread, nativeTurnId }), []); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("reports a thread another Codex client is writing to as in use", () => Effect.gen(function* () { const nativeThreadId = "thread-open-elsewhere"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 4c164b86ab1e7..782172ef13e60 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8788,6 +8788,64 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), ), mcpApps, + readHistoryAfter: Effect.fn("CodexAdapterV2.readHistoryAfter")( + function* ({ providerThread, nativeTurnId }) { + const threadId = yield* getNativeThreadId(providerThread); + yield* ensureInitialized; + const turns: Array = []; + const visited = new Set(); + let cursor: string | null = null; + do { + visited.add(cursor); + const page: CodexSchema.V2ThreadTurnsListResponse = yield* client.request( + "thread/turns/list", + { threadId, cursor, limit: 32, itemsView: "summary", sortDirection: "desc" }, + ); + const anchor = page.data.findIndex((turn) => turn.id === nativeTurnId); + if (anchor >= 0) { + const observedAt = yield* DateTime.now; + turns.push(...page.data.slice(0, anchor)); + return turns + .reverse() + .map((turn): ProviderAdapter.ProviderAdapterV2HistoryTurn => { + const startedAt = + turn.startedAt == null ? observedAt : codexTimestamp(turn.startedAt); + return { + id: turn.id, + status: turn.status, + startedAt, + completedAt: + turn.completedAt == null ? startedAt : codexTimestamp(turn.completedAt), + messages: turn.items.flatMap( + (item): ProviderAdapter.ProviderAdapterV2HistoryTurn["messages"] => { + if (item.type === "userMessage") { + return [{ role: "user", text: codexUserMessageText(item.content) }]; + } + return item.type === "agentMessage" && item.text.trim() !== "" + ? [{ role: "assistant", text: item.text }] + : []; + }, + ), + }; + }); + } + turns.push(...page.data); + cursor = page.nextCursor ?? null; + } while (cursor !== null && !visited.has(cursor)); + return []; + }, + (effect, { providerThread }) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({ + driver: CODEX_PROVIDER, + providerThreadId: providerThread.id, + cause, + }), + ), + ), + ), readThreadSnapshot: Effect.fn("CodexAdapterV2.readThreadSnapshot")( function* (threadInput) { const threadId = yield* getNativeThreadId(threadInput.providerThread); diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 20ada501a987e..e1c096b7b1aad 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -2,12 +2,16 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { type AgentSessionSource, + type OrchestrationV2Run, type ServerSettingsError, EventId, ProjectId, ProviderDriverKind, ProviderInstanceId, MessageId, + NodeId, + ProviderTurnId, + RunAttemptId, RunId, ThreadId, type ApplicationStoredEvent, @@ -280,6 +284,7 @@ const makeImporter = Effect.fn(function* ( return { run: importer.importRecentAgentThreads({ projectId }), importNativeHistory: importer.importNativeHistory, + refreshCodexHistory: importer.refreshCodexHistory, published, }; }); @@ -636,6 +641,164 @@ it.effect("appends new Codex messages to the existing import exactly once", () = }).pipe(Effect.scoped, Effect.provide(persistence)), ); +it.effect("refreshes completed Codex turns after a turn run in T3", () => + Effect.gen(function* () { + const sink = yield* EventSink.EventSinkV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, "alternating-clients")); + const { + thread, + providerThreads: [providerThread], + } = yield* projections.getThreadRecords(threadId, ["providerThreads"]); + expect(providerThread).toBeDefined(); + const nativeThread = providerThread!; + const runId = RunId.make(`${threadId}:first`); + const attemptId = RunAttemptId.make(`${runId}:1`); + const nodeId = NodeId.make(`${runId}:root`); + const localRun: OrchestrationV2Run = { + id: runId, + threadId, + ordinal: 1, + providerInstanceId: nativeThread.providerInstanceId, + modelSelection: thread.modelSelection, + providerThreadId: nativeThread.id, + userMessageId: MessageId.make(`${runId}:user`), + rootNodeId: nodeId, + activeAttemptId: attemptId, + status: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }; + const laterRun: OrchestrationV2Run = { + ...localRun, + id: RunId.make(`${threadId}:second`), + ordinal: 2, + userMessageId: MessageId.make(`${threadId}:second:user`), + rootNodeId: null, + activeAttemptId: null, + status: "queued", + startedAt: null, + completedAt: null, + }; + yield* sink.write({ + events: [ + { + id: EventId.make(`${runId}:created`), + type: "run.created", + threadId, + occurredAt: now, + payload: localRun, + }, + { + id: EventId.make(`${runId}:native`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make(`${runId}:native`), + providerThreadId: nativeThread.id, + nodeId, + runAttemptId: attemptId, + nativeTurnRef: { + driver: nativeThread.driver, + nativeId: "local-turn", + strength: "strong", + }, + ordinal: 1, + status: "completed", + startedAt: now, + completedAt: now, + }, + }, + { + id: EventId.make(`${laterRun.id}:created`), + type: "run.created", + threadId, + occurredAt: now, + payload: laterRun, + }, + ], + }); + + const nativeTurn = ( + id: string, + text: string, + status: ProviderAdapter.ProviderAdapterV2HistoryTurn["status"] = "completed", + ) => ({ + id, + status, + startedAt: now, + completedAt: now, + messages: [ + { role: "user" as const, text }, + { role: "assistant" as const, text: `Reply to ${text}` }, + ], + }); + const nativeHistory = [ + nativeTurn("local-turn", "From T3"), + nativeTurn("outside-1", "From Codex"), + nativeTurn("outside-stopped", "Interrupted in Codex", "interrupted"), + nativeTurn("outside-2", "Next Codex message", "inProgress"), + ]; + const readAnchors: Array = []; + const session = { + readHistoryAfter: ({ nativeTurnId }) => + Effect.sync(() => { + readAnchors.push(nativeTurnId); + const anchor = nativeHistory.findIndex((turn) => turn.id === nativeTurnId); + return anchor < 0 ? [] : nativeHistory.slice(anchor + 1); + }), + } satisfies Pick; + const adapter = { + openSession: () => Effect.succeed(session), + } as unknown as ProviderAdapter.ProviderAdapterV2["Service"]; + const importer = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter)); + const refresh = importer.refreshCodexHistory({ threadId }); + + expect(yield* refresh).toBe(0); + expect(readAnchors).toEqual([]); + yield* sink.write({ + events: [ + { + id: EventId.make(`${laterRun.id}:cancelled`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...laterRun, status: "cancelled", completedAt: now }, + }, + ], + }); + const copies = yield* Effect.all([refresh, refresh], { concurrency: 2 }); + expect(copies.toSorted()).toEqual([0, 1]); + expect(readAnchors).toEqual(["local-turn", "outside-1"]); + nativeHistory[3] = nativeTurn("outside-2", "Next Codex message"); + expect(yield* refresh).toBe(1); + + const after = yield* projections.getThreadRecords(threadId, [ + "runs", + "turnItems", + "providerTurns", + ]); + expect(after.runs.map((run) => run.ordinal)).toEqual([1, 2, 3, 4]); + expect(after.providerTurns.map((turn) => turn.nativeTurnRef?.nativeId)).toEqual([ + "local-turn", + "outside-1", + "outside-2", + ]); + expect(after.turnItems.map((item) => ("text" in item ? item.text : null))).toEqual([ + "From Codex", + "Reply to From Codex", + "Next Codex message", + "Reply to Next Codex message", + ]); + expect(after.turnItems[0]?.ordinal).toBeGreaterThan(2_000_000); + expect(after.thread.id).toBe(threadId); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + it.effect( "copies native session history into the imported thread once, retrying a failed read", () => diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index ed0982eaaeb2f..8722c8f7e71b1 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -12,6 +12,7 @@ import { MessageId, ProjectId, ProviderDriverKind, + RunId, ThreadId, TurnItemId, type AgentSessionImportInput, @@ -20,6 +21,8 @@ import { type OrchestrationV2ConversationMessage, type OrchestrationV2DomainEvent, type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2Run, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; @@ -30,10 +33,13 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import type { ProviderAdapterV2HistoryTurn } from "@t3tools/provider-core/server/ProviderAdapter"; +import { isActiveRun } from "../orchestration-v2/CommandPolicy.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; @@ -88,6 +94,7 @@ class AgentSessionThreadModifiedError extends Schema.TaggedError { const ordinal = input.index + 1; const suffix = String(input.index).padStart(6, "0"); - const messageId = MessageId.make(`${input.threadId}:${suffix}`); - const turnItemId = TurnItemId.make( - `${IMPORT_EVENT_PREFIX}:turn-item:${input.threadId}:${suffix}`, - ); + const messageKey = `${input.run?.id ?? input.threadId}:${suffix}`; + const messageId = MessageId.make(messageKey); + const turnItemId = TurnItemId.make(`${IMPORT_EVENT_PREFIX}:turn-item:${messageKey}`); const at = dateTime(input.message.createdAt); const common = { id: turnItemId, threadId: input.threadId, - runId: null, - nodeId: null, - providerThreadId: null, - providerTurnId: null, + runId: input.run?.id ?? null, + nodeId: input.turn?.nodeId ?? null, + providerThreadId: input.turn?.providerThreadId ?? null, + providerTurnId: input.turn?.id ?? null, nativeItemRef: null, parentItemId: null, ordinal, @@ -151,11 +159,11 @@ function messageEvents(input: { } const message: OrchestrationV2ConversationMessage = { createdBy: input.message.role === "user" ? "user" : "agent", - creationSource: "server", + creationSource: input.run === undefined ? "server" : "provider", id: messageId, threadId: input.threadId, - runId: null, - nodeId: null, + runId: common.runId, + nodeId: common.nodeId, role: input.message.role, text: input.message.text, attachments: [], @@ -168,7 +176,7 @@ function messageEvents(input: { ? { ...common, createdBy: "user", - creationSource: "server", + creationSource: message.creationSource, type: "user_message", messageId, inputIntent: "turn_start", @@ -184,7 +192,7 @@ function messageEvents(input: { }; return [ { - id: EventId.make(`${IMPORT_EVENT_PREFIX}:message:${input.threadId}:${suffix}`), + id: EventId.make(`${IMPORT_EVENT_PREFIX}:message:${messageKey}`), type: "message.updated", threadId: input.threadId, occurredAt: at, @@ -194,6 +202,125 @@ function messageEvents(input: { ]; } +function externalTurnEvents(input: { + readonly thread: OrchestrationV2AppThread; + readonly owner: OrchestrationV2ProviderThread; + readonly nativeThreadId: string; + readonly nativeTurn: ProviderAdapterV2HistoryTurn; + readonly indexOfUserMessage: number; + readonly runOrdinal: number; + readonly turnOrdinal: number; + readonly ids: IdAllocator.IdAllocatorV2["Service"]["derive"]; +}): ReadonlyArray { + const { thread, owner, nativeTurn, ids } = input; + const { id: threadId } = thread; + const { id: providerThreadId, providerInstanceId, driver } = owner; + const runId = RunId.make(`codex-history:${threadId}:${nativeTurn.id}`); + const attemptId = ids.runAttempt({ runId, attemptOrdinal: 1 }); + const nodeId = ids.rootNode({ runId }); + const providerTurnId = ids.providerTurn({ driver, nativeTurnId: nativeTurn.id }); + const { startedAt, completedAt } = nativeTurn; + const occurredAt = completedAt; + const nodeEvent = { threadId, nodeId, runId, providerInstanceId, occurredAt }; + const turn: OrchestrationV2ProviderTurn = { + id: providerTurnId, + providerThreadId, + nodeId, + runAttemptId: attemptId, + nativeTurnRef: { driver, nativeId: nativeTurn.id, strength: "strong" }, + nativeThreadRef: { driver, nativeId: input.nativeThreadId, strength: "strong" }, + ordinal: input.turnOrdinal, + status: "completed", + startedAt, + completedAt, + }; + const run: OrchestrationV2Run = { + id: runId, + threadId, + ordinal: input.runOrdinal, + providerInstanceId, + modelSelection: { ...thread.modelSelection, instanceId: providerInstanceId }, + providerThreadId, + userMessageId: MessageId.make(`${runId}:${String(input.indexOfUserMessage).padStart(6, "0")}`), + rootNodeId: nodeId, + activeAttemptId: attemptId, + status: "completed", + requestedAt: startedAt, + startedAt, + completedAt, + checkpointId: null, + contextHandoffId: null, + }; + return [ + { + ...nodeEvent, + id: EventId.make(`${runId}:created`), + type: "run.created", + payload: run, + }, + { + ...nodeEvent, + id: EventId.make(`${runId}:root`), + type: "node.updated", + payload: { + id: nodeId, + threadId, + runId, + parentNodeId: null, + rootNodeId: nodeId, + kind: "root_turn", + status: "completed", + countsForRun: true, + providerThreadId, + providerTurnId, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt, + completedAt, + }, + }, + { + ...nodeEvent, + id: EventId.make(`${runId}:attempt`), + type: "run-attempt.created", + payload: { + id: attemptId, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId, + providerTurnId, + nativeThreadId: input.nativeThreadId, + reason: "initial", + status: "completed", + startedAt, + completedAt, + }, + }, + { + ...nodeEvent, + driver, + id: EventId.make(`${runId}:provider-turn`), + type: "provider-turn.updated", + payload: turn, + }, + ...nativeTurn.messages.flatMap((message, index) => + messageEvents({ + threadId, + index, + message: { + ...message, + createdAt: DateTime.formatIso(message.role === "user" ? startedAt : completedAt), + }, + run, + turn, + }), + ), + ]; +} + const make = Effect.gen(function* () { const scanner = yield* AgentSessionScanner.AgentSessionScanner; const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -204,6 +331,7 @@ const make = Effect.gen(function* () { const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; const settingsService = yield* ServerSettings.ServerSettingsService; + const codexReaders = yield* Semaphore.make(2); const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode; const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* ( input: AgentSessionImportInput, @@ -641,7 +769,139 @@ const make = Effect.gen(function* () { return yield* commit(messages); }); - return { importRecentAgentThreads, importNativeHistory }; + const readCodexRefreshTarget = Effect.fn("AgentSessionImporter.readCodexRefreshTarget")( + function* (threadId: ThreadId) { + const { thread, providerThreads, runs, providerTurns } = yield* orchestrator.getThreadRecords( + threadId, + ["providerThreads", "runs", "providerTurns"], + ); + const owner = providerThreads.find( + (providerThread) => + providerThread.id === thread.activeProviderThreadId && + providerThread.appThreadId === threadId && + providerThread.ownerNodeId === null && + providerThread.driver === "codex" && + providerThread.nativeThreadRef?.strength === "strong", + ); + if ( + owner === undefined || + owner.nativeThreadRef?.nativeId == null || + thread.deletedAt !== null || + thread.archivedAt !== null || + runs.some((run) => run.status === "queued" || isActiveRun(run)) + ) { + return null; + } + const nativeId = owner.nativeThreadRef.nativeId; + const runByAttempt = new Map( + runs.flatMap((run) => + run.activeAttemptId === null || run.status === "rolled_back" + ? [] + : [[run.activeAttemptId, run] as const], + ), + ); + const ownedTurns = providerTurns.filter((turn) => turn.providerThreadId === owner.id); + const anchor = ownedTurns.findLast( + (turn) => + turn.runAttemptId !== null && + runByAttempt.has(turn.runAttemptId) && + turn.nativeTurnRef?.strength === "strong" && + turn.nativeTurnRef.nativeId !== null && + (turn.nativeThreadRef === undefined || turn.nativeThreadRef.nativeId === nativeId), + ); + const run = anchor?.runAttemptId == null ? undefined : runByAttempt.get(anchor.runAttemptId); + if (anchor?.nativeTurnRef?.nativeId == null || run === undefined) return null; + return { + thread, + owner, + nativeId, + anchor: anchor.nativeTurnRef.nativeId, + modelSelection: run.modelSelection, + runOrdinal: runs.at(-1)?.ordinal ?? 0, + turnOrdinal: ownedTurns.at(-1)?.ordinal ?? 0, + knownIds: new Set(ownedTurns.map((turn) => turn.nativeTurnRef?.nativeId)), + }; + }, + ); + + const refreshCodexHistory = Effect.fn("AgentSessionImporter.refreshCodexHistory")( + function* ({ threadId }: { readonly threadId: ThreadId }) { + const target = yield* readCodexRefreshTarget(threadId); + if (target === null) return 0; + const project = yield* projects.getById(target.thread.projectId); + if (Option.isNone(project)) return 0; + const cwd = target.thread.worktreePath ?? project.value.workspaceRoot; + const adapter = yield* registry.get(target.owner.providerInstanceId); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: target.owner.providerInstanceId, + threadId, + }); + const history = yield* adapter + .openSession({ + threadId, + providerSessionId, + modelSelection: target.modelSelection, + runtimePolicy: { + runtimeMode: target.thread.runtimeMode, + interactionMode: target.thread.interactionMode, + cwd, + }, + initialNativeThreadId: target.nativeId, + }) + .pipe( + Effect.flatMap( + (session) => + session.readHistoryAfter?.({ + providerThread: target.owner, + nativeTurnId: target.anchor, + }) ?? Effect.succeed([]), + ), + Effect.scoped, + codexReaders.withPermit, + Effect.timeout(CODEX_HISTORY_READ_TIMEOUT), + ); + const events: Array = []; + let runOrdinal = target.runOrdinal; + let turnOrdinal = target.turnOrdinal; + for (const nativeTurn of history) { + if (nativeTurn.status === "inProgress" || target.knownIds.has(nativeTurn.id)) break; + if (nativeTurn.status !== "completed" || nativeTurn.id === "") continue; + const indexOfUserMessage = nativeTurn.messages.findIndex( + (message) => message.role === "user", + ); + if (indexOfUserMessage < 0) continue; + target.knownIds.add(nativeTurn.id); + events.push( + ...externalTurnEvents({ + thread: target.thread, + owner: target.owner, + nativeThreadId: target.nativeId, + nativeTurn, + indexOfUserMessage, + runOrdinal: ++runOrdinal, + turnOrdinal: ++turnOrdinal, + ids: idAllocator.derive, + }), + ); + } + if (events.length === 0) return 0; + const stored = yield* eventSink.write({ unlessNativeThreadOwned: target.owner, events }); + return stored.length === 0 ? 0 : runOrdinal - target.runOrdinal; + }, + (effect, { threadId }) => + // A send after returning to the thread must take its ordinal after the sync. + threadCommands + .withLock(threadId, effect) + .pipe( + Effect.catch((cause) => + Effect.logDebug("Could not refresh Codex history", { threadId, cause }).pipe( + Effect.as(0), + ), + ), + ), + ); + + return { importRecentAgentThreads, importNativeHistory, refreshCodexHistory }; }); type AgentSessionImporterShape = Effect.Success; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 63d45c48816e4..ffa75507af45b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3058,6 +3058,8 @@ export const layerWsRpc = ( [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan, [WS_METHODS.agentSessionsImport]: (input) => agentSessionImporter.importRecentAgentThreads(input), + [WS_METHODS.agentSessionsRefreshCodexHistory]: (input) => + agentSessionImporter.refreshCodexHistory(input).pipe(Effect.asVoid), [WS_METHODS.assetsCreateUrl]: /* Request instrumentation already owns the span; keep this helper in that context. */ Effect.fnUntraced(function* (input) { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index a731a5798e191..6c9e9a0890c1c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -4102,7 +4102,14 @@ export default function ChatView(props: ChatViewProps) { onConfirm={onConfirmRevertStable} /> {embedded ? null : } - + ); diff --git a/apps/web/src/components/chat/ThreadVisitWatermark.tsx b/apps/web/src/components/chat/ThreadVisitWatermark.tsx index a60147aed86af..3fe31842f410f 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.tsx @@ -1,9 +1,14 @@ import { useAtomMount } from "@effect/atom-react"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits"; -import { type ScopedThreadRef } from "@t3tools/contracts"; +import { createEnvironmentRpcCommand, runAtomCommand } from "@t3tools/client-runtime/state/runtime"; +import { type ScopedThreadRef, WS_METHODS } from "@t3tools/contracts"; +import { useEffect } from "react"; import { environmentCatalog } from "../../connection/catalog"; +import { connectionAtomRuntime } from "../../connection/runtime"; +import { subscribeDocumentReturn } from "../../lib/documentActivity"; +import { appAtomRegistry } from "../../rpc/atomRegistry"; import { useUiStateStore } from "../../uiStateStore"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; @@ -15,10 +20,38 @@ const threadVisitTracker = createThreadVisitTracker({ useUiStateStore.getState().markThreadVisited(scopedThreadKey(ref), visitedAt), }); +const refreshCodexHistory = createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "environment-data:agent-sessions:refresh-codex-history", + tag: WS_METHODS.agentSessionsRefreshCodexHistory, +}); + // The visit watermark is the one part of the chat view that follows the // shell's updatedAt, which ticks while a run streams. The tracker subscribes to // it outside React, so ChatView keeps reading the quiet shell. -export function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRef }) { - useAtomMount(threadVisitTracker(props.threadRef)); +export function ThreadVisitWatermark({ + threadRef, + canRefreshCodexHistory, +}: { + readonly threadRef: ScopedThreadRef; + readonly canRefreshCodexHistory?: boolean; +}) { + useAtomMount(threadVisitTracker(threadRef)); + const { environmentId, threadId } = threadRef; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refresh the viewed native chat when the user returns to this window + useEffect(() => { + if (!canRefreshCodexHistory) return; + const refresh = () => { + if (document.visibilityState === "visible") { + void runAtomCommand( + appAtomRegistry, + refreshCodexHistory, + { environmentId, input: { threadId } }, + { reportFailure: false }, + ); + } + }; + refresh(); + return subscribeDocumentReturn(refresh); + }, [canRefreshCodexHistory, environmentId, threadId]); return null; } diff --git a/docs/user/welcome-page.md b/docs/user/welcome-page.md index cd7c518b3dea6..166a218e94c03 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -114,6 +114,10 @@ conversation adds new messages to the existing thread when the original history is intact and the thread has no turns run in T3 Code. You can continue without the remaining history. +After you run a turn in T3 Code, you can continue that same conversation in +Codex. Open the conversation in T3 Code or return to its window to pick up +recent completed text turns from the original Codex session. + You can start without importing. While an import runs, T3 Code stays on the Welcome page. If you quit, open the Welcome page again from **Settings → About**; the projects you started stay checked. diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 403f44394656b..159671c6888ba 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -155,11 +155,19 @@ describe("command permissions", () => { it.effect.each([ { method: WS_METHODS.serverRunStorageCleanup, scope: AuthSettingsWriteScope }, { method: WS_METHODS.serverReclaimDatabaseSpace, scope: AuthEnvironmentMaintainScope }, + { method: WS_METHODS.agentSessionsRefreshCodexHistory, scope: AuthOrchestrationOperateScope }, ])("requires the destination $scope grant for $method", ({ method, scope }) => Effect.gen(function* () { const registry = yield* setup; const command = createCommandPermissions(runtime, method); - registry.set(sessions(env), AsyncResult.success(grant(true))); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthOrchestrationReadScope], + permissions: [AuthOrchestrationReadScope], + }), + ); expect(registry.get(command.permissionAtom(env))).toBe(false); expect((yield* command.authorize(registry, env).pipe(Effect.flip))._tag).toBe( "EnvironmentAuthorizationError", diff --git a/packages/contracts/src/agentSessions.ts b/packages/contracts/src/agentSessions.ts index 93e0e36e4fbd4..b6565970a54bd 100644 --- a/packages/contracts/src/agentSessions.ts +++ b/packages/contracts/src/agentSessions.ts @@ -1,5 +1,11 @@ import * as Schema from "effect/Schema"; -import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { + IsoDateTime, + NonNegativeInt, + ProjectId, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex", "pi"]); @@ -78,6 +84,8 @@ export const AgentSessionImportResult = Schema.Struct({ }); export type AgentSessionImportResult = typeof AgentSessionImportResult.Type; +export const AgentSessionRefreshCodexHistoryInput = Schema.Struct({ threadId: ThreadId }); + export class AgentSessionScanError extends Schema.TaggedError()( "AgentSessionScanError", { diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 0b6164871a0ad..cdcf1c6b7b024 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -51,6 +51,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { // Writing a guide runs a model on this environment's providers, which reading one does not. [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, + [WS_METHODS.agentSessionsRefreshCodexHistory]: AuthOrchestrationOperateScope, [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlStar]: AuthSourceControlWriteScope, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 41733dae56417..ff65dcb7b8b04 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -97,6 +97,7 @@ import { AgentSessionImportProjectChangedError, AgentSessionImportProjectNotFoundError, AgentSessionImportResult, + AgentSessionRefreshCodexHistoryInput, AgentSessionScanInput, AgentSessionScanResult, AgentSessionScanError, @@ -458,6 +459,7 @@ export const WS_METHODS = { filesystemGetMetadata: "filesystem.getMetadata", agentSessionsScan: "agentSessions.scan", agentSessionsImport: "agentSessions.import", + agentSessionsRefreshCodexHistory: "agentSessions.refreshCodexHistory", assetsCreateUrl: "assets.createUrl", assetsPersistChatAttachments: "assets.persistChatAttachments", attachmentsCreateUploadUrl: "attachments.createUploadUrl", @@ -1610,6 +1612,15 @@ const WsAgentSessionsImportRpc = Rpc.make(WS_METHODS.agentSessionsImport, { ]), }); +const WsAgentSessionsRefreshCodexHistoryRpc = Rpc.make( + WS_METHODS.agentSessionsRefreshCodexHistory, + { + payload: AgentSessionRefreshCodexHistoryInput, + success: Schema.Void, + error: EnvironmentAuthorizationError, + }, +); + const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, { payload: AssetCreateUrlInput, success: AssetCreateUrlResult, @@ -2405,6 +2416,7 @@ export const WsRpcGroup = RpcGroup.make( WsFilesystemGetMetadataRpc, WsAgentSessionsScanRpc, WsAgentSessionsImportRpc, + WsAgentSessionsRefreshCodexHistoryRpc, WsAssetsCreateUrlRpc, WsAssetsPersistChatAttachmentsRpc, WsAttachmentsCreateUploadUrlRpc, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 62fe110dd5245..3969606b43ad6 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -35,6 +35,7 @@ import { TurnItemId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import type * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; import type * as Effect from "effect/Effect"; import type * as Scope from "effect/Scope"; @@ -697,6 +698,17 @@ export type ProviderAdapterV2SubagentOutcome = { readonly result: OrchestrationV2Subagent["result"]; }; +export interface ProviderAdapterV2HistoryTurn { + readonly id: string; + readonly status: "completed" | "interrupted" | "failed" | "inProgress"; + readonly startedAt: DateTime.Utc; + readonly completedAt: DateTime.Utc; + readonly messages: ReadonlyArray<{ + readonly role: "user" | "assistant"; + readonly text: string; + }>; +} + export interface ProviderAdapterV2SessionRuntime { readonly instanceId: ProviderInstanceId; readonly driver: ProviderDriverKind; @@ -798,6 +810,10 @@ export interface ProviderAdapterV2SessionRuntime { readonly readThreadSnapshot: ( input: ProviderAdapterV2ReadThreadSnapshotInput, ) => Effect.Effect; + /** Native turns after a known turn, oldest first. If the anchor is missing, returns no turns. */ + readonly readHistoryAfter?: ( + input: ProviderAdapterV2ReadThreadSnapshotInput & { readonly nativeTurnId: string }, + ) => Effect.Effect, ProviderAdapterV2Error>; readonly uploadFeedback?: (input: { readonly providerThread: OrchestrationV2ProviderThread; readonly reason?: string; From af6169de9b37438361f592a1a65fc256dd074b74 Mon Sep 17 00:00:00 2001 From: qi-hey <63509385+qi-hey@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:10:37 +0800 Subject: [PATCH 3/6] fix(codex): reconcile missed native history in order Hydrate complete Codex turns, keep the last reconciled boundary in durable history, and insert recovered turns before later local runs. Compare transcript prefixes in stored conversation order. --- .../Adapters/CodexAdapterV2.test.ts | 127 ++++++++- .../Adapters/CodexAdapterV2.ts | 91 +++++-- .../src/orchestration-v2/EffectOutbox.ts | 18 ++ .../src/orchestration-v2/runtimeLayer.ts | 1 + .../src/project/AgentSessionImporter.test.ts | 154 ++++++++++- .../src/project/AgentSessionImporter.ts | 249 +++++++++++++++--- packages/contracts/src/orchestrationV2.ts | 2 + .../src/server/ProviderAdapter.ts | 6 +- 8 files changed, 563 insertions(+), 85 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index ce2fa505f0332..5d13af2acf4f3 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -4925,23 +4925,57 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect("reads the Codex turn suffix across pages in conversation order", () => + it.effect("reads the complete text of the Codex turn suffix in conversation order", () => Effect.gen(function* () { const nativeThreadId = "external-history"; const nativeTurnId = "anchor"; - const turn = (id: string) => ({ + const user = (id: string, text = id) => ({ + type: "userMessage", + id, + content: [{ type: "text", text }], + }); + const answer = (id: string) => ({ + type: "agentMessage", + id: `${id}:assistant`, + text: `Reply to ${id}`, + }); + const turn = ( + id: string, + itemsView = "notLoaded", + items: Array | ReturnType> = [], + ) => ({ id, status: "completed", - items: [ - { type: "userMessage", id: `${id}:user`, content: [{ type: "text", text: id }] }, - { type: "agentMessage", id: `${id}:assistant`, text: `Reply to ${id}` }, - ], + startedAt: null, + completedAt: 1_785_000_000, + itemsView, + items, }); + const readMode = ( + id: number, + historyMode: "paginated" | "legacy", + ): Array => [ + { + type: "expect_outbound", + label: "thread/read", + frame: { + id, + method: "thread/read", + params: { threadId: nativeThreadId, includeTurns: false }, + }, + }, + { + type: "emit_inbound", + label: "thread/read", + frame: { id, result: { thread: { historyMode } } }, + }, + ]; const listPage = ( id: number, cursor: string | null, data: Array>, nextCursor: string | null, + itemsView = "notLoaded", ): Array => [ { type: "expect_outbound", @@ -4952,8 +4986,8 @@ describe("CodexAdapterV2 post-settle continuation", () => { params: { threadId: nativeThreadId, cursor, - limit: 32, - itemsView: "summary", + limit: itemsView === "full" ? 8 : 32, + itemsView, sortDirection: "desc", }, }, @@ -4964,33 +4998,102 @@ describe("CodexAdapterV2 post-settle continuation", () => { frame: { id, result: { data, nextCursor } }, }, ]; + const listItems = ( + id: number, + turnId: string, + cursor: string | null, + items: Array | ReturnType>, + nextCursor: string | null, + ): Array => [ + { + type: "expect_outbound", + label: "thread/items/list", + frame: { + id, + method: "thread/items/list", + params: { threadId: nativeThreadId, turnId, cursor, limit: 100, sortDirection: "asc" }, + }, + }, + { + type: "emit_inbound", + label: "thread/items/list", + frame: { + id, + result: { data: items.map((item) => ({ turnId, item })), nextCursor }, + }, + }, + ]; const { runtime, providerThread } = yield* makeCodexReplayHarness( makeCodexReplayTranscript({ scenario: "codex-external-history", entries: [ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Start" }).slice(0, 5), - ...listPage(3, null, [turn("newest")], "before-newest"), + ...readMode(3, "paginated"), + ...listPage(4, null, [turn("newest")], "before-newest"), ...listPage( - 4, + 5, "before-newest", [turn("older"), turn(nativeTurnId), turn("past")], null, ), - ...listPage(5, null, [turn("newest"), turn("older")], null), + ...listItems(6, "older", null, [user("older:user", "older")], "steer"), + ...listItems( + 7, + "older", + "steer", + [user("steer", "Steer the turn"), answer("older")], + null, + ), + ...readMode(8, "paginated"), + ...listPage(9, null, [turn("newest"), turn("older")], null), + ...readMode(10, "paginated"), + ...listPage(11, null, [turn("newest"), turn(nativeTurnId)], null), + ...listItems(12, "newest", null, [user("newest:user", "newest")], "stuck"), + ...listItems(13, "newest", "stuck", [answer("newest")], "stuck"), + ...readMode(14, "legacy"), + ...listPage( + 15, + null, + [ + turn("legacy", "full", [ + user("legacy:user", "legacy"), + user("steer", "Steer the turn"), + answer("legacy"), + ]), + turn(nativeTurnId, "full"), + ], + null, + "full", + ), ], }), ); const readHistory = runtime.readHistoryAfter!; - const appended = yield* readHistory({ providerThread, nativeTurnId }); + const appended = yield* readHistory({ + providerThread, + nativeTurnId, + knownNativeTurnIds: new Set(["newest"]), + }); assert.deepEqual( appended.map((turn) => turn.id), ["older", "newest"], ); assert.deepEqual(appended[0]?.messages, [ { role: "user", text: "older" }, + { role: "user", text: "Steer the turn" }, { role: "assistant", text: "Reply to older" }, ]); + assert.deepEqual(appended[0]?.startedAt, appended[0]?.completedAt); + assert.deepEqual(appended[1]?.messages, []); assert.deepEqual(yield* readHistory({ providerThread, nativeTurnId }), []); + const error = yield* Effect.flip(readHistory({ providerThread, nativeTurnId })); + assert.equal(error._tag, "ProviderAdapterReadThreadSnapshotError"); + const legacy = yield* readHistory({ providerThread, nativeTurnId }); + assert.deepEqual(legacy[0]?.messages, [ + { role: "user", text: "legacy" }, + { role: "user", text: "Steer the turn" }, + { role: "assistant", text: "Reply to legacy" }, + ]); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 782172ef13e60..6faed7da40450 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8789,9 +8789,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), mcpApps, readHistoryAfter: Effect.fn("CodexAdapterV2.readHistoryAfter")( - function* ({ providerThread, nativeTurnId }) { + function* ({ providerThread, nativeTurnId, knownNativeTurnIds }) { const threadId = yield* getNativeThreadId(providerThread); yield* ensureInitialized; + const { historyMode } = yield* readCodexThreadHistoryMetadata(client.raw, threadId); + const paginated = historyMode === "paginated"; const turns: Array = []; const visited = new Set(); let cursor: string | null = null; @@ -8799,35 +8801,78 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( visited.add(cursor); const page: CodexSchema.V2ThreadTurnsListResponse = yield* client.request( "thread/turns/list", - { threadId, cursor, limit: 32, itemsView: "summary", sortDirection: "desc" }, + { + threadId, + cursor, + limit: paginated ? 32 : 8, + itemsView: paginated ? "notLoaded" : "full", + sortDirection: "desc", + }, ); const anchor = page.data.findIndex((turn) => turn.id === nativeTurnId); if (anchor >= 0) { const observedAt = yield* DateTime.now; turns.push(...page.data.slice(0, anchor)); - return turns - .reverse() - .map((turn): ProviderAdapter.ProviderAdapterV2HistoryTurn => { - const startedAt = - turn.startedAt == null ? observedAt : codexTimestamp(turn.startedAt); - return { - id: turn.id, - status: turn.status, - startedAt, - completedAt: - turn.completedAt == null ? startedAt : codexTimestamp(turn.completedAt), - messages: turn.items.flatMap( - (item): ProviderAdapter.ProviderAdapterV2HistoryTurn["messages"] => { - if (item.type === "userMessage") { - return [{ role: "user", text: codexUserMessageText(item.content) }]; + const history: Array = []; + for (const turn of turns.reverse()) { + if (turn.status === "inProgress") break; + const start = turn.startedAt ?? turn.completedAt; + const startedAt = start == null ? observedAt : codexTimestamp(start); + const messages: Array< + ProviderAdapter.ProviderAdapterV2HistoryTurn["messages"][number] + > = []; + const addMessage = ( + item: CodexSchema.V2ThreadItemsListResponse__ThreadItem, + ) => { + if (item.type === "userMessage") { + messages.push({ role: "user", text: codexUserMessageText(item.content) }); + } else if (item.type === "agentMessage" && item.text.trim() !== "") { + messages.push({ role: "assistant", text: item.text }); + } + }; + if (turn.status === "completed" && !knownNativeTurnIds?.has(turn.id)) { + if (paginated) { + const itemCursors = new Set(); + let itemCursor: string | null = null; + do { + if (itemCursors.has(itemCursor)) { + return yield* toProtocolError( + `Codex repeated a history item cursor for turn ${turn.id}.`, + ); + } + itemCursors.add(itemCursor); + const items: CodexSchema.V2ThreadItemsListResponse = + yield* client.request("thread/items/list", { + threadId, + turnId: turn.id, + cursor: itemCursor, + limit: 100, + sortDirection: "asc", + }); + for (const entry of items.data) { + if (entry.turnId !== turn.id) { + return yield* toProtocolError( + `Codex returned history items for a different turn than ${turn.id}.`, + ); } - return item.type === "agentMessage" && item.text.trim() !== "" - ? [{ role: "assistant", text: item.text }] - : []; - }, - ), - }; + addMessage(entry.item); + } + itemCursor = items.nextCursor ?? null; + } while (itemCursor !== null); + } else { + for (const item of turn.items) addMessage(item); + } + } + history.push({ + id: turn.id, + status: turn.status, + startedAt, + completedAt: + turn.completedAt == null ? startedAt : codexTimestamp(turn.completedAt), + messages, }); + } + return history; } turns.push(...page.data); cursor = page.nextCursor ?? null; diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 4c94016e1c423..065254560f0c3 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -226,6 +226,10 @@ export interface EffectOutboxV2Shape { readonly listByCommandId: ( commandId: CommandId, ) => Effect.Effect, EffectOutboxError>; + readonly hasUnsettled: ( + threadId: ThreadId, + effectTypes: ReadonlyArray, + ) => Effect.Effect; /** A message's first steer effect: it records which runs were queued before the message. */ readonly firstSteer: ( threadId: ThreadId, @@ -477,6 +481,20 @@ export const layer: Layer.Layer = La : new EffectOutboxError({ operation: "list", cause }), ), ), + hasUnsettled: Effect.fn("EffectOutbox.hasUnsettled")(function* (threadId, effectTypes) { + if (effectTypes.length === 0) return false; + const rows = yield* sql` + SELECT 1 FROM orchestration_v2_effect_outbox + WHERE thread_id = ${threadId} + AND status IN ('pending', 'running') + AND effect_type IN ${sql.in(effectTypes)} + LIMIT 1 + `.pipe( + NodeSqliteClient.readOnly, + Effect.mapError((cause) => new EffectOutboxError({ operation: "list", cause })), + ); + return rows.length > 0; + }), firstSteer: (threadId, messageId) => sql` SELECT * diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index da06fd60e9000..5e76934929619 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -258,6 +258,7 @@ const layerAgentSessionImporterProvided = AgentSessionImporter.layer.pipe( layerProjectService, layerOrchestratorProvided, layerEventSink, + EffectOutbox.layer, IdAllocator.layer, ProviderSessionRuntime.layer, ProviderAdapterRegistry.layerFromProviderInstanceRegistry, diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index e1c096b7b1aad..e4ef4c4b341a2 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -4,6 +4,9 @@ import { type AgentSessionSource, type OrchestrationV2Run, type ServerSettingsError, + CheckpointId, + CheckpointRef, + CheckpointScopeId, EventId, ProjectId, ProviderDriverKind, @@ -14,6 +17,7 @@ import { RunAttemptId, RunId, ThreadId, + TurnItemId, type ApplicationStoredEvent, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, @@ -36,6 +40,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; import * as ServerConfig from "../config.ts"; +import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as EventStore from "../orchestration-v2/EventStore.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; @@ -63,6 +68,7 @@ const stores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( const persistence = Layer.mergeAll( stores, EventSink.layer.pipe(Layer.provide(stores)), + EffectOutbox.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), ProviderSessionRuntime.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), IdAllocator.layer, ); @@ -260,9 +266,9 @@ const makeImporter = Effect.fn(function* ( }), }), Layer.mock(Orchestrator.OrchestratorV2)({ - getThreadRecords: (threadId, fields) => + getThreadRecords: (threadId, fields, filter) => projections - .getThreadRecords(threadId, fields) + .getThreadRecords(threadId, fields, filter) .pipe( Effect.mapError( (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }), @@ -604,6 +610,8 @@ it.effect("appends new Codex messages to the existing import exactly once", () = const projections = yield* ProjectionStore.ProjectionStoreV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; const first = candidate(CODEX_MODEL_SELECTION, "continued-in-codex"); + const replyAt = "2026-09-01T09:59:59.000Z"; + first.thread.messages[1] = { role: "assistant", text: "Fixed", createdAt: replyAt }; const threadId = importId(first); expect(yield* (yield* makeImporter([first])).run).toEqual({ importedCount: 1, @@ -612,6 +620,7 @@ it.effect("appends new Codex messages to the existing import exactly once", () = const before = yield* projections.getThreadRecords(threadId, ["messages"]); const continued = candidate(CODEX_MODEL_SELECTION, first.source.providerSessionId); + continued.thread.messages[1] = { role: "assistant", text: "Fixed", createdAt: replyAt }; continued.source.size = 200; continued.source.mtimeMs = 3; continued.thread.messages.push( @@ -631,7 +640,7 @@ it.effect("appends new Codex messages to the existing import exactly once", () = expect(recorded).toEqual([continued.source]); expect(after.thread).toEqual(before.thread); expect(after.messages.slice(0, 2)).toEqual(before.messages); - expect(after.messages.map((message) => message.text)).toEqual([ + expect(after.turnItems.map((item) => ("text" in item ? item.text : null))).toEqual([ "Fix it", "Fixed", "Continue", @@ -641,7 +650,7 @@ it.effect("appends new Codex messages to the existing import exactly once", () = }).pipe(Effect.scoped, Effect.provide(persistence)), ); -it.effect("refreshes completed Codex turns after a turn run in T3", () => +it.effect("refreshes completed Codex turns in order, including gaps after a failed read", () => Effect.gen(function* () { const sink = yield* EventSink.EventSinkV2; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -744,12 +753,21 @@ it.effect("refreshes completed Codex turns after a turn run in T3", () => nativeTurn("outside-2", "Next Codex message", "inProgress"), ]; const readAnchors: Array = []; + let failRead = false; const session = { - readHistoryAfter: ({ nativeTurnId }) => - Effect.sync(() => { + readHistoryAfter: ({ nativeTurnId, providerThread }) => + Effect.suspend(() => { readAnchors.push(nativeTurnId); + if (failRead) { + return Effect.fail( + new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({ + driver: providerThread.driver, + providerThreadId: providerThread.id, + }), + ); + } const anchor = nativeHistory.findIndex((turn) => turn.id === nativeTurnId); - return anchor < 0 ? [] : nativeHistory.slice(anchor + 1); + return Effect.succeed(anchor < 0 ? [] : nativeHistory.slice(anchor + 1)); }), } satisfies Pick; const adapter = { @@ -777,22 +795,142 @@ it.effect("refreshes completed Codex turns after a turn run in T3", () => nativeHistory[3] = nativeTurn("outside-2", "Next Codex message"); expect(yield* refresh).toBe(1); + nativeHistory.push(nativeTurn("missed", "Missed Codex message")); + failRead = true; + expect(yield* refresh).toBe(0); + const continuedId = RunId.make(`${threadId}:continued`); + const continuedAttemptId = RunAttemptId.make(`${continuedId}:1`); + const continuedNodeId = NodeId.make(`${continuedId}:root`); + const checkpointId = CheckpointId.make(`${continuedId}:checkpoint`); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/continued"); + const continuedRun: OrchestrationV2Run = { + ...localRun, + id: continuedId, + ordinal: 5, + rootNodeId: continuedNodeId, + activeAttemptId: continuedAttemptId, + checkpointId, + }; + yield* sink.write({ + events: [ + { + id: EventId.make(`${continuedId}:created`), + type: "run.created", + threadId, + occurredAt: now, + payload: continuedRun, + }, + { + id: EventId.make(checkpointId), + type: "checkpoint.captured", + threadId, + occurredAt: now, + payload: { + id: checkpointId, + threadId, + scopeId: CheckpointScopeId.make(`${threadId}:scope`), + runId: continuedId, + nodeId: continuedNodeId, + parentCheckpointId: null, + ordinalWithinScope: 5, + appRunOrdinal: 5, + ref: checkpointRef, + status: "ready", + files: [], + capturedAt: now, + }, + }, + { + id: EventId.make(`${continuedId}:native`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make(`${continuedId}:native`), + providerThreadId: nativeThread.id, + nodeId: continuedNodeId, + runAttemptId: continuedAttemptId, + nativeTurnRef: { + driver: nativeThread.driver, + nativeId: "continued", + strength: "strong", + }, + ordinal: 4, + status: "completed", + startedAt: now, + completedAt: now, + }, + }, + { + id: EventId.make(`${continuedId}:prompt`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${continuedId}:prompt`), + threadId, + runId: continuedId, + nodeId: continuedNodeId, + providerThreadId: nativeThread.id, + providerTurnId: ProviderTurnId.make(`${continuedId}:native`), + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "user_message", + messageId: continuedRun.userMessageId, + createdBy: "user", + creationSource: "web", + inputIntent: "turn_start", + text: "Continued in T3", + attachments: [], + }, + }, + ], + }); + nativeHistory.push(nativeTurn("continued", "Continued in T3")); + failRead = false; + const restarted = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter)); + expect(yield* restarted.refreshCodexHistory({ threadId })).toBe(1); + expect(yield* refresh).toBe(0); + expect(readAnchors.slice(-3)).toEqual(["outside-2", "outside-2", "continued"]); + const after = yield* projections.getThreadRecords(threadId, [ "runs", "turnItems", "providerTurns", + "checkpoints", + ]); + expect(after.runs.map((run) => run.ordinal)).toEqual([1, 2, 3, 4, 5, 6]); + expect(after.runs.at(-1)?.id).toBe(continuedId); + expect(after.checkpoints).toMatchObject([ + { + id: checkpointId, + runId: continuedId, + ordinalWithinScope: 5, + appRunOrdinal: 6, + ref: checkpointRef, + }, ]); - expect(after.runs.map((run) => run.ordinal)).toEqual([1, 2, 3, 4]); expect(after.providerTurns.map((turn) => turn.nativeTurnRef?.nativeId)).toEqual([ "local-turn", "outside-1", "outside-2", + "missed", + "continued", ]); expect(after.turnItems.map((item) => ("text" in item ? item.text : null))).toEqual([ "From Codex", "Reply to From Codex", "Next Codex message", "Reply to Next Codex message", + "Missed Codex message", + "Reply to Missed Codex message", + "Continued in T3", ]); expect(after.turnItems[0]?.ordinal).toBeGreaterThan(2_000_000); expect(after.thread.id).toBe(threadId); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 8722c8f7e71b1..310e8b6311c6a 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -36,6 +36,7 @@ import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; +import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import type { ProviderAdapterV2HistoryTurn } from "@t3tools/provider-core/server/ProviderAdapter"; @@ -179,7 +180,10 @@ function messageEvents(input: { creationSource: message.creationSource, type: "user_message", messageId, - inputIntent: "turn_start", + inputIntent: + input.run !== undefined && input.run.userMessageId !== messageId + ? "steer" + : "turn_start", text: input.message.text, attachments: [], } @@ -229,6 +233,7 @@ function externalTurnEvents(input: { runAttemptId: attemptId, nativeTurnRef: { driver, nativeId: nativeTurn.id, strength: "strong" }, nativeThreadRef: { driver, nativeId: input.nativeThreadId, strength: "strong" }, + nativeHistoryReconciled: true, ordinal: input.turnOrdinal, status: "completed", startedAt, @@ -321,11 +326,25 @@ function externalTurnEvents(input: { ]; } +function shiftedOrdinals( + ordinals: ReadonlyArray, + insertions: ReadonlyArray, +): ReadonlyMap { + const shifted = new Map(); + let inserted = 0; + for (const ordinal of ordinals) { + while (inserted < insertions.length && insertions[inserted]! <= ordinal) inserted++; + if (inserted > 0) shifted.set(ordinal, ordinal + inserted); + } + return shifted; +} + const make = Effect.gen(function* () { const scanner = yield* AgentSessionScanner.AgentSessionScanner; const orchestrator = yield* Orchestrator.OrchestratorV2; const projects = yield* ProjectService.ProjectService; const eventSink = yield* EventSink.EventSinkV2; + const outbox = yield* EffectOutbox.EffectOutboxV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; @@ -451,15 +470,19 @@ const make = Effect.gen(function* () { }, { onConflict: "ignore" }, ); - const existing = yield* orchestrator.getThreadRecords(threadId, ["messages"]).pipe( - Effect.asSome, - Effect.catchIf( - (cause) => isProjectionStoreThreadNotFoundError(cause.cause), - () => Effect.succeedNone, - ), - ); + const existing = yield* orchestrator + .getThreadRecords(threadId, ["messages", "turnItems"], { + turnItemTypes: ["user_message", "assistant_message", "system_notice"], + }) + .pipe( + Effect.asSome, + Effect.catchIf( + (cause) => isProjectionStoreThreadNotFoundError(cause.cause), + () => Effect.succeedNone, + ), + ); if (Option.isSome(existing)) { - const { thread: current, messages: stored } = existing.value; + const { thread: current, messages, turnItems } = existing.value; if (current.projectId !== input.projectId) { return yield* new AgentSessionThreadProjectConflictError({ threadId, @@ -470,11 +493,15 @@ const make = Effect.gen(function* () { if (current.historyOrigin !== "v1_import") { return yield* new AgentSessionThreadModifiedError({ threadId }); } + const stored = turnItems.filter( + (item) => item.type === "user_message" || item.type === "assistant_message", + ); if ( + stored.length !== messages.length || stored.some( - (message, index) => - message.role !== thread.messages[index]?.role || - message.text !== thread.messages[index]?.text, + (item, index) => + (item.type === "user_message" ? "user" : "assistant") !== + thread.messages[index]?.role || item.text !== thread.messages[index]?.text, ) ) { return false; @@ -491,11 +518,10 @@ const make = Effect.gen(function* () { return false; } // Imported items are ordered before local runs, so only extend an intact import. - const { runs, turnItems, providerThreads } = yield* orchestrator.getThreadRecords( - threadId, - ["runs", "turnItems", "providerThreads"], - { turnItemTypes: ["system_notice"] }, - ); + const { runs, providerThreads } = yield* orchestrator.getThreadRecords(threadId, [ + "runs", + "providerThreads", + ]); const owner = providerThreads.find( (providerThread) => providerThread.id === current.activeProviderThreadId && @@ -771,10 +797,13 @@ const make = Effect.gen(function* () { const readCodexRefreshTarget = Effect.fn("AgentSessionImporter.readCodexRefreshTarget")( function* (threadId: ThreadId) { - const { thread, providerThreads, runs, providerTurns } = yield* orchestrator.getThreadRecords( - threadId, - ["providerThreads", "runs", "providerTurns"], - ); + const { thread, providerThreads, runs, providerTurns, attempts } = + yield* orchestrator.getThreadRecords(threadId, [ + "providerThreads", + "runs", + "providerTurns", + "attempts", + ]); const owner = providerThreads.find( (providerThread) => providerThread.id === thread.activeProviderThreadId && @@ -793,7 +822,7 @@ const make = Effect.gen(function* () { return null; } const nativeId = owner.nativeThreadRef.nativeId; - const runByAttempt = new Map( + const activeRunByAttempt = new Map( runs.flatMap((run) => run.activeAttemptId === null || run.status === "rolled_back" ? [] @@ -801,25 +830,45 @@ const make = Effect.gen(function* () { ), ); const ownedTurns = providerTurns.filter((turn) => turn.providerThreadId === owner.id); - const anchor = ownedTurns.findLast( - (turn) => - turn.runAttemptId !== null && - runByAttempt.has(turn.runAttemptId) && + const knownTurns = new Map( + ownedTurns.flatMap((turn) => turn.nativeTurnRef?.strength === "strong" && turn.nativeTurnRef.nativeId !== null && - (turn.nativeThreadRef === undefined || turn.nativeThreadRef.nativeId === nativeId), + (turn.nativeThreadRef === undefined || turn.nativeThreadRef.nativeId === nativeId) + ? [[turn.nativeTurnRef.nativeId, turn] as const] + : [], + ), + ); + const boundaries = [...knownTurns.entries()].filter( + ([, turn]) => + turn.runAttemptId !== null && + activeRunByAttempt.has(turn.runAttemptId) && + turn.status !== "running" && + turn.status !== "pending", ); - const run = anchor?.runAttemptId == null ? undefined : runByAttempt.get(anchor.runAttemptId); - if (anchor?.nativeTurnRef?.nativeId == null || run === undefined) return null; + const boundary = + boundaries.findLast(([, turn]) => turn.nativeHistoryReconciled) ?? boundaries[0]; + if (boundary === undefined) return null; + const [anchor, anchorTurn] = boundary; + const run = activeRunByAttempt.get(anchorTurn.runAttemptId!)!; + const runsById = new Map(runs.map((run) => [run.id, run])); + const runsByAttempt = new Map(activeRunByAttempt); + for (const attempt of attempts) { + const run = runsById.get(attempt.runId); + if (run !== undefined && run.status !== "rolled_back") runsByAttempt.set(attempt.id, run); + } return { thread, + providerThreads, owner, nativeId, - anchor: anchor.nativeTurnRef.nativeId, + anchor, modelSelection: run.modelSelection, - runOrdinal: runs.at(-1)?.ordinal ?? 0, - turnOrdinal: ownedTurns.at(-1)?.ordinal ?? 0, - knownIds: new Set(ownedTurns.map((turn) => turn.nativeTurnRef?.nativeId)), + runs, + ownedTurns, + knownTurns, + activeRunByAttempt, + runsByAttempt, }; }, ); @@ -828,6 +877,11 @@ const make = Effect.gen(function* () { function* ({ threadId }: { readonly threadId: ThreadId }) { const target = yield* readCodexRefreshTarget(threadId); if (target === null) return 0; + if ( + yield* outbox.hasUnsettled(threadId, ["provider-thread.rollback", "checkpoint.capture"]) + ) { + return 0; + } const project = yield* projects.getById(target.thread.projectId); if (Option.isNone(project)) return 0; const cwd = target.thread.worktreePath ?? project.value.workspaceRoot; @@ -854,23 +908,136 @@ const make = Effect.gen(function* () { session.readHistoryAfter?.({ providerThread: target.owner, nativeTurnId: target.anchor, + knownNativeTurnIds: new Set(target.knownTurns.keys()), }) ?? Effect.succeed([]), ), Effect.scoped, codexReaders.withPermit, Effect.timeout(CODEX_HISTORY_READ_TIMEOUT), ); - const events: Array = []; - let runOrdinal = target.runOrdinal; - let turnOrdinal = target.turnOrdinal; + const settled = []; for (const nativeTurn of history) { - if (nativeTurn.status === "inProgress" || target.knownIds.has(nativeTurn.id)) break; + if (nativeTurn.status === "inProgress") break; + settled.push(nativeTurn); + } + const additions = []; + let beforeRun = (target.runs.at(-1)?.ordinal ?? 0) + 1; + let beforeTurn = (target.ownedTurns.at(-1)?.ordinal ?? 0) + 1; + let boundary: OrchestrationV2ProviderTurn | undefined; + const seen = new Set([target.anchor]); + for (const nativeTurn of settled.reverse()) { + if (seen.has(nativeTurn.id)) return 0; + seen.add(nativeTurn.id); + const known = target.knownTurns.get(nativeTurn.id); + if (known !== undefined) { + beforeTurn = known.ordinal; + const attemptId = known.runAttemptId; + if (attemptId !== null) { + beforeRun = Math.min( + beforeRun, + target.runsByAttempt.get(attemptId)?.ordinal ?? beforeRun, + ); + if (target.activeRunByAttempt.has(attemptId)) boundary ??= known; + } + continue; + } if (nativeTurn.status !== "completed" || nativeTurn.id === "") continue; const indexOfUserMessage = nativeTurn.messages.findIndex( (message) => message.role === "user", ); if (indexOfUserMessage < 0) continue; - target.knownIds.add(nativeTurn.id); + additions.push({ nativeTurn, indexOfUserMessage, beforeRun, beforeTurn }); + } + additions.reverse(); + const movedRuns = shiftedOrdinals( + target.runs.map((run) => run.ordinal), + additions.map((turn) => turn.beforeRun), + ); + const movedTurns = shiftedOrdinals( + target.ownedTurns.map((turn) => turn.ordinal), + additions.map((turn) => turn.beforeTurn), + ); + const events: Array = []; + const occurredAt = yield* DateTime.now; + // Move the suffix back to front to free the unique ordinals before inserting into them. + for (const run of target.runs.toReversed()) { + const ordinal = movedRuns.get(run.ordinal); + if (ordinal === undefined) continue; + events.push({ + id: yield* idAllocator.allocate.event({ threadId }), + type: "run.updated", + threadId, + occurredAt, + payload: { ...run, ordinal }, + }); + } + for (const turn of target.ownedTurns.toReversed()) { + const ordinal = movedTurns.get(turn.ordinal); + const markBoundary = turn.id === boundary?.id && !turn.nativeHistoryReconciled; + if (ordinal === undefined && !markBoundary) continue; + events.push({ + id: yield* idAllocator.allocate.event({ threadId }), + type: "provider-turn.updated", + threadId, + driver: target.owner.driver, + occurredAt, + payload: { + ...turn, + ordinal: ordinal ?? turn.ordinal, + ...(markBoundary ? { nativeHistoryReconciled: true } : {}), + }, + }); + } + if (movedRuns.size > 0) { + const runIds = target.runs.filter((run) => movedRuns.has(run.ordinal)).map((run) => run.id); + const { checkpoints, turnItems } = yield* orchestrator.getThreadRecords( + threadId, + ["checkpoints", "turnItems"], + { turnItemRunIds: runIds }, + ); + for (const providerThread of target.providerThreads) { + const first = providerThread.firstRunOrdinal; + const last = providerThread.lastRunOrdinal; + const firstRunOrdinal = first === null ? null : (movedRuns.get(first) ?? first); + const lastRunOrdinal = last === null ? null : (movedRuns.get(last) ?? last); + if (firstRunOrdinal === first && lastRunOrdinal === last) continue; + events.push({ + id: yield* idAllocator.allocate.event({ threadId }), + type: "provider-thread.updated", + threadId, + occurredAt, + payload: { ...providerThread, firstRunOrdinal, lastRunOrdinal }, + }); + } + for (const checkpoint of checkpoints) { + if (checkpoint.appRunOrdinal === null) continue; + const appRunOrdinal = movedRuns.get(checkpoint.appRunOrdinal); + if (appRunOrdinal === undefined) continue; + events.push({ + id: yield* idAllocator.allocate.event({ threadId }), + type: "checkpoint.captured", + threadId, + occurredAt, + payload: { ...checkpoint, appRunOrdinal }, + }); + } + const itemsByRun = Map.groupBy(turnItems, (item) => item.runId); + for (const runId of runIds.toReversed()) { + for (const item of itemsByRun.get(runId) ?? []) { + events.push({ + id: yield* idAllocator.allocate.event({ threadId }), + type: "turn-item.updated", + threadId, + occurredAt, + payload: item, + }); + } + } + } + for (const [ + index, + { nativeTurn, indexOfUserMessage, beforeRun, beforeTurn }, + ] of additions.entries()) { events.push( ...externalTurnEvents({ thread: target.thread, @@ -878,15 +1045,15 @@ const make = Effect.gen(function* () { nativeThreadId: target.nativeId, nativeTurn, indexOfUserMessage, - runOrdinal: ++runOrdinal, - turnOrdinal: ++turnOrdinal, + runOrdinal: beforeRun + index, + turnOrdinal: beforeTurn + index, ids: idAllocator.derive, }), ); } if (events.length === 0) return 0; const stored = yield* eventSink.write({ unlessNativeThreadOwned: target.owner, events }); - return stored.length === 0 ? 0 : runOrdinal - target.runOrdinal; + return stored.length === 0 ? 0 : additions.length; }, (effect, { threadId }) => // A send after returning to the thread must take its ordinal after the sync. diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index c5286116655dd..d311e7fbf0b10 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1237,6 +1237,8 @@ export const OrchestrationV2ProviderTurn = Schema.Struct({ nativeTurnRef: Schema.NullOr(OrchestrationV2ProviderRef), /** The native session that held this turn, when a provider can move a thread between sessions. */ nativeThreadRef: Schema.optional(OrchestrationV2ProviderRef), + /** A successful Codex history scan has reconciled through this turn. */ + nativeHistoryReconciled: Schema.optionalKey(Schema.Literal(true)), ordinal: PositiveInt, status: Schema.Literals([ "pending", diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 3969606b43ad6..3d09a15f79708 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -812,7 +812,11 @@ export interface ProviderAdapterV2SessionRuntime { ) => Effect.Effect; /** Native turns after a known turn, oldest first. If the anchor is missing, returns no turns. */ readonly readHistoryAfter?: ( - input: ProviderAdapterV2ReadThreadSnapshotInput & { readonly nativeTurnId: string }, + input: ProviderAdapterV2ReadThreadSnapshotInput & { + readonly nativeTurnId: string; + /** Keep these turns in the result for ordering, but omit their messages. */ + readonly knownNativeTurnIds?: ReadonlySet; + }, ) => Effect.Effect, ProviderAdapterV2Error>; readonly uploadFeedback?: (input: { readonly providerThread: OrchestrationV2ProviderThread; From 7247ad59dc56e9b33e727c5c5982ef21e62c6d14 Mon Sep 17 00:00:00 2001 From: qi-hey <63509385+qi-hey@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:43:46 +0800 Subject: [PATCH 4/6] fix(codex): resume history scans and preserve native boundaries Resume legacy history scans across visits and defer gaps that cannot be inserted in native order. Rewind from the actual Codex checkpoint boundary and relocate current turn items in the committing transaction. --- .../Adapters/CodexAdapterV2.test.ts | 59 ++++- .../Adapters/CodexAdapterV2.ts | 243 +++++++++++++----- apps/server/src/orchestration-v2/EventSink.ts | 41 ++- .../src/project/AgentSessionImporter.test.ts | 105 +++++++- .../src/project/AgentSessionImporter.ts | 51 ++-- .../src/provider/CodexThreadRevert.test.ts | 23 +- apps/server/src/provider/CodexThreadRevert.ts | 25 +- 7 files changed, 435 insertions(+), 112 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 5d13af2acf4f3..6ed52427fa464 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -4976,6 +4976,8 @@ describe("CodexAdapterV2 post-settle continuation", () => { data: Array>, nextCursor: string | null, itemsView = "notLoaded", + backwardsCursor?: string, + headCheck = false, ): Array => [ { type: "expect_outbound", @@ -4986,16 +4988,23 @@ describe("CodexAdapterV2 post-settle continuation", () => { params: { threadId: nativeThreadId, cursor, - limit: itemsView === "full" ? 8 : 32, + limit: headCheck ? 1 : itemsView === "full" ? 8 : 32, itemsView, - sortDirection: "desc", + sortDirection: headCheck ? "asc" : "desc", }, }, }, { type: "emit_inbound", label: "thread/turns/list", - frame: { id, result: { data, nextCursor } }, + frame: { + id, + result: { + data, + nextCursor, + ...(backwardsCursor === undefined ? {} : { backwardsCursor }), + }, + }, }, ]; const listItems = ( @@ -5060,8 +5069,28 @@ describe("CodexAdapterV2 post-settle continuation", () => { user("steer", "Steer the turn"), answer("legacy"), ]), - turn(nativeTurnId, "full"), ], + "older-1", + "full", + "legacy-head", + ), + ...listPage(16, "older-1", [turn("local-3", "full")], "older-2", "full"), + ...listPage(17, "older-2", [turn("local-2", "full")], "older-3", "full"), + ...listPage(18, "older-3", [turn("local-1", "full")], "older-4", "full"), + ...readMode(19, "legacy"), + ...listPage( + 20, + "legacy-head", + [turn("legacy")], + "new-append", + "notLoaded", + undefined, + true, + ), + ...listPage( + 21, + "older-4", + [turn("missed-legacy", "full", [user("missed-legacy")]), turn(nativeTurnId, "full")], null, "full", ), @@ -5088,8 +5117,14 @@ describe("CodexAdapterV2 post-settle continuation", () => { assert.deepEqual(yield* readHistory({ providerThread, nativeTurnId }), []); const error = yield* Effect.flip(readHistory({ providerThread, nativeTurnId })); assert.equal(error._tag, "ProviderAdapterReadThreadSnapshotError"); + assert.deepEqual(yield* readHistory({ providerThread, nativeTurnId }), []); const legacy = yield* readHistory({ providerThread, nativeTurnId }); - assert.deepEqual(legacy[0]?.messages, [ + assert.deepEqual( + legacy.map((turn) => turn.id), + ["missed-legacy", "local-1", "local-2", "local-3", "legacy"], + ); + assert.deepEqual(legacy[0]?.messages, [{ role: "user", text: "missed-legacy" }]); + assert.deepEqual(legacy.at(-1)?.messages, [ { role: "user", text: "legacy" }, { role: "user", text: "Steer the turn" }, { role: "assistant", text: "Reply to legacy" }, @@ -10552,7 +10587,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect("unarchives an unloaded Codex thread before rolling it back", () => + it.effect("unarchives a Codex thread and reverts all native turns after the checkpoint", () => Effect.gen(function* () { const nativeThreadId = "archived-rollback-thread"; const resumeParams = { @@ -10605,13 +10640,17 @@ describe("CodexAdapterV2 post-settle continuation", () => { { threadId: nativeThreadId, cursor: null, - limit: 1, + limit: 32, sortDirection: "desc", - itemsView: "summary", + itemsView: "notLoaded", }, { result: { - data: [{ id: "native-turn-second", items: [], status: "completed", error: null }], + data: [ + { id: "native-turn-second", items: [], status: "completed", error: null }, + { id: "external-interrupted", items: [], status: "interrupted", error: null }, + { id: "native-turn-first", items: [], status: "completed", error: null }, + ], nextCursor: null, }, }, @@ -10619,7 +10658,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { ...exchange( 8, "thread/revert", - { threadId: nativeThreadId, beforeTurnId: "native-turn-second" }, + { threadId: nativeThreadId, beforeTurnId: "external-interrupted" }, { result: thread }, ), ], diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 6faed7da40450..7d95dfdef7dca 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1098,6 +1098,30 @@ const CodexThreadHistoryMetadata = Schema.Struct({ }); const decodeCodexThreadHistoryMetadata = Schema.decodeUnknownEffect(CodexThreadHistoryMetadata); +type CodexHistoryTurn = ProviderAdapter.ProviderAdapterV2HistoryTurn; +type LegacyHistoryRead = { + readonly anchor: string; + readonly head: CodexHistoryTurn; + readonly headCursor: string | null; + readonly turns: Array; + readonly cursors: Set; + cursor: string; +}; + +const LEGACY_HISTORY_PAGES_PER_READ = 4; +const LEGACY_HISTORY_READ_CACHE_SIZE = 8; + +function codexHistoryMessage( + item: CodexSchema.V2ThreadItemsListResponse__ThreadItem, +): CodexHistoryTurn["messages"][number] | undefined { + if (item.type === "userMessage") + return { role: "user", text: codexUserMessageText(item.content) }; + if (item.type === "agentMessage" && item.text.trim() !== "") { + return { role: "assistant", text: item.text }; + } + return undefined; +} + const readCodexThreadHistoryMetadata = Effect.fn("CodexAdapterV2.readThreadHistoryMetadata")( function* ( raw: Pick, @@ -1917,6 +1941,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( threadId === null ? Effect.undefined : mcpSessions.read(threadId); const { clientFactory, digest, fileSystem, idAllocator, serverConfig } = adapterOptions; const continuationRequests = adapterOptions.continuationRequests; + const legacyHistoryReads = new Map(); return ProviderAdapter.ProviderAdapterV2.of({ instanceId: adapterOptions.instanceId, @@ -8794,89 +8819,155 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* ensureInitialized; const { historyMode } = yield* readCodexThreadHistoryMetadata(client.raw, threadId); const paginated = historyMode === "paginated"; - const turns: Array = []; - const visited = new Set(); - let cursor: string | null = null; - do { - visited.add(cursor); - const page: CodexSchema.V2ThreadTurnsListResponse = yield* client.request( - "thread/turns/list", - { + const observedAt = yield* DateTime.now; + let pending = paginated ? undefined : legacyHistoryReads.get(threadId); + if (pending !== undefined && pending.anchor === nativeTurnId) { + // Check the saved head before reusing pages. Newer turns may be appended meanwhile. + const head = yield* client + .request("thread/turns/list", { + threadId, + cursor: pending.headCursor, + limit: 1, + itemsView: "notLoaded", + sortDirection: pending.headCursor === null ? "desc" : "asc", + }) + .pipe( + Effect.catchIf( + (error) => + error._tag === "CodexAppServerRequestError" && + error.errorMessage.startsWith("invalid cursor:"), + () => Effect.succeed(null), + ), + ); + if ( + head?.data[0]?.id !== pending.head.id || + head.data[0].status !== pending.head.status + ) { + pending = undefined; + } + } else { + pending = undefined; + } + if (pending === undefined) legacyHistoryReads.delete(threadId); + const turns = pending?.turns ?? []; + const cursors = pending?.cursors ?? new Set(); + let cursor = pending?.cursor ?? null; + const pageLimit = paginated ? Infinity : LEGACY_HISTORY_PAGES_PER_READ; + for (let index = 0; index < pageLimit; index++) { + const page: CodexSchema.V2ThreadTurnsListResponse = yield* client + .request("thread/turns/list", { threadId, cursor, limit: paginated ? 32 : 8, itemsView: paginated ? "notLoaded" : "full", sortDirection: "desc", - }, - ); + }) + .pipe( + Effect.tapError((error) => + Effect.sync(() => { + if ( + error._tag === "CodexAppServerRequestError" && + error.errorMessage.startsWith("invalid cursor:") + ) { + legacyHistoryReads.delete(threadId); + } + }), + ), + ); const anchor = page.data.findIndex((turn) => turn.id === nativeTurnId); + for (const turn of anchor < 0 ? page.data : page.data.slice(0, anchor)) { + const start = turn.startedAt ?? turn.completedAt; + const startedAt = start == null ? observedAt : codexTimestamp(start); + turns.push({ + id: turn.id, + status: turn.status, + startedAt, + completedAt: + turn.completedAt == null ? startedAt : codexTimestamp(turn.completedAt), + messages: + !paginated && turn.status === "completed" && !knownNativeTurnIds?.has(turn.id) + ? turn.items.flatMap((item) => { + const message = codexHistoryMessage(item); + return message === undefined ? [] : [message]; + }) + : [], + }); + } if (anchor >= 0) { - const observedAt = yield* DateTime.now; - turns.push(...page.data.slice(0, anchor)); - const history: Array = []; + legacyHistoryReads.delete(threadId); + const history: Array = []; for (const turn of turns.reverse()) { if (turn.status === "inProgress") break; - const start = turn.startedAt ?? turn.completedAt; - const startedAt = start == null ? observedAt : codexTimestamp(start); - const messages: Array< - ProviderAdapter.ProviderAdapterV2HistoryTurn["messages"][number] - > = []; - const addMessage = ( - item: CodexSchema.V2ThreadItemsListResponse__ThreadItem, - ) => { - if (item.type === "userMessage") { - messages.push({ role: "user", text: codexUserMessageText(item.content) }); - } else if (item.type === "agentMessage" && item.text.trim() !== "") { - messages.push({ role: "assistant", text: item.text }); + if ( + !paginated || + turn.status !== "completed" || + knownNativeTurnIds?.has(turn.id) + ) { + history.push(turn); + continue; + } + const messages: Array = []; + const itemCursors = new Set(); + let itemCursor: string | null = null; + do { + if (itemCursors.has(itemCursor)) { + return yield* toProtocolError( + `Codex repeated a history item cursor for turn ${turn.id}.`, + ); } - }; - if (turn.status === "completed" && !knownNativeTurnIds?.has(turn.id)) { - if (paginated) { - const itemCursors = new Set(); - let itemCursor: string | null = null; - do { - if (itemCursors.has(itemCursor)) { - return yield* toProtocolError( - `Codex repeated a history item cursor for turn ${turn.id}.`, - ); - } - itemCursors.add(itemCursor); - const items: CodexSchema.V2ThreadItemsListResponse = - yield* client.request("thread/items/list", { - threadId, - turnId: turn.id, - cursor: itemCursor, - limit: 100, - sortDirection: "asc", - }); - for (const entry of items.data) { - if (entry.turnId !== turn.id) { - return yield* toProtocolError( - `Codex returned history items for a different turn than ${turn.id}.`, - ); - } - addMessage(entry.item); - } - itemCursor = items.nextCursor ?? null; - } while (itemCursor !== null); - } else { - for (const item of turn.items) addMessage(item); + itemCursors.add(itemCursor); + const items: CodexSchema.V2ThreadItemsListResponse = yield* client.request( + "thread/items/list", + { + threadId, + turnId: turn.id, + cursor: itemCursor, + limit: 100, + sortDirection: "asc", + }, + ); + for (const entry of items.data) { + if (entry.turnId !== turn.id) { + return yield* toProtocolError( + `Codex returned history items for a different turn than ${turn.id}.`, + ); + } + const message = codexHistoryMessage(entry.item); + if (message !== undefined) messages.push(message); } - } - history.push({ - id: turn.id, - status: turn.status, - startedAt, - completedAt: - turn.completedAt == null ? startedAt : codexTimestamp(turn.completedAt), - messages, - }); + itemCursor = items.nextCursor ?? null; + } while (itemCursor !== null); + history.push({ ...turn, messages }); } return history; } - turns.push(...page.data); - cursor = page.nextCursor ?? null; - } while (cursor !== null && !visited.has(cursor)); + const next = page.nextCursor; + if (next == null || cursors.has(next) || page.data.length === 0) { + legacyHistoryReads.delete(threadId); + return []; + } + cursors.add(next); + cursor = next; + if (!paginated) { + if (pending === undefined) { + pending = { + anchor: nativeTurnId, + head: turns[0]!, + headCursor: page.backwardsCursor ?? null, + turns, + cursors, + cursor, + }; + if (legacyHistoryReads.size >= LEGACY_HISTORY_READ_CACHE_SIZE) { + const oldest = legacyHistoryReads.keys().next().value; + if (oldest !== undefined) legacyHistoryReads.delete(oldest); + } + legacyHistoryReads.set(threadId, pending); + } else { + pending.cursor = cursor; + } + } + } return []; }, (effect, { providerThread }) => @@ -8934,7 +9025,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( threadInput.target.type === "provider_turn" ? threadInput.target.providerTurn.nativeTurnRef : null; - if (numTurns === 0) { + const afterTurnId = + nativeConversationHeadRef?.strength === "strong" + ? (nativeConversationHeadRef.nativeId ?? undefined) + : undefined; + if (numTurns === 0 && afterTurnId === undefined) { return { providerThread: { ...threadInput.providerThread, @@ -8969,7 +9064,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); } const response = yield* ensureInitialized.pipe( - Effect.andThen(revertCodexThread(client, threadId, numTurns)), + Effect.andThen( + revertCodexThread( + client, + threadId, + afterTurnId === undefined ? numTurns : { afterTurnId }, + ), + ), ); turnTokenUsageByThread.delete(threadId); return { diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index cad0aff3afb19..a6d75775a1ea9 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -1,5 +1,6 @@ import { CommandId, + EventId, type OrchestrationV2Run, OrchestrationV2DomainEvent, type OrchestrationV2ProviderThread, @@ -114,6 +115,8 @@ export interface EventSinkV2Shape { "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" >; readonly guardPendingUserInputCancellations?: boolean; + /** Reposition items of updated runs using the rows current at commit time. */ + readonly repositionRunItems?: boolean; readonly commandId?: CommandId; readonly events: ReadonlyArray; }) => Effect.Effect, EventSinkV2Error>; @@ -128,6 +131,7 @@ export interface EventSinkV2Shape { "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" >; readonly guardPendingUserInputCancellations?: boolean; + readonly repositionRunItems?: boolean; readonly commandId?: CommandId; readonly events: ReadonlyArray; readonly effects: ReadonlyArray; @@ -481,6 +485,34 @@ const layerBase: Layer.Layer< ); }); + const repositionRunItems = Effect.fnUntraced(function* ( + threadId: ThreadId, + events: ReadonlyArray, + ) { + const runIds = events.flatMap((event) => + event.threadId === threadId && event.type === "run.updated" ? [event.payload.id] : [], + ); + if (runIds.length === 0) return events; + const { turnItems } = yield* projectionStore.getThreadRecords(threadId, ["turnItems"], { + turnItemRunIds: runIds, + }); + const itemsByRun = Map.groupBy(turnItems, (item) => item.runId); + return events.flatMap((event): ReadonlyArray => + event.type === "run.updated" && event.threadId === threadId + ? [ + event, + ...(itemsByRun.get(event.payload.id) ?? []).map((item) => ({ + type: "turn-item.updated" as const, + id: EventId.make(`${event.id}:position:${item.id}`), + threadId, + occurredAt: event.occurredAt, + payload: item, + })), + ] + : [event], + ); + }); + const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* ( input: Parameters[0], ) { @@ -514,10 +546,15 @@ const layerBase: Layer.Layer< const events = input.updateDelegatedCompletionOnly ? yield* updateDelegatedCompletionOnly(input.events, () => true) : input.events; + const threadId = events[0]?.threadId; + const withPositions = + input.repositionRunItems && threadId !== undefined + ? yield* repositionRunItems(threadId, events) + : events; const normalized = yield* normalizeEvents( input.guardPendingUserInputCancellations === true - ? yield* guardUserInputCancellations(events) - : events, + ? yield* guardUserInputCancellations(withPositions) + : withPositions, ); const committed = yield* eventStore.append({ ...(input.commandId === undefined ? {} : { commandId: input.commandId }), diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index e4ef4c4b341a2..7b2b994981c0f 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -811,6 +811,24 @@ it.effect("refreshes completed Codex turns in order, including gaps after a fail activeAttemptId: continuedAttemptId, checkpointId, }; + const backgroundCommand = { + id: TurnItemId.make(`${continuedId}:background`), + threadId, + runId: continuedId, + nodeId: continuedNodeId, + providerThreadId: nativeThread.id, + providerTurnId: ProviderTurnId.make(`${continuedId}:native`), + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "running" as const, + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "command_execution" as const, + input: "build", + }; yield* sink.write({ events: [ { @@ -890,11 +908,39 @@ it.effect("refreshes completed Codex turns in order, including gaps after a fail attachments: [], }, }, + { + id: EventId.make(`${continuedId}:background-started`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: backgroundCommand, + }, ], }); nativeHistory.push(nativeTurn("continued", "Continued in T3")); failRead = false; - const restarted = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter)); + const restarted = yield* makeImporter( + [], + sink + .write({ + events: [ + { + id: EventId.make(`${continuedId}:background-finished`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + ...backgroundCommand, + status: "completed", + completedAt: now, + output: "Build succeeded", + }, + }, + ], + }) + .pipe(Effect.orDie, Effect.asVoid), + () => Effect.succeed(adapter), + ); expect(yield* restarted.refreshCodexHistory({ threadId })).toBe(1); expect(yield* refresh).toBe(0); expect(readAnchors.slice(-3)).toEqual(["outside-2", "outside-2", "continued"]); @@ -923,7 +969,7 @@ it.effect("refreshes completed Codex turns in order, including gaps after a fail "missed", "continued", ]); - expect(after.turnItems.map((item) => ("text" in item ? item.text : null))).toEqual([ + expect(after.turnItems.flatMap((item) => ("text" in item ? [item.text] : []))).toEqual([ "From Codex", "Reply to From Codex", "Next Codex message", @@ -932,8 +978,63 @@ it.effect("refreshes completed Codex turns in order, including gaps after a fail "Reply to Missed Codex message", "Continued in T3", ]); + expect(after.turnItems.at(-1)).toMatchObject({ + id: backgroundCommand.id, + ordinal: 6_000_002, + status: "completed", + output: "Build succeeded", + }); expect(after.turnItems[0]?.ordinal).toBeGreaterThan(2_000_000); expect(after.thread.id).toBe(threadId); + + // A held run submitted before the continuation can reach Codex after it. + const heldAttemptId = RunAttemptId.make(`${laterRun.id}:1`); + const heldNodeId = NodeId.make(`${laterRun.id}:root`); + yield* sink.write({ + events: [ + { + id: EventId.make(`${laterRun.id}:held-completed`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + ...laterRun, + activeAttemptId: heldAttemptId, + rootNodeId: heldNodeId, + status: "completed", + startedAt: now, + completedAt: now, + }, + }, + { + id: EventId.make(`${laterRun.id}:held-native`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make(`${laterRun.id}:held-native`), + providerThreadId: nativeThread.id, + nodeId: heldNodeId, + runAttemptId: heldAttemptId, + nativeTurnRef: { driver: nativeThread.driver, nativeId: "held", strength: "strong" }, + ordinal: 6, + status: "completed", + startedAt: now, + completedAt: now, + }, + }, + ], + }); + nativeHistory.push( + nativeTurn("before-held", "Before the held run"), + nativeTurn("held", "Held"), + ); + expect(yield* refresh).toBe(0); + expect(yield* refresh).toBe(0); + expect(readAnchors.slice(-2)).toEqual(["continued", "continued"]); + expect((yield* projections.getThreadRecords(threadId, ["turnItems"])).turnItems).toEqual( + after.turnItems, + ); }).pipe(Effect.scoped, Effect.provide(persistence)), ); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 310e8b6311c6a..01912c17015a5 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -857,12 +857,21 @@ const make = Effect.gen(function* () { const run = runsById.get(attempt.runId); if (run !== undefined && run.status !== "rolled_back") runsByAttempt.set(attempt.id, run); } + let anchorRunOrdinal = run.ordinal; + for (const turn of knownTurns.values()) { + if (turn.ordinal > anchorTurn.ordinal || turn.runAttemptId === null) continue; + const preceding = runsByAttempt.get(turn.runAttemptId); + if (preceding !== undefined) + anchorRunOrdinal = Math.max(anchorRunOrdinal, preceding.ordinal); + } return { thread, providerThreads, owner, nativeId, anchor, + anchorRunOrdinal, + anchorTurnOrdinal: anchorTurn.ordinal, modelSelection: run.modelSelection, runs, ownedTurns, @@ -916,9 +925,21 @@ const make = Effect.gen(function* () { Effect.timeout(CODEX_HISTORY_READ_TIMEOUT), ); const settled = []; + const preceding = new Map(); + let lastRun = target.anchorRunOrdinal; + let lastTurn = target.anchorTurnOrdinal; for (const nativeTurn of history) { if (nativeTurn.status === "inProgress") break; settled.push(nativeTurn); + const known = target.knownTurns.get(nativeTurn.id); + if (known === undefined) { + preceding.set(nativeTurn.id, { run: lastRun, turn: lastTurn }); + continue; + } + const run = + known.runAttemptId === null ? undefined : target.runsByAttempt.get(known.runAttemptId); + lastTurn = Math.max(lastTurn, known.ordinal); + if (run !== undefined) lastRun = Math.max(lastRun, run.ordinal); } const additions = []; let beforeRun = (target.runs.at(-1)?.ordinal ?? 0) + 1; @@ -930,7 +951,7 @@ const make = Effect.gen(function* () { seen.add(nativeTurn.id); const known = target.knownTurns.get(nativeTurn.id); if (known !== undefined) { - beforeTurn = known.ordinal; + beforeTurn = Math.min(beforeTurn, known.ordinal); const attemptId = known.runAttemptId; if (attemptId !== null) { beforeRun = Math.min( @@ -946,6 +967,9 @@ const make = Effect.gen(function* () { (message) => message.role === "user", ); if (indexOfUserMessage < 0) continue; + // A held run can execute after a later submission, leaving no ordered slot for a gap. + const after = preceding.get(nativeTurn.id)!; + if (beforeRun <= after.run || beforeTurn <= after.turn) return 0; additions.push({ nativeTurn, indexOfUserMessage, beforeRun, beforeTurn }); } additions.reverse(); @@ -989,12 +1013,7 @@ const make = Effect.gen(function* () { }); } if (movedRuns.size > 0) { - const runIds = target.runs.filter((run) => movedRuns.has(run.ordinal)).map((run) => run.id); - const { checkpoints, turnItems } = yield* orchestrator.getThreadRecords( - threadId, - ["checkpoints", "turnItems"], - { turnItemRunIds: runIds }, - ); + const { checkpoints } = yield* orchestrator.getThreadRecords(threadId, ["checkpoints"]); for (const providerThread of target.providerThreads) { const first = providerThread.firstRunOrdinal; const last = providerThread.lastRunOrdinal; @@ -1021,18 +1040,6 @@ const make = Effect.gen(function* () { payload: { ...checkpoint, appRunOrdinal }, }); } - const itemsByRun = Map.groupBy(turnItems, (item) => item.runId); - for (const runId of runIds.toReversed()) { - for (const item of itemsByRun.get(runId) ?? []) { - events.push({ - id: yield* idAllocator.allocate.event({ threadId }), - type: "turn-item.updated", - threadId, - occurredAt, - payload: item, - }); - } - } } for (const [ index, @@ -1052,7 +1059,11 @@ const make = Effect.gen(function* () { ); } if (events.length === 0) return 0; - const stored = yield* eventSink.write({ unlessNativeThreadOwned: target.owner, events }); + const stored = yield* eventSink.write({ + unlessNativeThreadOwned: target.owner, + repositionRunItems: movedRuns.size > 0, + events, + }); return stored.length === 0 ? 0 : additions.length; }, (effect, { threadId }) => diff --git a/apps/server/src/provider/CodexThreadRevert.test.ts b/apps/server/src/provider/CodexThreadRevert.test.ts index f268719154722..a2d01b41c948a 100644 --- a/apps/server/src/provider/CodexThreadRevert.test.ts +++ b/apps/server/src/provider/CodexThreadRevert.test.ts @@ -11,6 +11,7 @@ const page = ( limit: number, turns: string[], nextCursor: string | null, + itemsView = "summary", ) => [ { type: "expect_outbound" as const, @@ -22,7 +23,7 @@ const page = ( cursor, limit, sortDirection: "desc", - itemsView: "summary", + itemsView, }, }, }, @@ -88,3 +89,23 @@ it.effect("rejects repeated cursors instead of looping or reverting incomplete h ), ), ); + +it.effect("refuses to revert when the native checkpoint is missing", () => + Effect.gen(function* () { + const client = yield* CodexClient.CodexAppServerClient; + const result = yield* revertCodexThread(client, "thread", { + afterTurnId: "checkpoint", + }).pipe(Effect.flip); + assert.include(result.message, "Checkpoint turn checkpoint is missing"); + }).pipe( + Effect.provide( + CodexReplay.layerReplay({ + provider: "codex", + protocol: "codex.app-server", + version: "test", + scenario: "revert-missing-checkpoint", + entries: [...page(1, null, 32, ["newest"], null, "notLoaded")], + }), + ), + ), +); diff --git a/apps/server/src/provider/CodexThreadRevert.ts b/apps/server/src/provider/CodexThreadRevert.ts index f2933dfe3d753..9bb2ef7374ee1 100644 --- a/apps/server/src/provider/CodexThreadRevert.ts +++ b/apps/server/src/provider/CodexThreadRevert.ts @@ -6,13 +6,15 @@ import * as Effect from "effect/Effect"; export const revertCodexThread = Effect.fn("revertCodexThread")(function* ( client: Pick, threadId: string, - numTurns: number, + boundary: number | { readonly afterTurnId: string }, ) { - let remaining = numTurns; + let remaining = typeof boundary === "number" ? boundary : undefined; + const afterTurnId = typeof boundary === "number" ? undefined : boundary.afterTurnId; let beforeTurnId: string | undefined; let cursor: string | null = null; const visited = new Set(); - while (remaining > 0) { + let found = afterTurnId === undefined; + scan: while (remaining === undefined || remaining > 0) { if (visited.has(cursor)) { return yield* CodexErrors.CodexAppServerRequestError.internalError( "Thread history pagination repeated a cursor.", @@ -24,17 +26,28 @@ export const revertCodexThread = Effect.fn("revertCodexThread")(function* ( const page: CodexSchema.V2ThreadTurnsListResponse = yield* client.request("thread/turns/list", { threadId, cursor, - limit: Math.min(remaining, 100), + limit: remaining === undefined ? 32 : Math.min(remaining, 100), sortDirection: "desc", - itemsView: "summary", + itemsView: afterTurnId === undefined ? "summary" : "notLoaded", }); for (const turn of page.data) { + if (turn.id === afterTurnId) { + found = true; + break scan; + } beforeTurnId = turn.id; - if (--remaining === 0) break; + if (remaining !== undefined && --remaining === 0) break scan; } cursor = page.nextCursor ?? null; if (cursor === null) break; } + if (!found) { + return yield* CodexErrors.CodexAppServerRequestError.internalError( + `Checkpoint turn ${afterTurnId} is missing from the native Codex history.`, + undefined, + { method: "thread/turns/list", operation: "decode-payload" }, + ); + } return beforeTurnId === undefined ? yield* client.request("thread/read", { threadId, includeTurns: false }) : yield* client.request("thread/revert", { threadId, beforeTurnId }); From d9af5b3705f011ac2fad547d479f798af3f7625d Mon Sep 17 00:00:00 2001 From: qi-hey <63509385+qi-hey@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:00:19 +0800 Subject: [PATCH 5/6] test(codex): replay rollback by native checkpoint --- .../record-codex-app-server-replay-fixture.ts | 29 +++++++++++++++---- .../thread_rollback/codex_transcript.ndjson | 4 +-- .../codex_transcript.ndjson | 4 +-- .../codex_transcript.ndjson | 4 +-- 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/apps/server/scripts/record-codex-app-server-replay-fixture.ts b/apps/server/scripts/record-codex-app-server-replay-fixture.ts index 202e72de32a43..656c5294e3115 100644 --- a/apps/server/scripts/record-codex-app-server-replay-fixture.ts +++ b/apps/server/scripts/record-codex-app-server-replay-fixture.ts @@ -143,7 +143,7 @@ type ReplayStep = | { readonly type: "rollback"; readonly label: string; - readonly numTurns: number; + readonly afterTurnLabel: string; } | { readonly type: "fork"; @@ -799,7 +799,7 @@ function scenarios(): ReadonlyArray { { type: "rollback", label: "rollback-latest-turn", - numTurns: 1, + afterTurnLabel: "first-before-rollback", }, { type: "turn", @@ -834,7 +834,7 @@ function scenarios(): ReadonlyArray { { type: "rollback", label: "rollback-latest-turn", - numTurns: 1, + afterTurnLabel: "first-before-rollback", }, { type: "turn", @@ -879,7 +879,7 @@ function scenarios(): ReadonlyArray { { type: "rollback", label: "rollback-to-stopped-turn", - numTurns: 1, + afterTurnLabel: "stopped-mid-tool", }, { type: "turn", @@ -1222,9 +1222,25 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe approvalGate ? Deferred.await(approvalGate) : Effect.void; const model = scenarioModel(scenario); const threadRuntimeParams = { cwd: process.cwd(), model, config: CODEX_THREAD_CONFIG }; + const turnIdsByLabel = new Map(); const lastTurnIdByThread = new Map(); const runningCommandProcessIds = new Map>(); + const rollbackToRecordedTurn = Effect.fn( + "record-codex-app-server-replay-fixture.rollbackToRecordedTurn", + )(function* ( + client: CodexClient.CodexAppServerClient["Service"], + threadId: string, + afterTurnLabel: string, + ) { + const afterTurnId = turnIdsByLabel.get(afterTurnLabel); + if (afterTurnId === undefined) { + throw new Error(`Unknown replay checkpoint turn '${afterTurnLabel}'.`); + } + yield* revertCodexThread(client, threadId, { afterTurnId }); + lastTurnIdByThread.set(threadId, afterTurnId); + }); + const initializeClient = Effect.gen(function* () { const client = yield* CodexClient.CodexAppServerClient; @@ -1311,6 +1327,7 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe const completed = yield* getCompletion(turnId); yield* Deferred.await(completed); + turnIdsByLabel.set(step.label, turnId); lastTurnIdByThread.set(threadId, turnId); }); @@ -1402,7 +1419,7 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe // Fresh app-servers report notLoaded; resume before thread/revert and again on the next turn. yield* client.request("thread/read", { threadId, includeTurns: false }); yield* client.request("thread/resume", resumeParams); - yield* revertCodexThread(client, threadId, rollback.numTurns); + yield* rollbackToRecordedTurn(client, threadId, rollback.afterTurnLabel); yield* client.request("thread/resume", resumeParams); yield* runTurnStep(client, threadId, after); }).pipe(Effect.provide(layerCodex({ recorder }))); @@ -1421,7 +1438,7 @@ const runReplaySession = Effect.fn("record-codex-app-server-replay-fixture.runRe for (const [stepIndex, step] of run.steps.entries()) { if (step.type === "rollback") { yield* client.request("thread/read", { threadId: activeThreadId, includeTurns: false }); - yield* revertCodexThread(client, activeThreadId, step.numTurns); + yield* rollbackToRecordedTurn(client, activeThreadId, step.afterTurnLabel); continue; } if (step.type === "fork") { diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson index 85cf1ead68bb6..b67499c7aeeb4 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_transcript.ndjson @@ -51,8 +51,8 @@ {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","turn":{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}},"emittedAtMs":1790295651335}} {"type":"expect_outbound","label":"thread/read","frame":{"id":7,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} {"type":"emit_inbound","label":"thread/read","frame":{"id":7,"result":{"thread":{"id":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295644,"updatedAt":1790295651,"recencyAt":1790295649,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-20-44-01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":8,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":8,"result":{"data":[{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[{"type":"userMessage","id":"01a0d5ef-ad0e-78d0-af5c-7145f750bd81","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_044082e5a0068297016ab5be62fefc87d0bbf3fdbed6561ac8","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931}],"nextCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":8,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"notLoaded","limit":32,"sortDirection":"desc","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":8,"result":{"data":[{"id":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1790295649,"completedAt":1790295651,"durationMs":1931},{"id":"01a0d5ef-9b58-7980-9e7a-2463dd068a8e","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1790295645,"completedAt":1790295649,"durationMs":4326}],"nextCursor":null,"backwardsCursor":"{\"requestedThreadId\":\"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} {"type":"expect_outbound","label":"thread/revert","frame":{"id":9,"method":"thread/revert","params":{"beforeTurnId":"01a0d5ef-ac4e-7471-a4a8-6776e39e6d29","threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","status":{"type":"notLoaded"}},"emittedAtMs":1790295651358}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295651544}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson index be3555213299a..32f31e9c3f9b0 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_after_restart/codex_transcript.ndjson @@ -60,10 +60,10 @@ {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790404935482}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"idle"}},"emittedAtMs":1790404935500}} {"type":"emit_inbound","label":"thread/resume","frame":{"id":3,"result":{"thread":{"id":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790404926,"updatedAt":1790404935,"recencyAt":1790404931,"status":{"type":"idle"},"path":"/home/replay-user/tmp/bughunt-codex/codex-home/sessions/2026/09/25/rollout-2026-09-25T23-42-06-01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"70629cdddbe2c29749e8dce588b1828580b2777b","branch":"fix/codex-rollback-resume","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","initialTurnsPage":null,"turnsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}","itemsBackwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":22,\"includeAnchor\":true,\"scope\":{\"kind\":\"itemsByCreatedAtOrdinal\"}}"}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":4,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":4,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"notLoaded","limit":32,"sortDirection":"desc","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} {"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turnId":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","tokenUsage":{"total":{"totalTokens":44003,"inputTokens":43985,"cachedInputTokens":19200,"cacheWriteInputTokens":0,"outputTokens":18,"reasoningOutputTokens":0},"last":{"totalTokens":24198,"inputTokens":24189,"cachedInputTokens":19200,"cacheWriteInputTokens":0,"outputTokens":9,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790404935520}} {"type":"emit_inbound","label":"thread/goal/cleared","frame":{"method":"thread/goal/cleared","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"},"emittedAtMs":1790404935521}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":4,"result":{"data":[{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[{"type":"userMessage","id":"01a0dc73-2e86-7131-a632-7a2b7e8186fb","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0f3ce1c685f16088016ab769447c6087d08bd0018d724b5401","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790404931,"completedAt":1790404934,"durationMs":3756}],"nextCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":4,"result":{"data":[{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1790404931,"completedAt":1790404934,"durationMs":3756},{"id":"01a0dc73-1c60-70a3-9a3c-d54c0020efa2","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1790404926,"completedAt":1790404930,"durationMs":4426}],"nextCursor":null,"backwardsCursor":"{\"requestedThreadId\":\"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a\",\"rolloutOrdinal\":16,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} {"type":"expect_outbound","label":"thread/revert","frame":{"id":5,"method":"thread/revert","params":{"beforeTurnId":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","name":"codex_apps","status":"cancelled","error":null,"failureReason":null},"emittedAtMs":1790404935542}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"notLoaded"}},"emittedAtMs":1790404935544}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson index b382b070c180e..e7818a39e3480 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback_to_stopped_turn/codex_transcript.ndjson @@ -88,8 +88,8 @@ {"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","turn":{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}},"emittedAtMs":1790459906344}} {"type":"expect_outbound","label":"thread/read","frame":{"id":11,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} {"type":"emit_inbound","label":"thread/read","frame":{"id":11,"result":{"thread":{"id":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code","runtimeWorkspaceRoots":["/home/replay-user/t3code"]}],"extra":null,"sessionId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","forkedFromId":null,"parentThreadId":null,"preview":"Respond with exactly: rollback fixture first turn complete","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790459892,"updatedAt":1790459906,"recencyAt":1790459903,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/26/rollout-2026-09-26T14-58-12-01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88.jsonl","cwd":"/home/replay-user/t3code","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"147b1509eac4291b323371299d0925a44035680c","branch":"master","originUrl":null},"name":null,"daybreakEnabled":null,"turns":[]}}}} -{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":12,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"summary","limit":1,"sortDirection":"desc","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} -{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":12,"result":{"data":[{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[{"type":"userMessage","id":"01a0dfba-0390-7aa0-a945-e25ca01302e2","clientId":null,"content":[{"type":"text","text":"Respond with exactly: rollback fixture second turn complete","text_elements":[]}]},{"type":"agentMessage","id":"msg_0508263b0487774d016ab840020e1087d08e559660413ebcd6","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423}],"nextCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":false,\"scope\":{\"kind\":\"turns\"}}","backwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} +{"type":"expect_outbound","label":"thread/turns/list","frame":{"id":12,"method":"thread/turns/list","params":{"cursor":null,"itemsView":"notLoaded","limit":32,"sortDirection":"desc","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} +{"type":"emit_inbound","label":"thread/turns/list","frame":{"id":12,"result":{"data":[{"id":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1790459903,"completedAt":1790459906,"durationMs":2423},{"id":"01a0dfb9-e509-7001-ba72-fe324f527fb9","items":[],"itemsView":"notLoaded","status":"interrupted","error":null,"startedAt":1790459897,"completedAt":1790459903,"durationMs":6789},{"id":"01a0dfb9-d479-70c0-9d88-912b52f7f613","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1790459892,"completedAt":1790459897,"durationMs":4216}],"nextCursor":null,"backwardsCursor":"{\"requestedThreadId\":\"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88\",\"rolloutOrdinal\":32,\"includeAnchor\":true,\"scope\":{\"kind\":\"turns\"}}"}}} {"type":"expect_outbound","label":"thread/revert","frame":{"id":13,"method":"thread/revert","params":{"beforeTurnId":"01a0dfb9-ff9f-7902-a370-d05cc4ec5959","threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} {"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","status":{"type":"notLoaded"}},"emittedAtMs":1790459906373}} {"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790459906471}} From e6afcc1ee3818e00e9dfaadc2aad1ee236cad3b4 Mon Sep 17 00:00:00 2001 From: qi-hey <63509385+qi-hey@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:27:17 +0800 Subject: [PATCH 6/6] fix(codex): preserve history and checkpoints across refreshes Refresh legacy history against the current native head, filter cached messages on return, and allow a legacy no-op rollback only when its checkpoint is still current. Preserve the order and contents of items updated while a run moves. Link the next capture and diff to the stored predecessor checkpoint. Implemented with OpenAI GPT-6.2 in Codex through T3 Code. --- .../checkpointing/CheckpointDiffQuery.test.ts | 53 +++- .../src/checkpointing/CheckpointDiffQuery.ts | 7 +- .../Adapters/CodexAdapterV2.test.ts | 280 +++++++++++------- .../Adapters/CodexAdapterV2.ts | 48 +-- .../CheckpointCaptureService.test.ts | 66 ++++- .../CheckpointCaptureService.ts | 17 +- .../src/orchestration-v2/CheckpointService.ts | 16 +- apps/server/src/orchestration-v2/EventSink.ts | 49 ++- .../src/orchestration-v2/ProjectionStore.ts | 39 ++- .../src/project/AgentSessionImporter.test.ts | 31 ++ 10 files changed, 439 insertions(+), 167 deletions(-) diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index 7c516e97fa730..8c2f9ca85c0a2 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts @@ -1,7 +1,13 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it, vi } from "@effect/vitest"; -import { CheckpointRef, CheckpointScopeId, RunId, ThreadId } from "@t3tools/contracts"; +import { + CheckpointId, + CheckpointRef, + CheckpointScopeId, + RunId, + ThreadId, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -36,6 +42,8 @@ function makeProjection(): ProjectionCheckpointContext { ], checkpoints: [ { + id: CheckpointId.make("checkpoint:second"), + parentCheckpointId: null, scopeId: secondScopeId, runId: secondRunId, ordinalWithinScope: 1, @@ -112,6 +120,8 @@ function makeProjectionAfterStoppedRun(stoppedRunCheckpoint: boolean) { ordinalWithinScope: number, runId: RunId | null, ): ProjectionCheckpointContext["checkpoints"][number] => ({ + id: CheckpointId.make(`checkpoint:root:${ordinalWithinScope}`), + parentCheckpointId: null, scopeId: firstScopeId, runId, ordinalWithinScope, @@ -132,6 +142,7 @@ function makeProjectionAfterStoppedRun(stoppedRunCheckpoint: boolean) { checkpoints: [ { ...checkpoint(2, null), + id: CheckpointId.make("checkpoint:tool:2"), scopeId: secondScopeId, ref: CheckpointRef.make("refs/t3/test/tool/2"), }, @@ -190,6 +201,44 @@ it.effect.each([false, true])( }, ); +it.effect( + "uses the captured parent when refreshed history separates app and scope ordinals", + () => { + const projection = makeProjectionAfterStoppedRun(true); + const parent = { ...projection.checkpoints[3]!, appRunOrdinal: 3 }; + const unusedBaseline = { ...projection.checkpoints[4]!, runId: null, appRunOrdinal: null }; + const target = { + ...projection.checkpoints[4]!, + id: CheckpointId.make("checkpoint:root:4"), + parentCheckpointId: parent.id, + ordinalWithinScope: 4, + appRunOrdinal: 4, + ref: CheckpointRef.make("refs/t3/test/ordinal/4"), + }; + const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) => + Effect.succeed("diff --git a/file b/file"), + ); + const layer = layerFor({ + projection: Effect.succeed({ + ...projection, + runs: projection.runs.map((run) => + run.ordinal === 1 ? run : { ...run, ordinal: run.ordinal + 1 }, + ), + checkpoints: [...projection.checkpoints.slice(0, 3), parent, unusedBaseline, target], + }), + diffCheckpoints, + }); + return Effect.gen(function* () { + const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; + yield* query.getTurnDiff({ threadId, fromTurnCount: 3, toTurnCount: 4 }); + assert.deepEqual( + diffCheckpoints.mock.calls.map(([input]) => input.fromCheckpointRef), + [parent.ref], + ); + }).pipe(Effect.provide(layer)); + }, +); + const layerVcsProcess = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer)); const layerStore = CheckpointStore.layer.pipe( Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess))), @@ -260,6 +309,8 @@ it.effect("shares the turn and full-thread diff budget across real Git batches", checkpointScopes: [{ id: scopeId, runId, kind: "root_run", cwd }], checkpoints: [ { + id: CheckpointId.make("checkpoint:patch-budget:1"), + parentCheckpointId: null, scopeId, runId, ordinalWithinScope: 1, diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index bf9543919de65..e508e10ff0a83 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -163,15 +163,16 @@ export const make = Effect.gen(function* () { }); } - // Capture compares against the preceding scope ordinal, even when that - // checkpoint belongs to a stopped run or has no run. + // Imported turns can move app ordinals while existing checkpoint refs stay in place. const parentCheckpoint = input.fromTurnCount === input.toTurnCount - 1 ? projection.checkpoints.find( (checkpoint) => checkpoint.status === "ready" && checkpoint.scopeId === toCheckpoint.scopeId && - checkpoint.ordinalWithinScope === toCheckpoint.ordinalWithinScope - 1, + (toCheckpoint.parentCheckpointId === null + ? checkpoint.ordinalWithinScope === toCheckpoint.ordinalWithinScope - 1 + : checkpoint.id === toCheckpoint.parentCheckpointId), ) : undefined; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 02a59d1c85cda..d8ebec047ac36 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -5252,6 +5252,12 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, ]; + const legacyTop = turn("legacy", "full", [ + user("legacy:user", "legacy"), + user("steer", "Steer the turn"), + answer("legacy"), + ]); + const local = turn("local-3", "full", [user("local-3")]); const { runtime, providerThread } = yield* makeCodexReplayHarness( makeCodexReplayTranscript({ scenario: "codex-external-history", @@ -5280,26 +5286,27 @@ describe("CodexAdapterV2 post-settle continuation", () => { ...listItems(12, "newest", null, [user("newest:user", "newest")], "stuck"), ...listItems(13, "newest", "stuck", [answer("newest")], "stuck"), ...readMode(14, "legacy"), + ...listPage(15, null, [legacyTop], "older-1", "full", "legacy-head"), + ...listPage(16, "older-1", [local], "older-2", "full"), + ...listPage(17, "older-2", [turn("local-2", "full")], "older-3", "full"), + ...listPage(18, "older-3", [turn("local-1", "full")], "older-4", "full"), + ...readMode(19, "legacy"), + ...listPage(20, "legacy-head", [turn("legacy")], null, "notLoaded", undefined, true), ...listPage( - 15, + 21, + "older-4", + [turn("missed-legacy", "full", [user("missed-legacy")]), turn(nativeTurnId, "full")], null, - [ - turn("legacy", "full", [ - user("legacy:user", "legacy"), - user("steer", "Steer the turn"), - answer("legacy"), - ]), - ], - "older-1", "full", - "legacy-head", ), - ...listPage(16, "older-1", [turn("local-3", "full")], "older-2", "full"), - ...listPage(17, "older-2", [turn("local-2", "full")], "older-3", "full"), - ...listPage(18, "older-3", [turn("local-1", "full")], "older-4", "full"), - ...readMode(19, "legacy"), + ...readMode(22, "legacy"), + ...listPage(23, null, [legacyTop], "older-1", "full", "legacy-head"), + ...listPage(24, "older-1", [local], "older-2", "full"), + ...listPage(25, "older-2", [turn("local-2", "full")], "older-3", "full"), + ...listPage(26, "older-3", [turn("local-1", "full")], "older-4", "full"), + ...readMode(27, "legacy"), ...listPage( - 20, + 28, "legacy-head", [turn("legacy")], "new-append", @@ -5308,9 +5315,13 @@ describe("CodexAdapterV2 post-settle continuation", () => { true, ), ...listPage( - 21, - "older-4", - [turn("missed-legacy", "full", [user("missed-legacy")]), turn(nativeTurnId, "full")], + 29, + null, + [ + turn("new-append", "full", [user("new-append")]), + legacyTop, + turn(nativeTurnId, "full"), + ], null, "full", ), @@ -5337,18 +5348,36 @@ describe("CodexAdapterV2 post-settle continuation", () => { assert.deepEqual(yield* readHistory({ providerThread, nativeTurnId }), []); const error = yield* Effect.flip(readHistory({ providerThread, nativeTurnId })); assert.equal(error._tag, "ProviderAdapterReadThreadSnapshotError"); - assert.deepEqual(yield* readHistory({ providerThread, nativeTurnId }), []); - const legacy = yield* readHistory({ providerThread, nativeTurnId }); + assert.deepEqual( + yield* readHistory({ + providerThread, + nativeTurnId, + knownNativeTurnIds: new Set(["legacy"]), + }), + [], + ); + const legacy = yield* readHistory({ + providerThread, + nativeTurnId, + knownNativeTurnIds: new Set(["local-3"]), + }); assert.deepEqual( legacy.map((turn) => turn.id), ["missed-legacy", "local-1", "local-2", "local-3", "legacy"], ); assert.deepEqual(legacy[0]?.messages, [{ role: "user", text: "missed-legacy" }]); + assert.deepEqual(legacy.find((turn) => turn.id === "local-3")?.messages, []); assert.deepEqual(legacy.at(-1)?.messages, [ { role: "user", text: "legacy" }, { role: "user", text: "Steer the turn" }, { role: "assistant", text: "Reply to legacy" }, ]); + assert.deepEqual(yield* readHistory({ providerThread, nativeTurnId }), []); + const afterAppend = yield* readHistory({ providerThread, nativeTurnId }); + assert.deepEqual( + afterAppend.map((turn) => turn.id), + ["legacy", "new-append"], + ); }).pipe( Effect.provide( Layer.mergeAll( @@ -10729,97 +10758,138 @@ describe("CodexAdapterV2 post-settle continuation", () => { completedAt: input.now, }); - it.effect("fails honestly when rolling back a legacy Codex thread", () => - Effect.gen(function* () { - const nativeThreadId = "legacy-rollback-thread"; - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId: "legacy-rollback-turn", - prompt: "unused", - }); - const transcript = makeCodexReplayTranscript({ - scenario: "codex-legacy-rollback", - entries: [ - ...preamble.slice(0, 5), - { - type: "expect_outbound", - label: "thread/read", - frame: { - id: 3, - method: "thread/read", - params: { threadId: nativeThreadId, includeTurns: false }, + it.effect.each(["known suffix", "native suffix", "native head"] as const)( + "checks whether a legacy Codex rollback would change history (%s)", + (scenario) => + Effect.gen(function* () { + const nativeThreadId = "legacy-rollback-thread"; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "legacy-rollback-turn", + prompt: "unused", + }); + const transcript = makeCodexReplayTranscript({ + scenario: "codex-legacy-rollback", + entries: [ + ...preamble.slice(0, 5), + { + type: "expect_outbound", + label: "thread/read", + frame: { + id: 3, + method: "thread/read", + params: { threadId: nativeThreadId, includeTurns: false }, + }, }, - }, - { - type: "emit_inbound", - label: "thread/read", - frame: { - id: 3, - result: { thread: { id: nativeThreadId, historyMode: "legacy" } }, + { + type: "emit_inbound", + label: "thread/read", + frame: { + id: 3, + result: { thread: { id: nativeThreadId, historyMode: "legacy" } }, + }, }, - }, - ], - }); - const outbound: Array = []; - const harness = yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method) => - Effect.sync(() => { - outbound.push(method); - }), - ); - const now = yield* DateTime.now; - const firstTurn = codexReplaySourceTurn({ - id: "provider-turn-first", - ordinal: 1, - nativeId: "native-turn-first", - providerThreadId: harness.providerThread.id, - now, - }); - const secondTurn = codexReplaySourceTurn({ - id: "provider-turn-second", - ordinal: 2, - nativeId: "native-turn-second", - providerThreadId: harness.providerThread.id, - now, - }); + ...(scenario === "known suffix" + ? [] + : ([ + { + type: "expect_outbound", + label: "thread/turns/list", + frame: { + id: 4, + method: "thread/turns/list", + params: { + threadId: nativeThreadId, + cursor: null, + limit: 1, + sortDirection: "desc", + itemsView: "notLoaded", + }, + }, + }, + { + type: "emit_inbound", + label: "thread/turns/list", + frame: { + id: 4, + result: { + data: [ + { + id: scenario === "native head" ? "native-turn-first" : "external-turn", + items: [], + status: "completed", + error: null, + }, + ], + nextCursor: null, + }, + }, + }, + ] satisfies Array)), + ], + }); + const outbound: Array = []; + const harness = yield* makeCodexReplayHarness( + transcript, + () => Effect.void, + (method) => + Effect.sync(() => { + outbound.push(method); + }), + ); + const now = yield* DateTime.now; + const firstTurn = codexReplaySourceTurn({ + id: "provider-turn-first", + ordinal: 1, + nativeId: "native-turn-first", + providerThreadId: harness.providerThread.id, + now, + }); + const secondTurn = codexReplaySourceTurn({ + id: "provider-turn-second", + ordinal: 2, + nativeId: "native-turn-second", + providerThreadId: harness.providerThread.id, + now, + }); - const error = yield* Effect.flip( - harness.runtime.rollbackThread({ - providerThread: harness.providerThread, - target: { - type: "provider_turn", - checkpointId: CheckpointId.make("checkpoint-legacy-rollback"), - appRunOrdinal: 1, - providerTurn: firstTurn, - }, - providerThreadTurns: [firstTurn, secondTurn], - }), - ); + const result = yield* Effect.result( + harness.runtime.rollbackThread({ + providerThread: harness.providerThread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint-legacy-rollback"), + appRunOrdinal: 1, + providerTurn: firstTurn, + }, + providerThreadTurns: + scenario === "known suffix" ? [firstTurn, secondTurn] : [firstTurn], + }), + ); - assert.instanceOf(error, ProviderAdapter.ProviderAdapterRollbackThreadError); - assert.include( - errorCauseChainText(error), - "legacy", - "legacy rollback must surface an honest unsupported-history failure", - ); - assert.notInclude( - outbound, - "thread/rollback", - "thread/rollback must not be sent to a legacy Codex thread", - ); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + if (result._tag === "Success") { + assert.equal(scenario, "native head"); + assert.deepEqual( + result.success.providerThread.nativeConversationHeadRef, + firstTurn.nativeTurnRef, + ); + } else { + assert.notEqual(scenario, "native head"); + assert.include(errorCauseChainText(result.failure), "legacy"); + } + if (scenario !== "known suffix") assert.include(outbound, "thread/turns/list"); + assert.notInclude(outbound, "thread/revert"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), - ), ); it.effect("unarchives a Codex thread and reverts all native turns after the checkpoint", () => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 12b6addae0d48..86c835b37b8d3 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -8939,7 +8939,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); if ( head?.data[0]?.id !== pending.head.id || - head.data[0].status !== pending.head.status + head.data[0].status !== pending.head.status || + (pending.headCursor !== null && head.nextCursor != null) ) { pending = undefined; } @@ -8983,7 +8984,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( completedAt: turn.completedAt == null ? startedAt : codexTimestamp(turn.completedAt), messages: - !paginated && turn.status === "completed" && !knownNativeTurnIds?.has(turn.id) + !paginated && turn.status === "completed" ? turn.items.flatMap((item) => { const message = codexHistoryMessage(item); return message === undefined ? [] : [message]; @@ -8996,11 +8997,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const history: Array = []; for (const turn of turns.reverse()) { if (turn.status === "inProgress") break; - if ( - !paginated || - turn.status !== "completed" || - knownNativeTurnIds?.has(turn.id) - ) { + if (knownNativeTurnIds?.has(turn.id)) { + history.push({ ...turn, messages: [] }); + continue; + } + if (!paginated || turn.status !== "completed") { history.push(turn); continue; } @@ -9127,22 +9128,35 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef?.strength === "strong" ? (nativeConversationHeadRef.nativeId ?? undefined) : undefined; + const unchanged = () => ({ + providerThread: { + ...threadInput.providerThread, + nativeConversationHeadRef, + status: "idle" as const, + }, + providerTurns: [], + messages: [], + runtimeRequests: [], + }); if (numTurns === 0 && afterTurnId === undefined) { - return { - providerThread: { - ...threadInput.providerThread, - nativeConversationHeadRef, - status: "idle" as const, - }, - providerTurns: [], - messages: [], - runtimeRequests: [], - }; + return unchanged(); } const { historyMode, loaded } = yield* ensureInitialized.pipe( Effect.andThen(readCodexThreadHistoryMetadata(client.raw, threadId)), ); if (historyMode !== "paginated") { + if (numTurns === 0 && afterTurnId !== undefined) { + const { data } = yield* client.request("thread/turns/list", { + threadId, + cursor: null, + limit: 1, + sortDirection: "desc", + itemsView: "notLoaded", + }); + if (data[0]?.id === afterTurnId && data[0].status !== "inProgress") { + return unchanged(); + } + } return yield* new ProviderAdapter.ProviderAdapterRollbackThreadError({ driver: CODEX_PROVIDER, providerThreadId: threadInput.providerThread.id, diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index 828d438646cdf..5e4eb96979f02 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -52,13 +52,15 @@ const modelSelection = { } as const; it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { - it.effect.each([false, true])( - "captures without decoding history or losing newer delegated completion, ref lookup fails=%s", - (refLookupFails) => + it.effect.each(["first run", "ref lookup fails", "shifted predecessor"] as const)( + "captures without decoding history or losing newer delegated completion (%s)", + (scenario) => Effect.gen(function* () { const projectionStore = yield* ProjectionStore.ProjectionStoreV2; const now = yield* DateTime.now; const later = DateTime.add(now, { seconds: 1 }); + const refLookupFails = scenario === "ref lookup fails"; + const shifted = scenario === "shifted predecessor"; const staleDelegatedCompletion = { disposition: "open" as const, @@ -77,7 +79,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { const staleRun: OrchestrationV2Run = { id: runId, threadId, - ordinal: 1, + ordinal: shifted ? 4 : 1, providerInstanceId, modelSelection, providerThreadId, @@ -167,6 +169,15 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { files: [], capturedAt: now, }; + const previousCheckpoint = { + ...readyBaseline, + id: CheckpointId.make("checkpoint:previous-run"), + ref: CheckpointRef.make("checkpoint-ref:previous-run"), + runId: RunId.make("run:previous-after-history-refresh"), + parentCheckpointId: readyBaseline.id, + appRunOrdinal: 3, + ordinalWithinScope: 2, + }; yield* projectionStore.apply({ id: EventId.make("event:checkpoint-capture:thread"), @@ -250,6 +261,15 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { occurredAt: now, payload: readyBaseline, }); + if (shifted) { + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture:previous-run"), + type: "checkpoint.captured", + threadId, + occurredAt: now, + payload: previousCheckpoint, + }); + } const sql = yield* SqlClient.SqlClient; yield* sql`INSERT OR REPLACE INTO orchestration_v2_projection_turn_items (turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id, @@ -265,11 +285,12 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { ); const committed = yield* Ref.make>([]); + const captureBases: Array = []; const layerCapture = CheckpointCaptureService.layer.pipe( Layer.provide( Layer.mergeAll( IdAllocator.layer, - refLookupFails + refLookupFails || shifted ? CheckpointService.layer.pipe( Layer.provide( Layer.mergeAll( @@ -278,16 +299,22 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, + captureCheckpoint: ({ previousCheckpointRef }) => + Effect.sync(() => { + captureBases.push(previousCheckpointRef); + }), + diffCheckpoints: () => Effect.succeed(""), hasCheckpointRef: () => - Effect.fail( - new VcsProcessTimeoutError({ - operation: "test.hasCheckpointRef", - command: "git", - cwd: "/repo", - timeoutMs: 30000, - }), - ), + refLookupFails + ? Effect.fail( + new VcsProcessTimeoutError({ + operation: "test.hasCheckpointRef", + command: "git", + cwd: "/repo", + timeoutMs: 30000, + }), + ) + : Effect.succeed(true), }), ), ), @@ -330,15 +357,22 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { return; } assert.equal(runUpdated.payload.status, "completed"); - const capturedEvent = events.find((event) => event.type === "checkpoint.captured"); + const capturedEvent = events + .filter((event) => event.type === "checkpoint.captured") + .find((event) => event.payload.runId === runId); assert.equal( runUpdated.payload.checkpointId, - refLookupFails ? capturedEvent?.payload.id : captured.id, + refLookupFails || shifted ? capturedEvent?.payload.id : captured.id, ); if (refLookupFails && capturedEvent?.type === "checkpoint.captured") { assert.equal(capturedEvent.payload.status, "ready"); assert.deepEqual(capturedEvent.payload.files, []); } + if (shifted) { + assert.equal(capturedEvent?.payload.parentCheckpointId, previousCheckpoint.id); + assert.equal(capturedEvent?.payload.ordinalWithinScope, 4); + assert.deepEqual(captureBases, [previousCheckpoint.ref]); + } assert.isUndefined( runUpdated.payload.delegatedCompletion, "checkpoint capture must omit delegatedCompletion so ProjectionStore can keep a newer cohort", diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 43cdae25d4bcd..ff7bf1bebd678 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -65,8 +65,15 @@ export const layer: Layer.Layer< readonly runId: RunId; readonly scopeId: CheckpointScopeId; }) { - const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } = - yield* projections.getCheckpointCaptureContext(input.threadId, input); + const { + run, + rootNode, + scope, + providerThread, + previousRunCheckpoint, + preservedCheckpointOrdinals, + sideChat, + } = yield* projections.getCheckpointCaptureContext(input.threadId, input); // Stopped runs remain terminal; their checkpoint is the next message's rollback point. const stopped = run?.status === "interrupted" || run?.status === "cancelled"; @@ -100,7 +107,8 @@ export const layer: Layer.Layer< } const capturedAt = yield* DateTime.now; - const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1); + const baselineOrdinalWithinScope = + previousRunCheckpoint?.ordinalWithinScope ?? Math.max(0, run.ordinal - 1); const isPreserved = (ordinalWithinScope: number) => preservedCheckpointOrdinals.includes(ordinalWithinScope); // The baselines this capture materializes are attributed to the run materializing them. The @@ -123,6 +131,9 @@ export const layer: Layer.Layer< runId: run.id, nodeId: rootNode.id, ordinalWithinScope: run.ordinal, + ...(previousRunCheckpoint === undefined + ? {} + : { previousCheckpoint: previousRunCheckpoint }), appRunOrdinal: run.ordinal, capturedAt, forceMissing: sideChat, diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index fb6490834c7f6..5697cc0f3110d 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -134,6 +134,7 @@ export interface CheckpointServiceV2Shape { readonly runId: RunId | null; readonly nodeId: NodeId; readonly ordinalWithinScope: number; + readonly previousCheckpoint?: Pick; readonly appRunOrdinal: number | null; readonly capturedAt: DateTime.Utc; readonly forceMissing?: boolean; @@ -400,19 +401,22 @@ export const layer: Layer.Layer< }); const parentCheckpointId = input.ordinalWithinScope > 0 - ? yield* checkpointIdForScopeOrdinal(idAllocator, { + ? (input.previousCheckpoint?.id ?? + (yield* checkpointIdForScopeOrdinal(idAllocator, { scopeId: input.scope.id, ordinalWithinScope: input.ordinalWithinScope - 1, - }) + }))) : null; const checkpointRef = yield* checkpointRefFor({ scopeId: input.scope.id, ordinalWithinScope: input.ordinalWithinScope, }); - const previousCheckpointRef = yield* checkpointRefFor({ - scopeId: input.scope.id, - ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1), - }); + const previousCheckpointRef = + input.previousCheckpoint?.ref ?? + (yield* checkpointRefFor({ + scopeId: input.scope.id, + ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1), + })); const repository = input.forceMissing === true ? "missing" : yield* probeRepository(input.scope); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index a6d75775a1ea9..90d0766bc0df2 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -497,19 +497,42 @@ const layerBase: Layer.Layer< turnItemRunIds: runIds, }); const itemsByRun = Map.groupBy(turnItems, (item) => item.runId); - return events.flatMap((event): ReadonlyArray => - event.type === "run.updated" && event.threadId === threadId - ? [ - event, - ...(itemsByRun.get(event.payload.id) ?? []).map((item) => ({ - type: "turn-item.updated" as const, - id: EventId.make(`${event.id}:position:${item.id}`), - threadId, - occurredAt: event.occurredAt, - payload: item, - })), - ] - : [event], + const updatesByItem = Map.groupBy( + events.flatMap((event) => + event.type === "turn-item.updated" && event.threadId === threadId ? [event] : [], + ), + (event) => event.payload.id, + ); + const relocated = new Set(); + const repositions = new Map>(); + for (const event of events) { + if (event.type !== "run.updated" || event.threadId !== threadId) continue; + const items = itemsByRun.get(event.payload.id); + if (items === undefined) continue; + itemsByRun.delete(event.payload.id); + // The position allocator follows event order, so updated items must keep their place. + const ordered: Array = []; + for (const item of items) { + const updates = updatesByItem.get(item.id); + if (updates === undefined) { + ordered.push({ + type: "turn-item.updated", + id: EventId.make(`${event.id}:position:${item.id}`), + threadId, + occurredAt: event.occurredAt, + payload: item, + }); + } else if (updates.every((update) => update.payload.runId === item.runId)) { + for (const update of updates) { + relocated.add(update.id); + ordered.push(update); + } + } + } + repositions.set(event.id, ordered); + } + return events.flatMap((event) => + relocated.has(event.id) ? [] : [event, ...(repositions.get(event.id) ?? [])], ); }); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a8d06679c801a..c65e2cf4d404d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -262,7 +262,18 @@ const ProjectionCheckpointContext = Schema.Struct({ ), checkpoints: Schema.Array( OrchestrationV2CheckpointJsonSchema.mapFields( - ({ scopeId, runId, ordinalWithinScope, appRunOrdinal, status, ref }) => ({ + ({ + id, + parentCheckpointId, + scopeId, + runId, + ordinalWithinScope, + appRunOrdinal, + status, + ref, + }) => ({ + id, + parentCheckpointId, scopeId, runId, ordinalWithinScope, @@ -281,6 +292,9 @@ export interface ProjectionCheckpointCaptureContext { readonly rootNode: OrchestrationV2ExecutionNode | undefined; readonly scope: OrchestrationV2CheckpointScope | undefined; readonly providerThread: OrchestrationV2ProviderThread | undefined; + readonly previousRunCheckpoint: + | Pick + | undefined; /** * Ordinals a runless baseline must not overwrite: ready snapshots, and missing checkpoints pinning * a run. Without file snapshots that run link is what rewind uses. Stale rows are rebaselined. @@ -6281,7 +6295,8 @@ export const layer: Layer.Layer = ORDER BY ordinal_within_parent ASC, scope_id ASC `, sql` - SELECT scope_id AS "scopeId", run_id AS "runId", + SELECT checkpoint_id AS id, scope_id AS "scopeId", run_id AS "runId", + json_extract(payload_json, '$.parentCheckpointId') AS "parentCheckpointId", ordinal_within_scope AS "ordinalWithinScope", app_run_ordinal AS "appRunOrdinal", status, json_extract(payload_json, '$.ref') AS ref @@ -6331,11 +6346,25 @@ export const layer: Layer.Layer = AND (thread_id = ${threadId} OR owner_node_id IN (${nodesOwningProviderThreads(threadId)}) OR provider_thread_id IN (SELECT provider_thread_id FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId}))`, - sql<{ readonly ordinal: number }>`SELECT ordinal_within_scope AS ordinal + sql<{ + readonly id: OrchestrationV2Checkpoint["id"]; + readonly ref: OrchestrationV2Checkpoint["ref"]; + readonly ordinal: number; + readonly run_id: RunId | null; + readonly app_run_ordinal: number | null; + }>`SELECT checkpoint_id AS id, json_extract(payload_json, '$.ref') AS ref, + ordinal_within_scope AS ordinal, run_id, app_run_ordinal FROM orchestration_v2_projection_checkpoints WHERE thread_id = ${threadId} AND scope_id = ${target.scopeId} AND (status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`, ]); + const previous = + run === undefined + ? undefined + : preservedRows.find( + (checkpoint) => + checkpoint.run_id !== null && checkpoint.app_run_ordinal === run.ordinal - 1, + ); return { run, rootNode: @@ -6351,6 +6380,10 @@ export const layer: Layer.Layer = ? undefined : yield* decodeProviderThreadPayload(providerRows[0].payload_json), preservedCheckpointOrdinals: preservedRows.map(({ ordinal }) => ordinal), + previousRunCheckpoint: + previous === undefined + ? undefined + : { id: previous.id, ref: previous.ref, ordinalWithinScope: previous.ordinal }, sideChat: threadRows[0].side_chat === 1, }; }), diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 7b2b994981c0f..5e6ea42bb4aec 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -1035,6 +1035,37 @@ it.effect("refreshes completed Codex turns in order, including gaps after a fail expect((yield* projections.getThreadRecords(threadId, ["turnItems"])).turnItems).toEqual( after.turnItems, ); + + yield* sink.write({ + repositionRunItems: true, + events: [ + { + id: EventId.make(`${continuedId}:background-rechecked`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + ...backgroundCommand, + status: "completed", + completedAt: now, + output: "Build succeeded after retry", + }, + }, + { + id: EventId.make(`${continuedId}:moved-again`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...continuedRun, ordinal: 7 }, + }, + ], + }); + const { turnItems } = yield* projections.getThreadRecords(threadId, ["turnItems"]); + expect(turnItems.find((item) => item.id === backgroundCommand.id)).toMatchObject({ + ordinal: 7_000_002, + status: "completed", + output: "Build succeeded after retry", + }); }).pipe(Effect.scoped, Effect.provide(persistence)), );