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/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index b276fafb2723a..665e7ef9d1a26 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -192,6 +192,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/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts index d3dec1efe59ff..bb5d6961faf1e 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, @@ -360,6 +411,8 @@ it.effect("adds a patch for each tracked repository that changed in the range", repositoryPath: cwd, }, checkpoints: ordinals.map((ordinalWithinScope) => ({ + id: CheckpointId.make(`checkpoint:${name}:${ordinalWithinScope}`), + parentCheckpointId: null, scopeId: id, runId: ordinalWithinScope === 2 ? secondRunId : null, ordinalWithinScope, @@ -380,6 +433,11 @@ it.effect("adds a patch for each tracked repository that changed in the range", const layer = layerFor({ projection: Effect.succeed({ ...projection, + runs: [ + projection.runs[0]!, + { id: RunId.make("imported-turn"), ordinal: 2, status: "completed" }, + { ...projection.runs[1]!, ordinal: 3 }, + ], checkpointScopes: [ ...projection.checkpointScopes.map((scope) => ({ ...scope, cwd: "/work/app" })), sibling.scope, @@ -387,7 +445,14 @@ it.effect("adds a patch for each tracked repository that changed in the range", later.scope, ], checkpoints: [ - ...projection.checkpoints, + { + ...projection.checkpoints[0]!, + id: CheckpointId.make("checkpoint:first"), + runId: firstRunId, + appRunOrdinal: 1, + ref: CheckpointRef.make("refs/t3/test/first"), + }, + { ...projection.checkpoints[0]!, ordinalWithinScope: 2, appRunOrdinal: 3 }, ...sibling.checkpoints, ...nested.checkpoints, ...later.checkpoints, @@ -397,7 +462,7 @@ it.effect("adds a patch for each tracked repository that changed in the range", }); return Effect.gen(function* () { const query = yield* CheckpointDiffQuery.CheckpointDiffQuery; - const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 }); + const result = yield* query.getTurnDiff({ threadId, fromTurnCount: 2, toTurnCount: 3 }); assert.deepEqual(result.repositories, [ { name: "shared", @@ -412,6 +477,8 @@ it.effect("adds a patch for each tracked repository that changed in the range", diffCheckpoints.mock.calls.find(([input]) => input.cwd === "/work/app")?.[0].excludePaths, ["packages/ui"], ); + const aggregate = yield* query.getFullThreadDiff({ threadId, toTurnCount: 3 }); + assert.deepEqual(aggregate.repositories, result.repositories); }).pipe(Effect.provide(layer)); }); diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.ts index d5344ecaa2fbb..85384da664ec8 100644 --- a/apps/server/src/checkpointing/CheckpointDiffQuery.ts +++ b/apps/server/src/checkpointing/CheckpointDiffQuery.ts @@ -100,14 +100,14 @@ type ContextCheckpoint = ProjectionCheckpointContext["checkpoints"][number]; */ function repositoryDiffRange( checkpoints: ReadonlyArray, - range: { readonly fromTurnCount: number; readonly toTurnCount: number }, + range: { readonly fromOrdinal: number; readonly toOrdinal: number }, ): { readonly from: ContextCheckpoint; readonly to: ContextCheckpoint } | undefined { const ready = checkpoints .filter( (checkpoint) => checkpoint.status === "ready" && - checkpoint.ordinalWithinScope >= range.fromTurnCount && - checkpoint.ordinalWithinScope <= range.toTurnCount, + checkpoint.ordinalWithinScope >= range.fromOrdinal && + checkpoint.ordinalWithinScope <= range.toOrdinal, ) .toSorted((left, right) => left.ordinalWithinScope - right.ordinalWithinScope); const from = ready[0]; @@ -115,6 +115,28 @@ function repositoryDiffRange( return from === undefined || to === undefined || from === to ? undefined : { from, to }; } +// Imported turns have no snapshots; a repository range starts at the first captured turn's baseline. +function repositoryRangeStart( + checkpoints: ReadonlyArray, + range: { readonly fromTurnCount: number; readonly toTurnCount: number }, + toOrdinal: number, +): number { + if (range.fromTurnCount === 0) return 0; + let firstOrdinal = toOrdinal; + for (const checkpoint of checkpoints) { + if ( + checkpoint.status !== "stale" && + checkpoint.appRunOrdinal !== null && + checkpoint.appRunOrdinal > range.fromTurnCount && + checkpoint.appRunOrdinal <= range.toTurnCount && + checkpoint.ordinalWithinScope < firstOrdinal + ) { + firstOrdinal = checkpoint.ordinalWithinScope; + } + } + return firstOrdinal - 1; +} + /** @public */ export const make = Effect.gen(function* () { const threads = yield* ThreadManagement.ThreadManagementService; @@ -193,8 +215,8 @@ export const make = Effect.gen(function* () { const repositoryDiffs = Effect.fn("CheckpointDiffQuery.repositoryDiffs")(function* (input: { readonly projection: ProjectionCheckpointContext; readonly threadCwd: string; - readonly fromTurnCount: number; - readonly toTurnCount: number; + readonly fromOrdinal: number; + readonly toOrdinal: number; readonly ignoreWhitespace: boolean; readonly nested: ReadonlyMap>; readonly maxBytes: number; @@ -346,7 +368,7 @@ export const make = Effect.gen(function* () { projection.checkpoints.some( (checkpoint) => checkpoint.scopeId === scope.id && - checkpoint.ordinalWithinScope <= input.toTurnCount, + checkpoint.ordinalWithinScope <= toCheckpoint.ordinalWithinScope, ), ), ]).pipe( @@ -361,8 +383,12 @@ export const make = Effect.gen(function* () { : yield* repositoryDiffs({ projection, threadCwd: toScope.cwd, - fromTurnCount: input.fromTurnCount, - toTurnCount: input.toTurnCount, + fromOrdinal: repositoryRangeStart( + projection.checkpoints, + input, + toCheckpoint.ordinalWithinScope, + ), + toOrdinal: toCheckpoint.ordinalWithinScope, ignoreWhitespace, nested, maxBytes: Math.max(0, CHECKPOINT_DIFF_MAX_OUTPUT_BYTES - Buffer.byteLength(diff)), @@ -378,15 +404,16 @@ export const make = Effect.gen(function* () { }); if (toCheckpoint.status === "missing") return yield* withRepositories(""); - // 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 the captured parent and its ref 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/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a4a918fe1ddee..f62d735035531 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -207,6 +207,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 330524c99ad3b..787aefffa9c7c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -5556,6 +5556,251 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + 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 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", + 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", + backwardsCursor?: string, + headCheck = false, + ): Array => [ + { + type: "expect_outbound", + label: "thread/turns/list", + frame: { + id, + method: "thread/turns/list", + params: { + threadId: nativeThreadId, + cursor, + limit: headCheck ? 1 : itemsView === "full" ? 8 : 32, + itemsView, + sortDirection: headCheck ? "asc" : "desc", + }, + }, + }, + { + type: "emit_inbound", + label: "thread/turns/list", + frame: { + id, + result: { + data, + nextCursor, + ...(backwardsCursor === undefined ? {} : { backwardsCursor }), + }, + }, + }, + ]; + 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 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", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Start" }).slice(0, 5), + ...readMode(3, "paginated"), + ...listPage(4, null, [turn("newest")], "before-newest"), + ...listPage( + 5, + "before-newest", + [turn("older"), turn(nativeTurnId), turn("past")], + 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, [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( + 21, + "older-4", + [turn("missed-legacy", "full", [user("missed-legacy")]), turn(nativeTurnId, "full")], + null, + "full", + ), + ...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( + 28, + "legacy-head", + [turn("legacy")], + "new-append", + "notLoaded", + undefined, + true, + ), + ...listPage( + 29, + null, + [ + turn("new-append", "full", [user("new-append")]), + legacyTop, + turn(nativeTurnId, "full"), + ], + null, + "full", + ), + ], + }), + ); + const readHistory = runtime.readHistoryAfter!; + 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"); + 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( + 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"; @@ -10942,100 +11187,141 @@ 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 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 = { @@ -11088,13 +11374,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, }, }, @@ -11102,7 +11392,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 1c38aaebffc80..db9f6d9800185 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1205,6 +1205,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, @@ -2048,6 +2072,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, @@ -9048,6 +9073,176 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), ), mcpApps, + readHistoryAfter: Effect.fn("CodexAdapterV2.readHistoryAfter")( + function* ({ providerThread, nativeTurnId, knownNativeTurnIds }) { + const threadId = yield* getNativeThreadId(providerThread); + yield* ensureInitialized; + const { historyMode } = yield* readCodexThreadHistoryMetadata(client.raw, threadId); + const paginated = historyMode === "paginated"; + 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.headCursor !== null && head.nextCursor != null) + ) { + 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" + ? turn.items.flatMap((item) => { + const message = codexHistoryMessage(item); + return message === undefined ? [] : [message]; + }) + : [], + }); + } + if (anchor >= 0) { + legacyHistoryReads.delete(threadId); + const history: Array = []; + for (const turn of turns.reverse()) { + if (turn.status === "inProgress") break; + if (knownNativeTurnIds?.has(turn.id)) { + history.push({ ...turn, messages: [] }); + continue; + } + if (!paginated || turn.status !== "completed") { + 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}.`, + ); + } + 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); + } + itemCursor = items.nextCursor ?? null; + } while (itemCursor !== null); + history.push({ ...turn, messages }); + } + return history; + } + 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 }) => + effect.pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({ + driver: CODEX_PROVIDER, + providerThreadId: providerThread.id, + cause, + }), + ), + ), + ), mcpSignIn: { start: Effect.fn("CodexAdapterV2.mcpSignIn.start")( function* ({ providerThread, server }) { @@ -9205,22 +9400,39 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( threadInput.target.type === "provider_turn" ? threadInput.target.providerTurn.nativeTurnRef : null; - if (numTurns === 0) { - return { - providerThread: { - ...threadInput.providerThread, - nativeConversationHeadRef, - status: "idle" as const, - }, - providerTurns: [], - messages: [], - runtimeRequests: [], - }; + const afterTurnId = + 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 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, @@ -9240,7 +9452,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/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index cc570a9ef113d..badfb70e8fffc 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -71,13 +71,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, @@ -96,7 +98,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { const staleRun: OrchestrationV2Run = { id: runId, threadId, - ordinal: 1, + ordinal: shifted ? 4 : 1, providerInstanceId, modelSelection, providerThreadId, @@ -186,6 +188,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"), @@ -269,6 +280,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, @@ -284,11 +304,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( @@ -298,16 +319,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), }), ), ), @@ -352,15 +379,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 dd7f27079a4e5..9ce54a59ccc39 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -74,8 +74,15 @@ export const layer: Layer.Layer< readonly scopeId: CheckpointScopeId; }) { const context = yield* projections.getCheckpointCaptureContext(input.threadId, input); - const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } = - context; + const { + run, + rootNode, + scope, + providerThread, + previousRunCheckpoint, + preservedCheckpointOrdinals, + sideChat, + } = context; // Stopped runs remain terminal; their checkpoint is the next message's rollback point. const stopped = run?.status === "interrupted" || run?.status === "cancelled"; @@ -109,7 +116,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 @@ -150,6 +158,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/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts index 95dca7c2b1a15..d39ff6927b4c8 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts @@ -89,7 +89,14 @@ it.effect.each([ targetAttempt: undefined, rolledBackAttemptIds: [], staleCheckpoints: [], - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: null }, + discardedSnapshotOrdinals: [1], + checkpoint: { + id: checkpointId, + scopeId, + status: "ready", + appRunOrdinal: null, + ordinalWithinScope: 0, + }, scope: { id: scopeId, cwd }, runsToRollback: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }], } as unknown as ProjectionCheckpointRollbackContext; diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index fd5d9c34b5bcd..e0cee18c0222b 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -222,9 +222,16 @@ it.effect.each([ }, providerThread, providerSession: undefined, - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }, + checkpoint: { + id: checkpointId, + scopeId, + status: "ready", + appRunOrdinal: 0, + ordinalWithinScope: 0, + }, scope: { id: scopeId, cwd: worktreePath }, runsToRollback: [], + discardedSnapshotOrdinals: [], targetAttempt: undefined, rolledBackAttemptIds: [], staleCheckpoints: [], @@ -446,9 +453,10 @@ it.effect.each([ providerInstanceId, }, providerSession: undefined, - checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0 }, + checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0, ordinalWithinScope: 0 }, scope: { id: scopeId, cwd: worktreePath }, runsToRollback: [], + discardedSnapshotOrdinals: [], targetAttempt: undefined, rolledBackAttemptIds: [], staleCheckpoints: [], @@ -541,7 +549,7 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -const seedRollbackHistory = Effect.gen(function* () { +const seedRollbackHistory = Effect.fn("seedRollbackHistory")(function* (insertedTurns = 0) { const store = yield* ProjectionStore.ProjectionStoreV2; const now = yield* DateTime.now; const threadId = ThreadId.make("rollback-history"); @@ -559,6 +567,7 @@ const seedRollbackHistory = Effect.gen(function* () { const turnId = (ordinal: number) => ProviderTurnId.make(`rollback-history-turn-${ordinal}`); const checkpointId = (ordinal: number) => CheckpointId.make(`rollback-history-checkpoint-${ordinal}`); + const appOrdinal = (ordinal: number) => (ordinal < 2 ? ordinal : ordinal + insertedTurns); type EventInput = Event extends OrchestrationV2DomainEvent ? Omit : never; @@ -607,7 +616,7 @@ const seedRollbackHistory = Effect.gen(function* () { nativeConversationHeadRef: null, status: "idle" as const, firstRunOrdinal: 1, - lastRunOrdinal: 6, + lastRunOrdinal: appOrdinal(6), handoffIds: [], forkedFrom: null, createdAt: now, @@ -648,7 +657,7 @@ const seedRollbackHistory = Effect.gen(function* () { payload: { id: runId(ordinal), threadId, - ordinal, + ordinal: appOrdinal(ordinal), providerInstanceId, modelSelection, providerThreadId, @@ -744,7 +753,7 @@ const seedRollbackHistory = Effect.gen(function* () { nodeId: nodeId(Math.max(1, Math.min(ordinal, 7))), parentCheckpointId: null, ordinalWithinScope: ordinal, - appRunOrdinal: ordinal === 0 ? null : ordinal, + appRunOrdinal: ordinal === 0 ? null : appOrdinal(ordinal), ref: CheckpointRef.make(`refs/t3/rollback-history/${ordinal}`), status: ordinal === 7 ? "stale" : "ready", files: [], @@ -882,7 +891,7 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe (it) => { it.effect("rolls back later terminal runs despite obsolete unrelated SQLite payloads", () => Effect.gen(function* () { - const history = yield* seedRollbackHistory; + const history = yield* seedRollbackHistory(2); const sql = yield* SqlClient.SqlClient; const { threadId, runId, nodeId, checkpointId } = history; yield* sql` @@ -954,7 +963,7 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe it.effect("rewinds the conversation to a run whose snapshot capture failed", () => Effect.gen(function* () { - const history = yield* seedRollbackHistory; + const history = yield* seedRollbackHistory(); const sql = yield* SqlClient.SqlClient; yield* sql`UPDATE orchestration_v2_projection_checkpoints SET status = 'error', payload_json = json_set(payload_json, '$.status', 'error') @@ -971,7 +980,7 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe "rewinds stopped runs repeatedly without counting discarded provider turns again", () => Effect.gen(function* () { - const history = yield* seedRollbackHistory; + const history = yield* seedRollbackHistory(); yield* history.rollback(5); yield* history.rollback(2); yield* history.rollback(0); @@ -1003,7 +1012,7 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe it.effect("skips a pending rollback once the thread is deleted", () => Effect.gen(function* () { - const history = yield* seedRollbackHistory; + const history = yield* seedRollbackHistory(); const thread = yield* history.store.getThread(history.threadId); yield* history.store.apply({ id: EventId.make("rollback-history-deleted"), diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index e85175ef2ee33..bd1620dc62473 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -363,7 +363,7 @@ export const layer: Layer.Layer< const repositoryTargets = repositories.flatMap((repository) => { const target = repositoryRewindCheckpoint( recorded.filter((candidate) => candidate.scopeId === repository.id), - targetOrdinal, + checkpoint.ordinalWithinScope, ); return target === null ? [] : [{ scope: repository, checkpoint: target }]; }); @@ -374,7 +374,7 @@ export const layer: Layer.Layer< recorded.some( (candidate) => candidate.scopeId === repository.id && - candidate.ordinalWithinScope > targetOrdinal && + candidate.ordinalWithinScope > checkpoint.ordinalWithinScope && (candidate.status === "ready" || candidate.runId !== null), ), ); @@ -438,7 +438,7 @@ export const layer: Layer.Layer< yield* checkpoints.discardRepositorySnapshots({ rootScope: scope, thread: context.thread, - ordinals: runsToRollback.map((run) => run.ordinal), + ordinals: context.discardedSnapshotOrdinals, }); // Lock against full-row thread writes that could restore the old native session after rollback. diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index ec3e872d61c2b..be4d5da29cb1c 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -216,6 +216,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; @@ -626,19 +627,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/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index b495293bc2228..ce82bb1f9b5f4 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -228,6 +228,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, @@ -479,6 +483,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/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 3f6744e576edd..f1cf11a0aff07 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, @@ -116,6 +117,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>; @@ -130,6 +133,7 @@ export interface EventSinkV2Shape { "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef" >; readonly guardPendingUserInputCancellations?: boolean; + readonly repositionRunItems?: boolean; readonly commandId?: CommandId; readonly events: ReadonlyArray; readonly effects: ReadonlyArray; @@ -485,6 +489,57 @@ 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); + 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) ?? [])], + ); + }); + const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* ( input: Parameters[0], ) { @@ -518,10 +573,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/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ae06077992d0a..4adce7e125ab6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14667,7 +14667,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio typeof scope.repositoryPath === "string" && repositoryRewindCheckpoint( projection.checkpoints.filter((candidate) => candidate.scopeId === scope.id), - targetCheckpoint.appRunOrdinal ?? 0, + targetCheckpoint.ordinalWithinScope, ) !== null, ); // Missing or failed snapshots otherwise support conversation rewind only. diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2278284d7fde7..5801926cafdcb 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -266,7 +266,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, @@ -285,6 +296,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. @@ -318,6 +332,7 @@ export interface ProjectionCheckpointRollbackContext { readonly providerTurns: ReadonlyArray; readonly rolledBackAttemptIds: ReadonlyArray; readonly runsToRollback: ReadonlyArray; + readonly discardedSnapshotOrdinals: ReadonlyArray; readonly rootNodes: ReadonlyArray; /** Ready checkpoints of the target scope and of repository scopes that the rollback discards. */ readonly staleCheckpoints: ReadonlyArray; @@ -6356,7 +6371,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 @@ -6420,7 +6436,14 @@ 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 ${preservedCheckpoint}`, @@ -6434,6 +6457,13 @@ export const layer: Layer.Layer = WHERE thread_id = ${threadId} AND kind = 'manual') AND ${preservedCheckpoint}`, ]); + const previous = + run === undefined + ? undefined + : preservedRows.find( + (checkpoint) => + checkpoint.run_id !== null && checkpoint.app_run_ordinal === run.ordinal - 1, + ); return { run, rootNode: @@ -6449,6 +6479,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, thread: { projectId: threadRows[0].project_id, @@ -6505,6 +6539,7 @@ export const layer: Layer.Layer = providerTurns: [], rolledBackAttemptIds: [], runsToRollback: [], + discardedSnapshotOrdinals: [], rootNodes: [], staleCheckpoints: [], }; @@ -6529,10 +6564,15 @@ export const layer: Layer.Layer = ON attempt.attempt_id = json_extract(run.payload_json, '$.activeAttemptId') WHERE run.thread_id = ${threadId} AND run.ordinal = ${targetOrdinal} AND run.status != 'rolled_back' AND attempt.thread_id = ${threadId}`, - sql`SELECT payload_json FROM orchestration_v2_projection_runs - WHERE thread_id = ${threadId} AND ordinal > ${targetOrdinal} - AND status IN ('completed', 'interrupted', 'failed', 'cancelled') - ORDER BY ordinal ASC`, + sql` + SELECT run.payload_json, coalesce(snapshot.ordinal_within_scope, run.ordinal) AS snapshot_ordinal + FROM orchestration_v2_projection_runs AS run + LEFT JOIN orchestration_v2_projection_checkpoints AS snapshot + ON snapshot.thread_id = run.thread_id AND snapshot.run_id = run.run_id + AND snapshot.checkpoint_id = json_extract(run.payload_json, '$.checkpointId') + WHERE run.thread_id = ${threadId} AND run.ordinal > ${targetOrdinal} + AND run.status IN ('completed', 'interrupted', 'failed', 'cancelled') + ORDER BY run.ordinal ASC`, sql`SELECT session.payload_json FROM orchestration_v2_projection_provider_sessions AS session JOIN orchestration_v2_projection_provider_session_bindings AS binding @@ -6547,14 +6587,20 @@ export const layer: Layer.Layer = sql`SELECT payload_json FROM orchestration_v2_projection_checkpoints WHERE thread_id = ${threadId} AND status = 'ready' AND ((scope_id = ${scope.id} AND app_run_ordinal > ${targetOrdinal}) - -- Repository checkpoints carry no app run ordinal; theirs is the run's ordinal. - OR (ordinal_within_scope > ${targetOrdinal} AND scope_id IN ( + OR (ordinal_within_scope > ${checkpoint.ordinalWithinScope} AND scope_id IN ( SELECT scope_id FROM orchestration_v2_projection_checkpoint_scopes WHERE thread_id = ${threadId} AND kind = 'manual'))) ORDER BY scope_id = ${scope.id} DESC, scope_id ASC, ordinal_within_scope ASC`, ]); const targetAttempt = (yield* decodeRollbackTargetAttempts(attemptRows))[0]; const runsToRollback = yield* decodeRows(decodeRunPayload, threadId)(runRows); + // A later capture can leave a baseline ref even when that repository never changed. + const discardedSnapshotOrdinals = new Set(); + for (const { snapshot_ordinal } of runRows) { + for (const ordinal of [snapshot_ordinal - 1, snapshot_ordinal]) { + if (ordinal > checkpoint.ordinalWithinScope) discardedSnapshotOrdinals.add(ordinal); + } + } const [nodeRows, turnRows] = yield* Effect.all([ sql`SELECT payload_json FROM orchestration_v2_projection_nodes WHERE thread_id = ${threadId} AND ${sql.in( @@ -6573,6 +6619,7 @@ export const layer: Layer.Layer = ...context, targetAttempt, runsToRollback, + discardedSnapshotOrdinals: [...discardedSnapshotOrdinals], providerSession: sessionRows[0] === undefined ? undefined diff --git a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts index accfca8ddc7e0..e555ad973c3c4 100644 --- a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts +++ b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + CheckpointId, CheckpointRef, CheckpointScopeId, ProjectId, @@ -46,6 +47,8 @@ const finalizationLayer = ( const usedRepositoryScopeId = CheckpointScopeId.make(`${scopeId}_api`); const idleRepositoryScopeId = CheckpointScopeId.make(`${scopeId}_docs`); const repositoryCheckpoint = (repositoryScopeId: CheckpointScopeId, checkpointRunId: RunId) => ({ + id: CheckpointId.make(`checkpoint:${repositoryScopeId}:${checkpointRunId}`), + parentCheckpointId: null, scopeId: repositoryScopeId, runId: checkpointRunId, ordinalWithinScope: 1, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index c4eed74b274cf..63e0577de3d31 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -277,6 +277,7 @@ const layerAgentSessionImporterProvided = AgentSessionImporter.layer.pipe( layerProjectService, layerOrchestratorProvided, layerEventSink, + EffectOutbox.layer, IdAllocator.layer, ProviderSessionRuntime.layer, ProviderAdapterRegistry.layerFromProviderInstanceRegistry, 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 3bb8185a7390b..23586c54da1e5 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 @@ -56,8 +56,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":9,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0d5ef-9a99-7bf2-a24c-197fc5cc32ff"}}} {"type":"emit_inbound","label":"thread/read","frame":{"id":9,"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":10,"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":10,"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":10,"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":10,"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":11,"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 086462cb51e05..e8e3b7bf39a9e 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 @@ -67,10 +67,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":4,"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":5,"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":5,"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":5,"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":5,"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":6,"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 9b5eece1211e0..c042bbafc8bf4 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 @@ -93,8 +93,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":13,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0dfb9-d3d6-7c72-a2a4-2f0ba5eedd88"}}} {"type":"emit_inbound","label":"thread/read","frame":{"id":13,"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":14,"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":14,"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":14,"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":14,"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":15,"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}} diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 18c0946144d4a..5e6ea42bb4aec 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -2,14 +2,22 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { type AgentSessionSource, + type OrchestrationV2Run, type ServerSettingsError, + CheckpointId, + CheckpointRef, + CheckpointScopeId, EventId, ProjectId, ProviderDriverKind, ProviderInstanceId, MessageId, + NodeId, + ProviderTurnId, + RunAttemptId, RunId, ThreadId, + TurnItemId, type ApplicationStoredEvent, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, @@ -32,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"; @@ -59,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, ); @@ -256,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 }), @@ -280,6 +290,7 @@ const makeImporter = Effect.fn(function* ( return { run: importer.importRecentAgentThreads({ projectId }), importNativeHistory: importer.importNativeHistory, + refreshCodexHistory: importer.refreshCodexHistory, published, }; }); @@ -543,7 +554,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 +573,499 @@ 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 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, 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.thread.messages[1] = { role: "assistant", text: "Fixed", createdAt: replyAt }; 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, + 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.turnItems.map((item) => ("text" in item ? item.text : null))).toEqual([ + "Fix it", + "Fixed", + "Continue", + "Continued", + ]); + expect(after.turnItems.map((item) => item.ordinal)).toEqual([1, 2, 3, 4]); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +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; + 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 = []; + let failRead = false; + const session = { + 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 Effect.succeed(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); + + 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, + }; + 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: [ + { + 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: [], + }, + }, + { + 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( + [], + 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({ - recordsChangedTranscript: recorded?.some((source) => source.size === 200) ?? false, - showsNewMessages: texts.includes("Continued"), - }).not.toEqual({ recordsChangedTranscript: true, showsNewMessages: false }); + 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.providerTurns.map((turn) => turn.nativeTurnRef?.nativeId)).toEqual([ + "local-turn", + "outside-1", + "outside-2", + "missed", + "continued", + ]); + expect(after.turnItems.flatMap((item) => ("text" in item ? [item.text] : []))).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.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, + ); + + 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)), ); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 0f8736986a2df..01912c17015a5 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,14 @@ 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 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"; +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 +95,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 +160,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,10 +177,13 @@ function messageEvents(input: { ? { ...common, createdBy: "user", - creationSource: "server", + 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: [], } @@ -184,7 +196,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,16 +206,151 @@ 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" }, + nativeHistoryReconciled: true, + 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, + }), + ), + ]; +} + +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; 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, @@ -303,6 +450,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,37 +470,85 @@ const make = Effect.gen(function* () { }, { onConflict: "ignore" }, ); - const existing = yield* Effect.option( - orchestrator.getThreadRecords(threadId, ["messages"]), - ); + 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)) { - if (existing.value.thread.projectId !== input.projectId) { + const { thread: current, messages, turnItems } = 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; + const stored = turnItems.filter( + (item) => item.type === "user_message" || item.type === "assistant_message", + ); if ( - stored.length !== thread.messages.length || + 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; } + 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, providerThreads } = yield* orchestrator.getThreadRecords(threadId, [ + "runs", + "providerThreads", + ]); + 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 +632,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 +676,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, @@ -596,7 +795,291 @@ 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, attempts } = + yield* orchestrator.getThreadRecords(threadId, [ + "providerThreads", + "runs", + "providerTurns", + "attempts", + ]); + 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 activeRunByAttempt = 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 knownTurns = new Map( + ownedTurns.flatMap((turn) => + turn.nativeTurnRef?.strength === "strong" && + turn.nativeTurnRef.nativeId !== null && + (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 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); + } + 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, + knownTurns, + activeRunByAttempt, + runsByAttempt, + }; + }, + ); + + const refreshCodexHistory = Effect.fn("AgentSessionImporter.refreshCodexHistory")( + 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; + 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, + knownNativeTurnIds: new Set(target.knownTurns.keys()), + }) ?? Effect.succeed([]), + ), + Effect.scoped, + codexReaders.withPermit, + 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; + 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 = Math.min(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; + // 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(); + 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 { checkpoints } = yield* orchestrator.getThreadRecords(threadId, ["checkpoints"]); + 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 }, + }); + } + } + for (const [ + index, + { nativeTurn, indexOfUserMessage, beforeRun, beforeTurn }, + ] of additions.entries()) { + events.push( + ...externalTurnEvents({ + thread: target.thread, + owner: target.owner, + nativeThreadId: target.nativeId, + nativeTurn, + indexOfUserMessage, + runOrdinal: beforeRun + index, + turnOrdinal: beforeTurn + index, + ids: idAllocator.derive, + }), + ); + } + if (events.length === 0) return 0; + const stored = yield* eventSink.write({ + unlessNativeThreadOwned: target.owner, + repositionRunItems: movedRuns.size > 0, + events, + }); + return stored.length === 0 ? 0 : additions.length; + }, + (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/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 }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ff783eeb57324..c6d9c6bd289ef 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3144,6 +3144,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 e3b4e9e5f7682..9b3a1fed50d57 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -4261,7 +4261,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 ed8e75c28c74c..166a218e94c03 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -109,8 +109,14 @@ 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. + +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 diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index a3b1861ca0351..24b0b439f22a6 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -156,6 +156,7 @@ describe("command permissions", () => { it.effect.each([ { method: WS_METHODS.serverRunStorageCleanup, scope: AuthSettingsWriteScope }, { method: WS_METHODS.serverReclaimDatabaseSpace, scope: AuthEnvironmentMaintainScope }, + { method: WS_METHODS.agentSessionsRefreshCodexHistory, scope: AuthOrchestrationOperateScope }, { method: WS_METHODS.workspaceAddTaskFolderRepository, scope: AuthSourceControlWriteScope }, { method: WS_METHODS.providerMcpSignInStart, scope: AuthProvidersManageScope }, { method: WS_METHODS.providerMcpSignInComplete, scope: AuthProvidersManageScope }, @@ -163,7 +164,14 @@ describe("command permissions", () => { 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/client-runtime/src/state/threadRepositories.test.ts b/packages/client-runtime/src/state/threadRepositories.test.ts index 04625dac4071b..833733cdb8ae1 100644 --- a/packages/client-runtime/src/state/threadRepositories.test.ts +++ b/packages/client-runtime/src/state/threadRepositories.test.ts @@ -343,14 +343,14 @@ describe("threadRepositorySections", () => { describe("rewindFileRestore", () => { const projection = { checkpointScopes: scopes, checkpoints }; - const missingRoot = (appRunOrdinal: number | null) => - ({ status: "missing", appRunOrdinal }) as const; + const missingRoot = (appRunOrdinal: number | null, ordinalWithinScope = appRunOrdinal ?? 0) => + ({ status: "missing", appRunOrdinal, ordinalWithinScope }) as const; const linkedProjectFolder = { projectIsWorktree: false }; it.each([ { why: "a ready snapshot restores every file", - checkpoint: { status: "ready", appRunOrdinal: 1 } as const, + checkpoint: { status: "ready", appRunOrdinal: 1, ordinalWithinScope: 1 } as const, taskFolder: null, restores: "files", }, @@ -360,6 +360,12 @@ describe("rewindFileRestore", () => { taskFolder: linkedProjectFolder, restores: "repositories", }, + { + why: "a turn moved by a history refresh keeps its repository snapshot", + checkpoint: missingRoot(3, 1), + taskFolder: linkedProjectFolder, + restores: "repositories", + }, { why: "the thread start restores a repository's baseline", checkpoint: missingRoot(null), @@ -386,7 +392,7 @@ describe("rewindFileRestore", () => { }, { why: "a stale snapshot restores nothing", - checkpoint: { status: "stale", appRunOrdinal: 1 } as const, + checkpoint: { status: "stale", appRunOrdinal: 1, ordinalWithinScope: 1 } as const, taskFolder: linkedProjectFolder, restores: null, }, diff --git a/packages/client-runtime/src/state/threadRepositories.ts b/packages/client-runtime/src/state/threadRepositories.ts index 574bfac5d1b69..4912302aea17f 100644 --- a/packages/client-runtime/src/state/threadRepositories.ts +++ b/packages/client-runtime/src/state/threadRepositories.ts @@ -101,20 +101,19 @@ export function repositoryCheckpointScopeIds( */ export function rewindFileRestore(input: { readonly projection: Pick; - readonly checkpoint: Pick | undefined; + readonly checkpoint: Pick | undefined; readonly taskFolder: Pick | null | undefined; }): "files" | "repositories" | null { const { checkpoint, projection } = input; if (checkpoint === undefined) return null; if (checkpoint.status === "ready") return "files"; if (checkpoint.status !== "missing" || input.taskFolder?.projectIsWorktree !== false) return null; - const targetOrdinal = checkpoint.appRunOrdinal ?? 0; return projection.checkpointScopes.some( (scope) => isRepositoryCheckpointScope(scope) && repositoryRewindCheckpoint( projection.checkpoints.filter((candidate) => candidate.scopeId === scope.id), - targetOrdinal, + checkpoint.ordinalWithinScope, ) !== null, ) ? "repositories" 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 b23b4650b20a9..53fa746a50e7f 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -54,6 +54,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/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index c9c8eea937e94..b14a137ba443e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1349,6 +1349,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/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index c7fe990a4be7e..2d54c03429477 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -117,6 +117,7 @@ import { AgentSessionImportProjectChangedError, AgentSessionImportProjectNotFoundError, AgentSessionImportResult, + AgentSessionRefreshCodexHistoryInput, AgentSessionScanInput, AgentSessionScanResult, AgentSessionScanError, @@ -505,6 +506,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", @@ -1744,6 +1746,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, @@ -2629,6 +2640,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 049198f9a6cb4..bd12d13d41a14 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -38,6 +38,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"; @@ -759,6 +760,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; @@ -860,6 +872,14 @@ 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; + /** Keep these turns in the result for ordering, but omit their messages. */ + readonly knownNativeTurnIds?: ReadonlySet; + }, + ) => Effect.Effect, ProviderAdapterV2Error>; readonly uploadFeedback?: (input: { readonly providerThread: OrchestrationV2ProviderThread; readonly reason?: string;