diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 7c58e6ad079e8..8af3c4465f674 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -54,6 +54,7 @@ import * as ProviderTurnStart from "./ProviderTurnStartService.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; +import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; const isDomainEvent = Schema.is(OrchestrationV2DomainEvent); @@ -137,6 +138,7 @@ function startWithMissingWorktree( Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}), Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }), IdAllocator.layer, + Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false), realPath: (target: string) => @@ -948,6 +950,7 @@ function makeLocalCommandHarness(input: { }), }), IdAllocator.layer, + Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}), layerWorktreeLocation(input.worktreesDir), input.fileSystem === undefined ? FileSystem.layerNoop({ exists: () => Effect.succeed(true) }) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 98652036118fc..c692335f8ff08 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -57,6 +57,7 @@ import { } from "@t3tools/provider-core/server/failure"; import * as RunExecutionService from "./RunExecutionService.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; +import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import { isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, @@ -145,6 +146,7 @@ export const layer: Layer.Layer< | ProviderSessionManager.ProviderSessionManagerV2 | RunExecutionService.RunExecutionServiceV2 | RuntimePolicy.RuntimePolicyV2 + | TurnItemPositionStore.TurnItemPositionStoreV2 > = Layer.effect( ProviderTurnStartServiceV2, Effect.gen(function* () { @@ -161,6 +163,7 @@ export const layer: Layer.Layer< const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const runExecution = yield* RunExecutionService.RunExecutionServiceV2; const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2; + const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2; const isManagedWorktreePath = yield* makeIsManagedWorktreePath; const resolveRecreateBase = Effect.fn("ProviderTurnStartService.resolveRecreateBase")( @@ -1115,6 +1118,7 @@ export const layer: Layer.Layer< let resumedRetryHandoff: ReadonlyArray | undefined; let resumedHandoffContext: ReturnType | undefined; let portableForkFallback: OrchestrationV2ContextHandoff | undefined; + let recoveryTurnItem: OrchestrationV2TurnItem | undefined; const loadedProviderThread = yield* Effect.gen(function* () { if (nativeForkTransfer !== undefined) { const sourceProjection = yield* projectionStore.getThreadRecords( @@ -1369,6 +1373,50 @@ export const layer: Layer.Layer< const { handoff, transferId, createdAt } = yield* recoveryHandoff; effectiveHandoffs = withRecoveryHandoff(handoff); resumeFellBack = true; + const previousRun = projection.runs.findLast( + (candidate) => + candidate.providerThreadId === providerThread.id && + candidate.ordinal < run.ordinal && + candidate.startedAt !== null, + ); + // Stable per run so a retried start reuses the reserved run-start position. + const handoffTurnItemId = idAllocator.derive.runSignalTurnItem({ + runId, + signal: "resume-fallback-handoff", + }); + const handoffTurnItem: OrchestrationV2TurnItem = { + id: handoffTurnItemId, + threadId: projection.thread.id, + runId, + nodeId: rootNode.id, + providerThreadId: providerThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + // The summary is delivered ahead of this run's own handoffs and message. + ordinal: yield* turnItemPositions.allocate({ + threadId: projection.thread.id, + turnItemId: handoffTurnItemId, + runId, + runOrdinal: run.ordinal, + placement: "run_start", + }), + status: "completed", + title: "Recovered context", + startedAt: createdAt, + completedAt: createdAt, + updatedAt: createdAt, + type: "handoff", + contextHandoffId: handoff.id, + fromProviderThreadIds: handoff.fromProviderThreadIds, + toProviderThreadId: handoff.toProviderThreadId, + fromProviderInstanceIds: [providerThread.providerInstanceId], + toProviderInstanceId: run.providerInstanceId, + fromModelSelections: previousRun === undefined ? [] : [previousRun.modelSelection], + toModel: run.modelSelection.model, + strategy: handoff.strategy, + summary: handoff.summaryText, + }; yield* eventSink.write({ events: [ { @@ -1408,6 +1456,7 @@ export const layer: Layer.Layer< }, ], }); + recoveryTurnItem = handoffTurnItem; return replacement; }); if (loadedProviderThread === undefined) return; @@ -1514,6 +1563,20 @@ export const layer: Layer.Layer< }, }, ]), + // Shown only once the replacement session commits with the running transition. + ...(recoveryTurnItem === undefined + ? [] + : [ + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "turn-item.updated" as const, + threadId: projection.thread.id, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: recoveryTurnItem, + }, + ]), { id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), type: "run.updated", diff --git a/apps/server/src/orchestration-v2/TurnItemPositionStore.test.ts b/apps/server/src/orchestration-v2/TurnItemPositionStore.test.ts index 579c82f03ee40..ea3a70bdf22af 100644 --- a/apps/server/src/orchestration-v2/TurnItemPositionStore.test.ts +++ b/apps/server/src/orchestration-v2/TurnItemPositionStore.test.ts @@ -56,3 +56,24 @@ it.effect("reuses an item's position without attempting another allocation inser ); }).pipe(Effect.provide(layerTest)), ); + +it.effect("places a run-start item ahead of the run's items, then appends once taken", () => + Effect.gen(function* () { + const positions = yield* TurnItemPositionStore.TurnItemPositionStoreV2; + const threadId = ThreadId.make("thread:run-start"); + const allocate = (id: string, placement?: "run_start") => + positions.allocate({ + threadId, + turnItemId: TurnItemId.make(id), + runId: RunId.make("run:2"), + runOrdinal: 2, + ...(placement === undefined ? {} : { placement }), + }); + const message = yield* allocate("item:message"); + const recovery = yield* allocate("item:recovery", "run_start"); + assert.isBelow(recovery, message); + assert.isAbove(recovery, 1_999_999); + assert.equal(yield* allocate("item:retry-recovery", "run_start"), message + 1); + assert.equal(yield* allocate("item:reply"), message + 2); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts index 03636b34153c9..95eb9cdc2415f 100644 --- a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts +++ b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts @@ -22,6 +22,8 @@ export interface TurnItemPositionStoreV2Shape { readonly turnItemId: TurnItemId; readonly runId: RunId | null; readonly runOrdinal?: number; + // `run_start` takes the run's unused first slot, ahead of its items, and appends once it is taken. + readonly placement?: "append" | "run_start"; }) => Effect.Effect; readonly normalize: ( item: OrchestrationV2TurnItem, @@ -42,7 +44,13 @@ export const layer: Layer.Layer` SELECT ordinal FROM orchestration_v2_turn_item_positions @@ -68,7 +76,11 @@ export const layer: Layer.Layer ${lowerBound} THEN ${lowerBound} ELSE MAX(ordinal) + 1 END` + : sql`COALESCE(MAX(ordinal), ${lowerBound}) + 1` + } FROM orchestration_v2_turn_item_positions WHERE thread_id = ${threadId} AND ordinal >= ${lowerBound} diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index ba1dadad1864c..5d540448264e5 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -173,6 +173,7 @@ const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pip layerProviderAuthServiceProvided, layerRunExecutionServiceProvided, layerRuntimePolicyProvided, + TurnItemPositionStore.layer, ), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 83eee8f66a5dc..728e4f2189c26 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -1335,6 +1335,20 @@ describe("orchestration v2 provider switching", () => { assert.isFalse(turns[1]?.nativeThreadHasTurns); assert.equal(turns[2]?.nativeThreadId, turns[1]?.nativeThreadId); assert.isTrue(turns[2]?.nativeThreadHasTurns); + + const projection = yield* orchestrator.getThreadProjection(threadId); + const run2 = projection.runs[1]!; + const handoff = projection.contextHandoffs.find( + (candidate) => candidate.targetRunId === run2.id, + ); + assert.deepEqual( + projection.turnItems + .filter((item) => item.runId === run2.id) + .toSorted((left, right) => left.ordinal - right.ordinal) + .slice(0, 2) + .map((item) => (item.type === "handoff" ? item.contextHandoffId : item.type)), + [handoff?.id, "user_message"], + ); }).pipe( Effect.provide( ProviderReplayHarness.layerWithRegistry(