diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index b967a3ffcca27..6486c041bb377 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -198,6 +198,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 197343fdc36ca..62f72ce837802 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -212,6 +212,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 58214ab95b380..acd1f264b57d1 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -6506,6 +6506,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"; @@ -12637,100 +12882,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 = { @@ -12791,16 +13077,33 @@ describe("CodexAdapterV2 post-settle continuation", () => { result: { data: [ { id: "native-turn-second", items: [], status: "completed", error: null }, - { id: "native-turn-first", items: [], status: "completed", error: null }, + { id: "external-interrupted", items: [], status: "interrupted", error: null }, ], - nextCursor: null, + nextCursor: "older", }, }, ), ...exchange( 8, + "thread/turns/list", + { + threadId: nativeThreadId, + cursor: "older", + limit: 2, + sortDirection: "desc", + itemsView: "summary", + }, + { + result: { + data: [{ id: "native-turn-first", items: [], status: "completed", error: null }], + nextCursor: null, + }, + }, + ), + ...exchange( + 9, "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 28c4312b499a6..0cff5c4908cd3 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1266,6 +1266,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, @@ -2198,6 +2222,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(); // Codex restarts a thread's MCP servers on each resume, and an idle thread or app-server // is released after minutes, so a server that keeps failing would repeat its notice. const shownMcpStartupFailures = new Map>(); @@ -9551,6 +9576,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 }) { @@ -9708,16 +9903,21 @@ 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, - }, - messages: [], - runtimeRequests: [], - }; + const afterTurnId = + nativeConversationHeadRef?.strength === "strong" + ? (nativeConversationHeadRef.nativeId ?? undefined) + : undefined; + const unchanged = () => ({ + providerThread: { + ...threadInput.providerThread, + nativeConversationHeadRef, + status: "idle" as const, + }, + messages: [], + runtimeRequests: [], + }); + if (numTurns === 0 && afterTurnId === undefined) { + return unchanged(); } const keptNativeTurnId = nativeConversationHeadRef?.nativeId ?? null; const nativeTurnIds = rollbackTurns.flatMap( @@ -9734,6 +9934,18 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.andThen(readCodexThreadHistoryMetadata(client.raw, threadId)), ); if (historyMode !== "paginated") { + if (numTurns === 0 && afterTurnId !== undefined) { + const { data } = yield* client.request("thread/turns/list", { + threadId, + cursor: null, + limit: 1, + sortDirection: "desc", + itemsView: "notLoaded", + }); + if (data[0]?.id === afterTurnId && data[0].status !== "inProgress") { + return unchanged(); + } + } return yield* new ProviderAdapter.ProviderAdapterRollbackThreadError({ driver: CODEX_PROVIDER, providerThreadId: threadInput.providerThread.id, diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index 6f0c4aa47f9cb..ef820740734d7 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -82,12 +82,13 @@ const modelSelection = { it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { it.effect.each([ - { ordinal: 1, refLookupFails: false }, - { ordinal: 1, refLookupFails: true }, - { ordinal: 128, refLookupFails: false }, + { ordinal: 1, refLookupFails: false, shifted: false }, + { ordinal: 1, refLookupFails: true, shifted: false }, + { ordinal: 4, refLookupFails: false, shifted: true }, + { ordinal: 128, refLookupFails: false, shifted: false }, ])( "captures without decoding history or losing newer delegated completion, ordinal=$ordinal, ref lookup fails=$refLookupFails", - ({ ordinal, refLookupFails }) => + ({ ordinal, refLookupFails, shifted }) => Effect.gen(function* () { const projectionStore = yield* ProjectionStore.ProjectionStoreV2; const now = yield* DateTime.now; @@ -200,6 +201,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"), @@ -283,8 +293,30 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { occurredAt: now, payload: readyBaseline, }); + if (shifted) { + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture:previous-run-updated"), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + ...staleRun, + id: previousCheckpoint.runId, + ordinal: previousCheckpoint.appRunOrdinal, + userMessageId: MessageId.make("message:checkpoint-capture-previous"), + checkpointId: previousCheckpoint.id, + }, + }); + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture:previous-run"), + type: "checkpoint.captured", + threadId, + occurredAt: now, + payload: previousCheckpoint, + }); + } const sql = yield* SqlClient.SqlClient; - if (ordinal > 1) { + if (ordinal > 1 && !shifted) { yield* sql`WITH RECURSIVE history(ordinal) AS ( SELECT 1 UNION ALL SELECT ordinal + 1 FROM history WHERE ordinal < ${ordinal - 1} ) @@ -301,7 +333,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { ); assert.deepEqual( [...baselineContext.preservedCheckpointOrdinals].toSorted((a, b) => a - b), - ordinal === 1 ? [0] : [0, ordinal - 1], + shifted ? [0, 2] : ordinal === 1 ? [0] : [0, ordinal - 1], ); 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, @@ -317,11 +349,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( @@ -331,16 +364,23 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.succeed(null), + captureCheckpoint: ({ previousCheckpointRef }) => + Effect.sync(() => { + captureBases.push(previousCheckpointRef); + return null; + }), + 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), }), ), ), @@ -388,15 +428,22 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { assert.equal(runUpdated.payload.status, "completed"); assert.deepEqual(runUpdated.payload.completedAt, now); assert.isFalse(events.some((event) => event.type === "node.updated")); - 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", @@ -432,7 +479,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { yield* service.execute({ threadId, runId, scopeId }); assert.deepEqual(yield* Ref.get(committed), []); }).pipe(Effect.provide(layerCapture)); - }), + }).pipe(Effect.provide(Layer.fresh(layerProjectionStoreTest))), ); it.effect("does not capture a stopped run that a rollback already discarded", () => diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 6f3318b6be476..4a9dc5c899a7d 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -77,8 +77,15 @@ export const layer: Layer.Layer< const context = yield* projections.getCheckpointCaptureContext(input.threadId, input, { preservedCheckpoints: "baselines", }); - const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } = - context; + const { + run, + rootNode, + scope, + providerThread, + previousRunCheckpoint, + preservedCheckpointOrdinals, + sideChat, + } = context; // Runs settle before capture; `waiting` is a run persisted before captures ran after settling. const settled = run?.status === "completed" || 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 7ee99acf323fb..16cff76e80339 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -223,9 +223,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: [], @@ -447,9 +454,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: [], @@ -542,7 +550,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"); @@ -560,6 +568,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; @@ -608,7 +617,7 @@ const seedRollbackHistory = Effect.gen(function* () { nativeConversationHeadRef: null, status: "idle" as const, firstRunOrdinal: 1, - lastRunOrdinal: 6, + lastRunOrdinal: appOrdinal(6), handoffIds: [], forkedFrom: null, createdAt: now, @@ -649,7 +658,7 @@ const seedRollbackHistory = Effect.gen(function* () { payload: { id: runId(ordinal), threadId, - ordinal, + ordinal: appOrdinal(ordinal), providerInstanceId, modelSelection, providerThreadId, @@ -745,7 +754,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: [], @@ -886,7 +895,7 @@ const layerProjections = ProjectionStore.layer.pipe( it.layer(layerProjections)("rollback history reads", (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` @@ -958,7 +967,7 @@ it.layer(layerProjections)("rollback history reads", (it) => { 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') @@ -973,7 +982,7 @@ it.layer(layerProjections)("rollback history reads", (it) => { it.effect("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); @@ -1005,7 +1014,7 @@ it.layer(layerProjections)("rollback history reads", (it) => { 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 735dbd044fdbc..76ad9c2092b40 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -365,7 +365,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 }]; }); @@ -376,7 +376,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), ), ); @@ -440,7 +440,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 085fecf86c5d8..6ad8d7737b75d 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -220,6 +220,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; @@ -651,19 +652,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 82721f6762b2d..fff310f367aa7 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -235,6 +235,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, @@ -486,6 +490,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 250f078318103..a598bdefc95b9 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15043,7 +15043,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 9fb93526ec188..ea8f67dd447cc 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -269,7 +269,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, @@ -288,6 +299,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. @@ -321,6 +335,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; @@ -6467,7 +6482,8 @@ export const layer: Layer.Layer`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} ${ options?.preservedCheckpoints === "baselines" - ? sql`AND ordinal_within_scope IN (0, ${run === undefined ? null : Math.max(0, run.ordinal - 1)})` + ? sql`AND ordinal_within_scope IN (0, ${previousRunOrdinal}, ( + -- History refresh moves app runs without changing their Git checkpoint slots. + SELECT previous_checkpoint.ordinal_within_scope + FROM orchestration_v2_projection_runs AS previous_run + JOIN orchestration_v2_projection_checkpoints AS previous_checkpoint + ON previous_checkpoint.checkpoint_id = json_extract(previous_run.payload_json, '$.checkpointId') + WHERE previous_run.thread_id = ${threadId} + AND previous_run.ordinal = ${previousRunOrdinal} + AND previous_checkpoint.scope_id = ${target.scopeId} + AND previous_checkpoint.run_id = previous_run.run_id + ))` : sql`` }`, sql`SELECT payload_json FROM orchestration_v2_projection_checkpoint_scopes @@ -6551,6 +6585,14 @@ export const layer: Layer.Layer + checkpoint.run_id !== null && + checkpoint.app_run_ordinal === previousRunOrdinal, + ); return { run, rootNode: @@ -6566,6 +6608,10 @@ export const layer: Layer.Layer 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, @@ -6622,6 +6668,7 @@ export const layer: Layer.Layer`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 @@ -6664,14 +6716,20 @@ export const layer: Layer.Layer`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( @@ -6690,6 +6748,7 @@ export const layer: Layer.Layer ({ + 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 13401ce2f36c4..91e534e19421b 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -279,6 +279,7 @@ const layerAgentSessionImporterProvided = AgentSessionImporter.layer.pipe( layerProjectService, layerOrchestratorProvided, layerEventSink, + EffectOutbox.layer, IdAllocator.layer, ProviderSessionRuntime.layer, ProviderAdapterRegistry.layerFromProviderInstanceRegistry, diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 0ea71d971e20e..39d5dbabc5dd6 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, @@ -33,6 +41,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"; @@ -62,6 +71,7 @@ const stores = Layer.mergeAll( 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, ProjectionMaintenance.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), @@ -264,9 +274,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 }), @@ -288,6 +298,7 @@ const makeImporter = Effect.fn(function* ( return { run: importer.importRecentAgentThreads({ projectId }), importNativeHistory: importer.importNativeHistory, + refreshCodexHistory: importer.refreshCodexHistory, published, }; }); @@ -585,44 +596,492 @@ it.effect("certifies new native history only with its messages after a partial i }).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).toEqual([ + { importedCount: 0, skippedCount: 0 }, + { importedCount: 0, skippedCount: 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 shared Codex history after a provider switch and 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 = []; + const requestedInstances: 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 getAdapter = (instanceId: ProviderInstanceId) => + Effect.sync(() => { + requestedInstances.push(instanceId); + return adapter; + }); + const importer = yield* makeImporter([], Effect.void, getAdapter); + 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"]); + expect(requestedInstances.at(-1)).toBe(nativeThread.providerInstanceId); + 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 alternateInstanceId = ProviderInstanceId.make("codex-shared-home"); + const continuedRun: OrchestrationV2Run = { + ...localRun, + id: continuedId, + ordinal: 5, + providerInstanceId: alternateInstanceId, + modelSelection: { ...localRun.modelSelection, instanceId: alternateInstanceId }, + 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: [ + // Resuming in a Codex instance with the same home retains the native thread and its turns. + { + id: EventId.make(`${continuedId}:shared-home-switch`), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { + ...nativeThread, + providerInstanceId: alternateInstanceId, + lastRunOrdinal: continuedRun.ordinal, + }, + }, + { + 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), + getAdapter, ); - 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"]); + expect(requestedInstances.slice(-2)).toEqual([alternateInstanceId, alternateInstanceId]); + + 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 21d9ea56b5524..5b6249399c92e 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 ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; @@ -89,6 +96,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, @@ -152,11 +161,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: [], @@ -169,10 +178,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: [], } @@ -185,7 +197,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, @@ -195,6 +207,139 @@ 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; +} + function historyTruncatedEvent(input: { readonly threadId: ThreadId; readonly at: DateTime.Utc; @@ -232,12 +377,14 @@ const make = Effect.gen(function* () { 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 maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2; 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, @@ -357,43 +504,55 @@ const make = Effect.gen(function* () { }, { onConflict: "ignore" }, ); - const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, [])); + const existing = yield* orchestrator + .getThreadRecords(threadId, ["messages", "runs", "turnItems"], { + turnItemTypes: ["user_message", "assistant_message"], + }) + .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, runs, 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 }); } - } - if (Option.isSome(existing) && existing.value.thread.deletedAt === null) { - // A transcript can change after the import. A thread without runs holds only - // imported history, so it takes the changed messages; record the transcript - // only once the thread holds exactly its messages. - const current = yield* threadCommands.withLock( - threadId, - Effect.gen(function* () { - const { messages: stored, runs } = yield* orchestrator.getThreadRecords(threadId, [ - "messages", - "runs", - ]); - const changed = thread.messages.flatMap((message, index) => - stored[index]?.role === message.role && stored[index]?.text === message.text - ? [] - : messageEvents({ threadId, index, message }), - ); - if (changed.length === 0 && stored.length === thread.messages.length) return true; + // A deleted import falls through and comes back as its transcript. A live import + // keeps the stored turn order: message timestamps can disagree with that order. + if (current.deletedAt === null) { + const orderedItems = turnItems.filter( + (item) => item.type === "user_message" || item.type === "assistant_message", + ); + const stored = + orderedItems.length === messages.length + ? orderedItems.map((item) => ({ + role: item.type === "user_message" ? "user" : "assistant", + text: item.text, + })) + : messages; + const changed = thread.messages.flatMap((message, index) => + stored[index]?.role === message.role && stored[index]?.text === message.text + ? [] + : messageEvents({ threadId, index, message }), + ); + if (changed.length > 0 || stored.length !== thread.messages.length) { if (runs.length > 0 || stored.length > thread.messages.length) return false; const events = [ ...(thread.omittedMessageCount > 0 ? [ historyTruncatedEvent({ threadId, - at: existing.value.thread.createdAt, + at: current.createdAt, omittedMessageCount: thread.omittedMessageCount, }), ] @@ -409,14 +568,12 @@ const make = Effect.gen(function* () { })), ), }); - return true; - }), - ); - if (!current) return false; - yield* persistRuntime; - yield* runtimes.recordImportedTranscript({ threadId, source }); - importedThreadIds.add(threadId); - return null; + } + yield* persistRuntime; + yield* runtimes.recordImportedTranscript({ threadId, source }); + importedThreadIds.add(threadId); + return null; + } } const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL; @@ -519,40 +676,39 @@ const make = Effect.gen(function* () { ]; // A deleted thread comes back as its transcript alone. Finish its purge, then create // it again in the tombstone: clients reload a thread whose replay holds a creation. + // The import already holds this thread's command lock. Taking it again deadlocks. const committed = Option.isNone(existing) ? yield* eventSink.write({ unlessNativeThreadOwned: providerThread, events }) - : yield* threadCommands.withLock( - threadId, - Effect.gen(function* () { - yield* maintenance.purgeDeletedThread(threadId); - // The purge leaves a thread that a live fork still shows or that queued teardown - // still reads; its title marks one that ran. That teardown works by thread id, - // so it must not find the thread restored. - const kept = yield* orchestrator.getThreadRecords(threadId, []); - if ( - kept.thread.deletedAt === null || - kept.thread.title !== ProjectionMaintenance.DELETED_THREAD_TITLE - ) { - return null; - } - // The tombstone keeps the first import's creation event, and its id with it. - return yield* eventSink.write({ - unlessNativeThreadOwned: providerThread, - events: yield* Effect.forEach(events, (event) => - Effect.map(idAllocator.allocate.event({ threadId }), (id) => ({ - ...event, - id, - })), - ), - }); - }), - ); + : yield* Effect.gen(function* () { + yield* maintenance.purgeDeletedThread(threadId); + // The purge leaves a thread that a live fork still shows or that queued teardown + // still reads; its title marks one that ran. That teardown works by thread id, + // so it must not find the thread restored. + const kept = yield* orchestrator.getThreadRecords(threadId, []); + if ( + kept.thread.deletedAt === null || + kept.thread.title !== ProjectionMaintenance.DELETED_THREAD_TITLE + ) { + return null; + } + // The tombstone keeps the first import's creation event, and its id with it. + return yield* eventSink.write({ + unlessNativeThreadOwned: providerThread, + events: yield* Effect.forEach(events, (event) => + Effect.map(idAllocator.allocate.event({ threadId }), (id) => ({ + ...event, + id, + })), + ), + }); + }); if (committed === null) return false; if (committed.length === 0) return null; yield* persistRuntime; 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, @@ -671,7 +827,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/ws.ts b/apps/server/src/ws.ts index b4c37c5286c68..d12e376b1756d 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3289,6 +3289,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 800c9f3b5b1fb..58aa7f7653b0f 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -4348,7 +4348,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 387c78b16e0a0..476abbd6cc92e 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.tsx @@ -1,11 +1,19 @@ import { useAtomMount } from "@effect/atom-react"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { createEnvironmentRpcCommand, runAtomCommand } from "@t3tools/client-runtime/state/runtime"; import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits"; -import { type ScopedThreadRef } from "@t3tools/contracts"; +import { type ScopedThreadRef, WS_METHODS } from "@t3tools/contracts"; import { Atom } from "effect/reactivity"; +import { useEffect } from "react"; import { environmentCatalog } from "../../connection/catalog"; -import { getDocumentActivity, subscribeDocumentActivity } from "../../lib/documentActivity"; +import { connectionAtomRuntime } from "../../connection/runtime"; +import { + getDocumentActivity, + subscribeDocumentActivity, + subscribeDocumentReturn, +} from "../../lib/documentActivity"; +import { appAtomRegistry } from "../../rpc/atomRegistry"; import { useUiStateStore } from "../../uiStateStore"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; @@ -28,10 +36,38 @@ const threadVisitTracker = createThreadVisitTracker({ viewingAtom: documentViewedAtom, }); +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 de353b6b3acb1..b4dd363b078ed 100644 --- a/docs/user/welcome-page.md +++ b/docs/user/welcome-page.md @@ -35,4 +35,5 @@ Conversation import is best-effort: - Keeps the first user prompt and the most recent visible user/assistant messages (up to 200 messages total), omitting tool activity and attachments. - Skips malformed/empty sessions, files over 4 GiB, sessions over 32 MiB of kept text/metadata, or sessions with over 100,000 records. -- Each import pass reads up to 100 conversations and 4 GiB per project. Reopen the Welcome page and select the project in **Review all** to continue importing a larger batch; already-imported conversations are skipped. +- Each import pass reads up to 100 conversations and 4 GiB per project. Reopen the Welcome page and select the project in **Review all** to continue importing a larger batch; unchanged conversations are skipped. +- Re-importing a conversation updates its existing messages if you have not run a turn in T3 Code yet. After running a Codex turn in T3 Code, you can continue the same conversation in Codex. Opening the conversation in T3 Code or returning to its window picks up completed text turns from that Codex session. diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 225922ccca137..bb88f2e79542a 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 4cc14681a1947..aaca4c362d9cb 100644 --- a/packages/client-runtime/src/state/threadRepositories.test.ts +++ b/packages/client-runtime/src/state/threadRepositories.test.ts @@ -387,14 +387,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", }, @@ -404,6 +404,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), @@ -430,7 +436,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 4b358f872106d..c2313cfc26284 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 4fee4fceb90b0..092634b424ddc 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -56,6 +56,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 04ea9df12bbd2..0d12aa3df1a60 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1373,6 +1373,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 9c936925aafe9..a05d536dc1a5c 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -121,6 +121,7 @@ import { AgentSessionImportProjectChangedError, AgentSessionImportProjectNotFoundError, AgentSessionImportResult, + AgentSessionRefreshCodexHistoryInput, AgentSessionScanInput, AgentSessionScanResult, AgentSessionScanError, @@ -516,6 +517,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", @@ -1791,6 +1793,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, @@ -2688,6 +2699,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 4ec7b70c1b4a1..46edd605a9234 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"; @@ -767,6 +768,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; @@ -878,6 +890,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;