From 7cfdb4e79ead786b4ab27de02513bc9e09dce5c4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 1 May 2026 18:08:56 -0700 Subject: [PATCH] Add merge-back context handoff support - Map fork and merge-back turns into stored handoffs and transfer resolutions - Add shell snapshot projection support plus coverage tests - Update replay fixtures and web contracts for the new turn flow --- .../orchestration-v2/ContextHandoffService.ts | 191 +++++- .../src/orchestration-v2/Orchestrator.ts | 469 +++++++++++++- .../orchestration-v2/ProjectionStore.test.ts | 128 ++++ .../src/orchestration-v2/ProjectionStore.ts | 466 ++++++++++++- .../orchestration-v2/ProviderSwitchService.ts | 3 +- apps/server/src/orchestration-v2/TODO.md | 90 +-- .../src/orchestration-v2/runtimeLayer.ts | 5 + .../CodexReplayFixtures.integration.test.ts | 47 ++ .../testkit/OrchestratorScenario.ts | 5 + .../testkit/ProviderReplayHarness.ts | 5 + .../testkit/ThreadFork.integration.test.ts | 602 ++++++++++++++++- .../fixtures/message_steering/codex_output.ts | 4 + .../fixtures/multi_turn/codex_output.ts | 2 + .../fixtures/plan_questions/codex_output.ts | 2 + .../fixtures/proposed_plan/codex_output.ts | 2 + .../fixtures/queued_turn/codex_output.ts | 4 + .../testkit/fixtures/shared.ts | 33 + .../testkit/fixtures/simple/codex_output.ts | 2 + .../fixtures/thread_rollback/codex_output.ts | 2 + .../fixtures/todo_list/codex_output.ts | 2 + .../codex_output.ts | 2 + .../codex_output.ts | 2 + .../tool_call_workspace_never/codex_output.ts | 2 + .../fixtures/turn_interrupt/codex_output.ts | 2 + .../fixtures/web_search/codex_output.ts | 2 + apps/server/src/server.test.ts | 42 +- apps/server/src/ws.ts | 70 +- apps/web/src/components/ChatView.browser.tsx | 2 + apps/web/src/environmentApi.ts | 2 + .../web/src/routes/debug.orchestration-v2.tsx | 612 +++++++++++------- apps/web/src/rpc/wsRpcClient.ts | 8 + apps/web/src/rpc/wsTransport.ts | 289 +++++++++ .../core-graph-and-data-model.md | 6 + packages/contracts/src/ipc.ts | 12 + packages/contracts/src/orchestrationV2.ts | 93 +++ packages/contracts/src/rpc.ts | 12 + 36 files changed, 2921 insertions(+), 301 deletions(-) create mode 100644 apps/server/src/orchestration-v2/ProjectionStore.test.ts create mode 100644 apps/web/src/rpc/wsTransport.ts diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.ts b/apps/server/src/orchestration-v2/ContextHandoffService.ts index ca0fe6785a..c426b2c43e 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.ts @@ -1,11 +1,14 @@ import { OrchestrationV2ContextHandoff, + type OrchestrationV2TurnItem, + type ProviderKind, ProviderThreadId, RunId, ThreadId, } from "@t3tools/contracts"; -import { Context, Schema } from "effect"; -import type { Effect } from "effect"; +import { Context, DateTime, Effect, Layer, Schema } from "effect"; + +import { IdAllocatorV2 } from "./IdAllocator.ts"; export class ContextHandoffPrepareError extends Schema.TaggedErrorClass()( "ContextHandoffPrepareError", @@ -32,9 +35,193 @@ export interface ContextHandoffServiceV2Shape { readonly fromProviderThreadIds: ReadonlyArray; readonly toProviderThreadId: ProviderThreadId; }) => Effect.Effect; + readonly prepareForkDelta: (input: { + readonly sourceThreadId: ThreadId; + readonly targetThreadId: ThreadId; + readonly targetRunId: RunId; + readonly transferId: OrchestrationV2ContextHandoff["transferId"]; + readonly fromProviderThreadIds: ReadonlyArray; + readonly toProviderThreadId: ProviderThreadId; + readonly fromProvider: ProviderKind; + readonly toProvider: ProviderKind; + readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; + readonly deltaItems: ReadonlyArray; + readonly createdAt: DateTime.Utc; + }) => Effect.Effect; } export class ContextHandoffServiceV2 extends Context.Service< ContextHandoffServiceV2, ContextHandoffServiceV2Shape >()("t3/orchestration-v2/ContextHandoffService") {} + +function compactText(text: string, maxLength = 240): string { + const compacted = text.replace(/\s+/g, " ").trim(); + if (compacted.length <= maxLength) { + return compacted; + } + return `${compacted.slice(0, maxLength - 3)}...`; +} + +function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null { + switch (item.type) { + case "user_message": + return `- User: ${compactText(item.text)}`; + case "assistant_message": + return `- Assistant: ${compactText(item.text)}`; + case "command_execution": + return `- Command: ${compactText(item.input)}`; + case "file_change": + return `- File change: ${item.fileName}`; + case "checkpoint": + return `- Checkpoint: ${item.files.length} files`; + case "handoff": + return `- Handoff: ${compactText(item.summary ?? item.strategy)}`; + default: + return null; + } +} + +function makeForkDeltaSummary(input: { + readonly sourceThreadId: ThreadId; + readonly targetThreadId: ThreadId; + readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; + readonly deltaItems: ReadonlyArray; +}): string { + const itemLines = input.deltaItems.flatMap((item) => { + const line = summarizeDeltaItem(item); + return line === null ? [] : [line]; + }); + return [ + "Merge-back context from forked conversation.", + `Source thread: ${input.sourceThreadId}`, + `Target thread: ${input.targetThreadId}`, + `Covered fork runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`, + "", + "Fork delta:", + ...(itemLines.length === 0 ? ["- No user-visible delta items."] : itemLines), + ].join("\n"); +} + +export function providerMessageWithContextHandoff(input: { + readonly handoff: OrchestrationV2ContextHandoff; + readonly userText: string; +}): string { + return [ + "Context handoff (merge_back / fork_delta_summary):", + input.handoff.summaryText, + "", + "User message:", + input.userText, + ].join("\n"); +} + +const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffService.layer")( + function* () { + const idAllocator = yield* IdAllocatorV2; + + const prepare = Effect.fn("orchestrationV2.contextHandoff.prepare")(function* (input: { + readonly threadId: ThreadId; + readonly targetRunId: RunId; + readonly fromProviderThreadIds: ReadonlyArray; + readonly toProviderThreadId: ProviderThreadId; + }) { + const now = yield* DateTime.now; + const handoffId = yield* idAllocator.allocate + .contextHandoff({ + threadId: input.threadId, + fromProvider: "codex", + toProvider: "codex", + }) + .pipe( + Effect.mapError( + (cause) => + new ContextHandoffPrepareError({ + threadId: input.threadId, + targetRunId: input.targetRunId, + fromProviderThreadIds: Array.from(input.fromProviderThreadIds), + toProviderThreadId: input.toProviderThreadId, + cause, + }), + ), + ); + return { + id: handoffId, + transferId: null, + threadId: input.threadId, + targetRunId: input.targetRunId, + fromProviderThreadIds: Array.from(input.fromProviderThreadIds), + toProviderThreadId: input.toProviderThreadId, + coveredRunOrdinals: { from: 1, to: 1 }, + strategy: "manual_context", + status: "ready", + summaryMessageId: null, + summaryText: "Manual context handoff.", + createdByProvider: null, + createdAt: now, + updatedAt: now, + } satisfies OrchestrationV2ContextHandoff; + }); + + const prepareForkDelta = Effect.fn("orchestrationV2.contextHandoff.prepareForkDelta")( + function* (input: { + readonly sourceThreadId: ThreadId; + readonly targetThreadId: ThreadId; + readonly targetRunId: RunId; + readonly transferId: OrchestrationV2ContextHandoff["transferId"]; + readonly fromProviderThreadIds: ReadonlyArray; + readonly toProviderThreadId: ProviderThreadId; + readonly fromProvider: ProviderKind; + readonly toProvider: ProviderKind; + readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; + readonly deltaItems: ReadonlyArray; + readonly createdAt: DateTime.Utc; + }) { + const handoffId = yield* idAllocator.allocate + .contextHandoff({ + threadId: input.targetThreadId, + fromProvider: input.fromProvider, + toProvider: input.toProvider, + }) + .pipe( + Effect.mapError( + (cause) => + new ContextHandoffPrepareError({ + threadId: input.targetThreadId, + targetRunId: input.targetRunId, + fromProviderThreadIds: Array.from(input.fromProviderThreadIds), + toProviderThreadId: input.toProviderThreadId, + cause, + }), + ), + ); + return { + id: handoffId, + transferId: input.transferId, + threadId: input.targetThreadId, + targetRunId: input.targetRunId, + fromProviderThreadIds: Array.from(input.fromProviderThreadIds), + toProviderThreadId: input.toProviderThreadId, + coveredRunOrdinals: input.coveredRunOrdinals, + strategy: "fork_delta_summary", + status: "ready", + summaryMessageId: null, + summaryText: makeForkDeltaSummary(input), + createdByProvider: null, + createdAt: input.createdAt, + updatedAt: input.createdAt, + } satisfies OrchestrationV2ContextHandoff; + }, + ); + + return ContextHandoffServiceV2.of({ + prepare, + prepareForkDelta, + }); + }, +); + +export const layer: Layer.Layer = Layer.effect( + ContextHandoffServiceV2, + makeContextHandoffService(), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 69befd4034..8b5b22bd9c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5,6 +5,7 @@ import { OrchestrationV2Command, type OrchestrationV2AppThread, type OrchestrationV2Checkpoint, + type OrchestrationV2ContextHandoff, type OrchestrationV2ContextSourcePoint, type OrchestrationV2ContextTransfer, type OrchestrationV2ContextTransferResolution, @@ -14,6 +15,7 @@ import { type OrchestrationV2ProviderThread, type OrchestrationV2Run, type OrchestrationV2RunAttempt, + type OrchestrationV2ShellSnapshot, type OrchestrationV2StoredEvent, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, @@ -24,6 +26,10 @@ import * as Semaphore from "effect/Semaphore"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts"; +import { + ContextHandoffServiceV2, + providerMessageWithContextHandoff, +} from "./ContextHandoffService.ts"; import { EventSinkV2 } from "./EventSink.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; import { ProjectionStoreV2 } from "./ProjectionStore.ts"; @@ -114,6 +120,7 @@ export interface OrchestratorV2Shape { readonly getThreadProjection: ( threadId: ThreadId, ) => Effect.Effect; + readonly getShellSnapshot: () => Effect.Effect; readonly getThreadEventSequence: ( threadId: ThreadId, ) => Effect.Effect; @@ -141,6 +148,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId { case "provider.switch": return command.threadId; case "thread.fork": + case "thread.merge_back": return command.targetThreadId; } } @@ -177,6 +185,29 @@ function latestStableRun(projection: OrchestrationV2ThreadProjection): Orchestra ); } +function runForSourcePoint( + projection: OrchestrationV2ThreadProjection, + sourcePoint: Extract< + OrchestrationV2Command, + { readonly type: "thread.fork" | "thread.merge_back" } + >["sourcePoint"], +): OrchestrationV2Run | null { + switch (sourcePoint.type) { + case "latest_stable": + return latestStableRun(projection); + case "run": + return projection.runs.find((run) => run.id === sourcePoint.runId) ?? null; + case "checkpoint": { + const checkpoint = projection.checkpoints.find( + (candidate) => candidate.id === sourcePoint.checkpointId, + ); + return checkpoint?.runId === null || checkpoint === undefined + ? null + : (projection.runs.find((run) => run.id === checkpoint.runId) ?? null); + } + } +} + function providerThreadForRun( projection: OrchestrationV2ThreadProjection, run: OrchestrationV2Run, @@ -225,8 +256,53 @@ function pendingForkTransferForThread( ); } +function pendingMergeBackTransfersForThread( + projection: OrchestrationV2ThreadProjection, +): ReadonlyArray { + return projection.contextTransfers.filter( + (transfer) => + transfer.type === "merge_back" && + transfer.targetThreadId === projection.thread.id && + transfer.status === "pending", + ); +} + +function latestContextTransfer( + transfers: ReadonlyArray, +): OrchestrationV2ContextTransfer | undefined { + return transfers.reduce((latest, transfer) => { + if (latest === undefined) { + return transfer; + } + return DateTime.toEpochMillis(transfer.updatedAt) >= DateTime.toEpochMillis(latest.updatedAt) + ? transfer + : latest; + }, undefined); +} + +function visibleDeltaRunOrdinals( + projection: OrchestrationV2ThreadProjection, + items: ReadonlyArray, +): OrchestrationV2ContextHandoff["coveredRunOrdinals"] { + const ordinals = items.flatMap((item) => { + if (item.runId === null) { + return []; + } + const run = projection.runs.find((candidate) => candidate.id === item.runId); + return run === undefined ? [] : [run.ordinal]; + }); + if (ordinals.length === 0) { + return { from: 1, to: 1 }; + } + return { + from: Math.min(...ordinals), + to: Math.max(...ordinals), + }; +} + const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(function* () { const checkpointService = yield* CheckpointServiceV2; + const contextHandoffService = yield* ContextHandoffServiceV2; const eventSink = yield* EventSinkV2; const commandReceipts = yield* CommandReceiptStoreV2; const idAllocator = yield* IdAllocatorV2; @@ -593,23 +669,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); - const sourcePoint = command.sourcePoint; - const sourceRun = (() => { - switch (sourcePoint.type) { - case "latest_stable": - return latestStableRun(sourceProjection); - case "run": - return sourceProjection.runs.find((run) => run.id === sourcePoint.runId) ?? null; - case "checkpoint": { - const checkpoint = sourceProjection.checkpoints.find( - (candidate) => candidate.id === sourcePoint.checkpointId, - ); - return checkpoint?.runId === null || checkpoint === undefined - ? null - : (sourceProjection.runs.find((run) => run.id === checkpoint.runId) ?? null); - } - } - })(); + const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint); if (sourceRun === null) { return yield* new OrchestratorDispatchError({ @@ -693,6 +753,142 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); + const dispatchThreadMergeBack = Effect.fn("orchestrationV2.dispatch.threadMergeBack")(function* ( + command: Extract, + events: Ref.Ref>, + ) { + yield* Effect.annotateCurrentSpan({ + "orchestration_v2.command_id": command.commandId, + "orchestration_v2.command_type": command.type, + "orchestration_v2.source_thread_id": command.sourceThreadId, + "orchestration_v2.target_thread_id": command.targetThreadId, + "orchestration_v2.source_point_type": command.sourcePoint.type, + }); + + const sourceProjection = yield* projectionStore + .getThreadProjection(command.sourceThreadId) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: command.sourceThreadId, + cause, + }), + ), + ); + const targetProjection = yield* projectionStore + .getThreadProjection(command.targetThreadId) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: command.targetThreadId, + cause, + }), + ), + ); + + if ( + sourceProjection.thread.lineage.relationshipToParent !== "fork" || + sourceProjection.thread.lineage.parentThreadId !== command.targetThreadId + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.sourceThreadId} is not a fork of ${command.targetThreadId}.`, + }); + } + + const sourceRun = runForSourcePoint(sourceProjection, command.sourcePoint); + if (sourceRun === null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `No stable source run was found for merge-back source ${command.sourcePoint.type}.`, + }); + } + if (sourceRun.status !== "completed") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Merge-back source run ${sourceRun.id} is ${sourceRun.status}; only completed runs are supported.`, + }); + } + + const forkTransfer = sourceProjection.contextTransfers.findLast( + (transfer) => + transfer.type === "fork" && + transfer.sourceThreadId === command.targetThreadId && + transfer.targetThreadId === command.sourceThreadId, + ); + if (forkTransfer === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `No fork transfer exists between ${command.targetThreadId} and ${command.sourceThreadId}.`, + }); + } + + const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun); + const now = command.createdAt ?? (yield* DateTime.now); + const emitEvent = emit(events, command); + const transferId = yield* mapDispatchError(command)( + idAllocator.allocate.contextTransfer({ + sourceThreadId: command.sourceThreadId, + targetThreadId: command.targetThreadId, + type: "merge_back", + }), + ); + const pendingMergeBackTransfersForPair = targetProjection.contextTransfers.filter( + (transfer) => + transfer.type === "merge_back" && + transfer.status === "pending" && + transfer.sourceThreadId === command.sourceThreadId && + transfer.targetThreadId === command.targetThreadId, + ); + const transfer: OrchestrationV2ContextTransfer = { + id: transferId, + type: "merge_back", + sourceThreadId: command.sourceThreadId, + targetThreadId: command.targetThreadId, + sourcePoint: contextSourcePointForRun(sourceProjection, sourceRun), + basePoint: forkTransfer.sourcePoint, + sourceProvider: sourceRun.provider, + targetProvider: targetProjection.thread.modelSelection.provider, + targetRunId: null, + status: "pending", + resolution: null, + createdBy: "user", + error: + sourceProviderThread === undefined ? "Source merge-back run has no provider thread." : null, + createdAt: now, + updatedAt: now, + consumedAt: null, + }; + + for (const pendingTransfer of pendingMergeBackTransfersForPair) { + yield* emitEvent({ + type: "context-transfer.updated", + threadId: command.targetThreadId, + provider: sourceRun.provider, + occurredAt: now, + payload: { + ...pendingTransfer, + status: "superseded", + error: `Superseded by merge-back transfer ${transferId}.`, + updatedAt: now, + }, + }); + } + yield* emitEvent({ + type: "context-transfer.created", + threadId: command.targetThreadId, + provider: sourceRun.provider, + occurredAt: now, + payload: transfer, + }); + }); + const dispatchSteerIntoRun = (input: { readonly command: Extract< OrchestrationV2Command, @@ -809,6 +1005,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: now, type: "user_message", messageId: input.messageId, + inputIntent: + input.command.type === "queued-message.promote-to-steer" + ? "promoted_queued_to_steer" + : "steer", text: input.text, attachments: input.attachments, }; @@ -1122,10 +1322,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (candidate) => candidate.id === projection.thread.activeProviderThreadId, ); const activeRun = projection.runs.find(isBlockingRun); + const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection); const shouldQueue = activeRun !== undefined && (dispatchMode.type === "start_immediately" || dispatchMode.type === "queue_after_active"); if (shouldQueue) { + if (pendingMergeBackTransfers.length > 0) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} has a pending merge-back transfer; queued merge-back consumption is not implemented yet.`, + }); + } const queueProviderThread = activeProviderThread ?? projection.providerThreads.find( @@ -1274,6 +1482,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: now, type: "user_message", messageId: command.messageId, + inputIntent: "queued_turn", text: command.text, attachments: command.attachments, }; @@ -1344,6 +1553,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; } const pendingForkTransfer = pendingForkTransferForThread(projection); + const pendingMergeBackSourceThreadIds = new Set( + pendingMergeBackTransfers.map((transfer) => transfer.sourceThreadId), + ); + if (pendingMergeBackSourceThreadIds.size > 1) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} has pending merge-back transfers from multiple forks.`, + }); + } + const pendingMergeBackTransfer = latestContextTransfer(pendingMergeBackTransfers); + const supersededMergeBackTransfers = pendingMergeBackTransfers.filter( + (transfer) => transfer.id !== pendingMergeBackTransfer?.id, + ); const now = yield* DateTime.now; const ordinal = nextRunOrdinal(projection); const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal }); @@ -1540,6 +1763,90 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }); const rootNodeId = idAllocator.derive.rootNode({ runId }); const emitEvent = emit(events, command); + const mergeBackSourceProjection = + pendingMergeBackTransfer === undefined + ? null + : yield* projectionStore + .getThreadProjection(pendingMergeBackTransfer.sourceThreadId) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: pendingMergeBackTransfer.sourceThreadId, + cause, + }), + ), + ); + const mergeBackSourceRun = + pendingMergeBackTransfer?.sourcePoint.runId === undefined || + mergeBackSourceProjection === null + ? null + : (mergeBackSourceProjection.runs.find( + (candidate) => candidate.id === pendingMergeBackTransfer.sourcePoint.runId, + ) ?? null); + if (pendingMergeBackTransfer !== undefined && mergeBackSourceRun === null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source run.`, + }); + } + const mergeBackSourceProviderThread = + mergeBackSourceProjection === null || mergeBackSourceRun === null + ? undefined + : providerThreadForRun(mergeBackSourceProjection, mergeBackSourceRun); + if (pendingMergeBackTransfer !== undefined && mergeBackSourceProviderThread === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source provider thread.`, + }); + } + const mergeBackDeltaItems = + mergeBackSourceProjection === null || mergeBackSourceRun === null + ? [] + : mergeBackSourceProjection.turnItems.filter((item) => { + if (item.runId === null) { + return false; + } + const itemRun = mergeBackSourceProjection.runs.find( + (candidate) => candidate.id === item.runId, + ); + return itemRun !== undefined && itemRun.ordinal <= mergeBackSourceRun.ordinal; + }); + const mergeBackHandoff = + pendingMergeBackTransfer === undefined || + mergeBackSourceProjection === null || + mergeBackSourceRun === null || + mergeBackSourceProviderThread === undefined + ? null + : yield* contextHandoffService + .prepareForkDelta({ + sourceThreadId: pendingMergeBackTransfer.sourceThreadId, + targetThreadId: command.threadId, + targetRunId: runId, + transferId: pendingMergeBackTransfer.id, + fromProviderThreadIds: [mergeBackSourceProviderThread.id], + toProviderThreadId: providerThread.id, + fromProvider: mergeBackSourceRun.provider, + toProvider: modelSelection.provider, + coveredRunOrdinals: visibleDeltaRunOrdinals( + mergeBackSourceProjection, + mergeBackDeltaItems, + ), + deltaItems: mergeBackDeltaItems, + createdAt: now, + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), + ); const checkpointScope = yield* checkpointService .prepareRootRunScope({ threadId: command.threadId, @@ -1574,7 +1881,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio startedAt: now, completedAt: null, checkpointId: null, - contextHandoffId: null, + contextHandoffId: mergeBackHandoff?.id ?? null, }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, @@ -1635,9 +1942,40 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: now, type: "user_message", messageId: command.messageId, + inputIntent: "turn_start", text: command.text, attachments: command.attachments, }; + const handoffTurnItem: OrchestrationV2TurnItem | null = + mergeBackHandoff === null + ? null + : { + id: idAllocator.derive.runSignalTurnItem({ + runId, + signal: `context-handoff:${mergeBackHandoff.id}`, + }), + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerThreadId: providerThread.id, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: ordinal * 100 - 1, + status: "completed", + title: "Merge-back context", + startedAt: now, + completedAt: now, + updatedAt: now, + type: "handoff", + contextHandoffId: mergeBackHandoff.id, + fromProviderThreadIds: mergeBackHandoff.fromProviderThreadIds, + toProviderThreadId: mergeBackHandoff.toProviderThreadId, + fromProviders: mergeBackSourceRun === null ? [] : [mergeBackSourceRun.provider], + toProvider: modelSelection.provider, + strategy: "fork_delta_summary", + summary: mergeBackHandoff.summaryText, + }; const nativeForkResolution: OrchestrationV2ContextTransferResolution | null = pendingForkTransfer === undefined || providerThread.nativeThreadRef === null ? null @@ -1645,6 +1983,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio strategy: "native_fork", providerThreadRef: providerThread.nativeThreadRef, }; + const mergeBackResolution: OrchestrationV2ContextTransferResolution | null = + pendingMergeBackTransfer === undefined || mergeBackHandoff === null + ? null + : { + strategy: "fork_delta_context", + contextHandoffId: mergeBackHandoff.id, + }; if (pendingForkTransfer !== undefined && nativeForkResolution !== null) { yield* emitEvent({ @@ -1678,6 +2023,53 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: providerThread, }); + if (mergeBackHandoff !== null) { + yield* emitEvent({ + type: "context-handoff.updated", + threadId: command.threadId, + runId, + provider: modelSelection.provider, + occurredAt: now, + payload: mergeBackHandoff, + }); + } + for (const supersededTransfer of supersededMergeBackTransfers) { + yield* emitEvent({ + type: "context-transfer.updated", + threadId: command.threadId, + runId, + provider: modelSelection.provider, + occurredAt: now, + payload: { + ...supersededTransfer, + status: "superseded", + error: + pendingMergeBackTransfer === undefined + ? "Superseded while consuming merge-back transfer." + : `Superseded by merge-back transfer ${pendingMergeBackTransfer.id}.`, + updatedAt: now, + }, + }); + } + if (pendingMergeBackTransfer !== undefined && mergeBackResolution !== null) { + yield* emitEvent({ + type: "context-transfer.updated", + threadId: command.threadId, + runId, + provider: modelSelection.provider, + occurredAt: now, + payload: { + ...pendingMergeBackTransfer, + targetProvider: modelSelection.provider, + targetRunId: runId, + status: "consumed", + resolution: mergeBackResolution, + error: null, + updatedAt: now, + consumedAt: now, + }, + }); + } yield* emitEvent({ type: "run.created", threadId: command.threadId, @@ -1723,6 +2115,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ), }); + if (handoffTurnItem !== null) { + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + provider: modelSelection.provider, + occurredAt: now, + payload: handoffTurnItem, + }); + } yield* emitEvent({ type: "message.updated", threadId: command.threadId, @@ -1761,6 +2164,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } + const providerMessageText = + mergeBackHandoff === null + ? command.text + : providerMessageWithContextHandoff({ + handoff: mergeBackHandoff, + userText: command.text, + }); yield* runExecution .startRootRun({ commandId: command.commandId, @@ -1782,7 +2192,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), message: { messageId: command.messageId, - text: command.text, + text: providerMessageText, attachments: command.attachments, }, modelSelection, @@ -2515,6 +2925,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.fork": yield* dispatchThreadFork(command, events); break; + case "thread.merge_back": + yield* dispatchThreadMergeBack(command, events); + break; default: return yield* dispatchUnsupported(command); } @@ -2633,6 +3046,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projectionStore .getThreadProjection(threadId) .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), + getShellSnapshot: () => + projectionStore.getShellSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: ThreadId.make("thread:shell"), + cause, + }), + ), + ), getThreadEventSequence: (threadId) => eventSink .latestSequence({ threadId }) @@ -2662,6 +3085,7 @@ export const layer: Layer.Layer< never, | CheckpointServiceV2 | CommandReceiptStoreV2 + | ContextHandoffServiceV2 | EventSinkV2 | IdAllocatorV2 | ProviderSessionManagerV2 @@ -2688,6 +3112,13 @@ export const layerUnavailable: Layer.Layer = Layer.succeed( cause: "Orchestration V2 live runtime is not configured.", }), ), + getShellSnapshot: () => + Effect.fail( + new OrchestratorProjectionError({ + threadId: ThreadId.make("thread:shell"), + cause: "Orchestration V2 live runtime is not configured.", + }), + ), getThreadEventSequence: (threadId) => Effect.fail( new OrchestratorProjectionError({ diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts new file mode 100644 index 0000000000..edfb55e7e6 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -0,0 +1,128 @@ +import { assert, it } from "@effect/vitest"; +import { EventId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { DateTime, Effect, Layer } from "effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts"; + +const TestLayer = Layer.mergeAll( + projectionStoreLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory)), + SqlitePersistenceMemory, +); + +it.layer(TestLayer)("ProjectionStoreV2", (it) => { + it.effect("builds shell snapshots without decoding full turn item payloads", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const nowIso = DateTime.formatIso(now); + const threadId = ThreadId.make("thread:projection-shell-stale-item"); + const projectId = ProjectId.make("project:projection-shell"); + + yield* projectionStore.apply({ + id: EventId.make("event:projection-shell-thread-created"), + type: "thread.created", + threadId, + occurredAt: now, + payload: { + id: threadId, + projectId, + title: "Projection shell", + defaultProvider: "codex", + modelSelection: { + provider: "codex", + model: "gpt-5.4", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + }, + }); + + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items ( + turn_item_id, + thread_id, + run_id, + node_id, + provider_thread_id, + provider_turn_id, + parent_item_id, + ordinal, + type, + status, + updated_at, + payload_json + ) + VALUES ( + ${"turn-item:stale-user-message"}, + ${threadId}, + ${null}, + ${null}, + ${null}, + ${null}, + ${null}, + ${0}, + ${"user_message"}, + ${"completed"}, + ${nowIso}, + ${JSON.stringify({ + id: "turn-item:stale-user-message", + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: null, + startedAt: nowIso, + completedAt: nowIso, + updatedAt: nowIso, + type: "user_message", + messageId: "message:stale-user-message", + text: "stale user message", + attachments: [], + })} + ) + `; + + const shell = yield* projectionStore.getShellSnapshot(); + const fullProjectionExit = yield* Effect.exit(projectionStore.getThreadProjection(threadId)); + + assert.deepEqual( + shell.threads.map((thread) => ({ + id: thread.id, + itemCount: thread.itemCount, + visibleItemCount: thread.visibleItemCount, + status: thread.status, + })), + [ + { + id: threadId, + itemCount: 1, + visibleItemCount: 1, + status: "idle", + }, + ], + ); + assert.equal(fullProjectionExit._tag, "Failure"); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ab7c089b4f..36d8ca661a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1,6 +1,10 @@ import type { OrchestrationV2ConversationMessage, OrchestrationV2DomainEvent, + OrchestrationV2ProjectedTurnItem, + OrchestrationV2ShellSnapshot, + OrchestrationV2ShellThreadStatus, + OrchestrationV2ThreadShell, OrchestrationV2ThreadProjection, OrchestrationV2TurnItem, } from "@t3tools/contracts"; @@ -20,7 +24,9 @@ import { OrchestrationV2RunJson as OrchestrationV2RunJsonSchema, OrchestrationV2RuntimeRequestJson as OrchestrationV2RuntimeRequestJsonSchema, OrchestrationV2TurnItemJson as OrchestrationV2TurnItemJsonSchema, + RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import { Context, DateTime, Effect, Layer, Ref, Schema } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -83,6 +89,10 @@ export interface ProjectionStoreV2Shape { readonly apply: ( event: OrchestrationV2DomainEvent, ) => Effect.Effect; + readonly getShellSnapshot: () => Effect.Effect< + OrchestrationV2ShellSnapshot, + ProjectionStoreV2Error + >; readonly getThreadProjection: ( threadId: ThreadId, ) => Effect.Effect; @@ -122,6 +132,7 @@ export function emptyProjection( checkpoints: [], contextHandoffs: [], contextTransfers: [], + visibleTurnItems: [], updatedAt: event.occurredAt, }; } @@ -184,10 +195,10 @@ export function applyToProjection( messages: upsertById(base.messages, event.payload), }; case "turn-item.updated": - return { + return withLocalVisibleTurnItems({ ...base, turnItems: upsertById(base.turnItems, event.payload), - }; + }); case "plan.updated": return { ...base, @@ -221,6 +232,26 @@ type PayloadRow = { readonly payload_json: string; }; +type ShellThreadRow = { + readonly thread_id: string; + readonly payload_json: string; + readonly latest_run_id: string | null; + readonly latest_run_status: string | null; + readonly item_count: number; +}; + +type ShellRunRow = { + readonly thread_id: string; + readonly run_id: string; + readonly ordinal: number; +}; + +type ShellRunItemCountRow = { + readonly thread_id: string; + readonly run_id: string; + readonly item_count: number; +}; + const encodeThreadPayload = Schema.encodeEffect( Schema.fromJsonString(OrchestrationV2AppThreadJsonSchema), ); @@ -375,6 +406,268 @@ function sortMessagesByTurnItemOrder( }); } +function localVisibleTurnItems( + turnItems: ReadonlyArray, +): Array { + return turnItems.map((item, position) => ({ + position, + visibility: "local", + sourceThreadId: item.threadId, + sourceItemId: item.id, + item, + })); +} + +function withLocalVisibleTurnItems( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadProjection { + return { + ...projection, + visibleTurnItems: localVisibleTurnItems(projection.turnItems), + }; +} + +function renumberVisibleTurnItems( + rows: ReadonlyArray>, +): Array { + return rows.map((row, position) => ({ ...row, position })); +} + +function makeForkMarkerTurnItem(input: { + readonly targetProjection: OrchestrationV2ThreadProjection; + readonly sourceThreadId: ThreadId; + readonly sourceRunId: NonNullable; +}): OrchestrationV2TurnItem { + const createdAt = input.targetProjection.thread.createdAt; + return { + id: TurnItemId.make(`turn-item:fork:${input.targetProjection.thread.id}`), + threadId: input.targetProjection.thread.id, + runId: null, + nodeId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: "Forked from conversation", + startedAt: null, + completedAt: createdAt, + updatedAt: createdAt, + type: "fork", + source: { type: "run", threadId: input.sourceThreadId, runId: input.sourceRunId }, + targetThreadId: input.targetProjection.thread.id, + }; +} + +function visibleTurnItemsThroughRun(input: { + readonly sourceProjection: OrchestrationV2ThreadProjection; + readonly sourceRunId: NonNullable; +}): Array> { + const sourceRun = input.sourceProjection.runs.find((run) => run.id === input.sourceRunId); + if (sourceRun === undefined) { + return []; + } + + const runOrdinalById = new Map(input.sourceProjection.runs.map((run) => [run.id, run.ordinal])); + return input.sourceProjection.visibleTurnItems + .filter((row) => { + const item = row.item; + if (item.threadId !== input.sourceProjection.thread.id) { + return true; + } + if (item.type === "fork") { + return true; + } + if (item.runId === null) { + return false; + } + const ordinal = runOrdinalById.get(item.runId); + return ordinal !== undefined && ordinal <= sourceRun.ordinal; + }) + .map((row) => ({ + visibility: "inherited", + sourceThreadId: row.sourceThreadId, + sourceItemId: row.sourceItemId, + item: row.item, + })); +} + +function buildVisibleTurnItems(input: { + readonly projection: OrchestrationV2ThreadProjection; + readonly sourceProjection: OrchestrationV2ThreadProjection | null; +}): Array { + const forkedFrom = input.projection.thread.forkedFrom; + if (forkedFrom?.type !== "run" || input.sourceProjection === null) { + return localVisibleTurnItems(input.projection.turnItems); + } + + const inherited = visibleTurnItemsThroughRun({ + sourceProjection: input.sourceProjection, + sourceRunId: forkedFrom.runId, + }); + const markerItem = makeForkMarkerTurnItem({ + targetProjection: input.projection, + sourceThreadId: forkedFrom.threadId, + sourceRunId: forkedFrom.runId, + }); + const local = input.projection.turnItems.map((item) => ({ + visibility: "local" as const, + sourceThreadId: item.threadId, + sourceItemId: item.id, + item, + })); + + return renumberVisibleTurnItems([ + ...inherited, + { + visibility: "synthetic", + sourceThreadId: forkedFrom.threadId, + sourceItemId: markerItem.id, + item: markerItem, + }, + ...local, + ]); +} + +export function threadShellFromProjection( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadShell { + const latestRun = projection.runs.at(-1) ?? null; + return { + id: projection.thread.id, + projectId: projection.thread.projectId, + title: projection.thread.title, + defaultProvider: projection.thread.defaultProvider, + modelSelection: projection.thread.modelSelection, + runtimeMode: projection.thread.runtimeMode, + interactionMode: projection.thread.interactionMode, + lineage: projection.thread.lineage, + forkedFrom: projection.thread.forkedFrom, + activeProviderThreadId: projection.thread.activeProviderThreadId, + latestRunId: latestRun?.id ?? null, + status: latestRun?.status ?? "idle", + itemCount: projection.turnItems.length, + visibleItemCount: projection.visibleTurnItems.length, + createdAt: projection.thread.createdAt, + updatedAt: projection.updatedAt, + }; +} + +type ShellThreadState = { + readonly thread: OrchestrationV2ThreadProjection["thread"]; + readonly latestRunId: RunId | null; + readonly latestRunStatus: OrchestrationV2ShellThreadStatus; + readonly itemCount: number; + readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"]; + readonly runOrdinalById: ReadonlyMap; + readonly itemCountByRunId: ReadonlyMap; +}; + +function shellStatusFromStoredRunStatus(status: string | null): OrchestrationV2ShellThreadStatus { + switch (status) { + case null: + return "idle"; + case "queued": + case "starting": + case "running": + case "waiting": + case "completed": + case "interrupted": + case "failed": + case "cancelled": + case "rolled_back": + return status; + default: + return "failed"; + } +} + +function itemCountThroughRun(input: { + readonly state: ShellThreadState; + readonly runId: RunId; +}): number { + const runOrdinal = input.state.runOrdinalById.get(input.runId); + if (runOrdinal === undefined) { + return 0; + } + + let count = 0; + for (const [runId, itemCount] of input.state.itemCountByRunId) { + const itemRunOrdinal = input.state.runOrdinalById.get(runId); + if (itemRunOrdinal !== undefined && itemRunOrdinal <= runOrdinal) { + count += itemCount; + } + } + return count; +} + +function visibleItemCountForShell(input: { + readonly threadId: ThreadId; + readonly statesByThreadId: ReadonlyMap; + readonly seenThreadIds?: ReadonlySet; +}): number { + const state = input.statesByThreadId.get(input.threadId); + if (state === undefined) { + return 0; + } + + const forkedFrom = state.thread.forkedFrom; + if (forkedFrom?.type !== "run") { + return state.itemCount; + } + + const seenThreadIds = input.seenThreadIds ?? new Set(); + if (seenThreadIds.has(state.thread.id)) { + return state.itemCount; + } + + const sourceState = input.statesByThreadId.get(forkedFrom.threadId); + if (sourceState === undefined) { + return state.itemCount; + } + + const sourceForkedFrom = sourceState.thread.forkedFrom; + const inheritedPrefixCount = + sourceForkedFrom?.type === "run" + ? visibleItemCountForShell({ + threadId: sourceState.thread.id, + statesByThreadId: input.statesByThreadId, + seenThreadIds: new Set([...seenThreadIds, state.thread.id]), + }) - sourceState.itemCount + : 0; + + return ( + inheritedPrefixCount + + itemCountThroughRun({ state: sourceState, runId: forkedFrom.runId }) + + 1 + + state.itemCount + ); +} + +function shellFromState(input: { + readonly state: ShellThreadState; + readonly visibleItemCount: number; +}): OrchestrationV2ThreadShell { + return { + id: input.state.thread.id, + projectId: input.state.thread.projectId, + title: input.state.thread.title, + defaultProvider: input.state.thread.defaultProvider, + modelSelection: input.state.thread.modelSelection, + runtimeMode: input.state.thread.runtimeMode, + interactionMode: input.state.thread.interactionMode, + lineage: input.state.thread.lineage, + forkedFrom: input.state.thread.forkedFrom, + activeProviderThreadId: input.state.thread.activeProviderThreadId, + latestRunId: input.state.latestRunId, + status: input.state.latestRunStatus, + itemCount: input.state.itemCount, + visibleItemCount: input.visibleItemCount, + createdAt: input.state.thread.createdAt, + updatedAt: input.state.updatedAt, + }; +} + export const layer: Layer.Layer = Layer.effect( ProjectionStoreV2, Effect.gen(function* () { @@ -1048,7 +1341,7 @@ export const layer: Layer.Layer = ), ); - const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) => + const readCanonicalProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) => Effect.gen(function* () { const threadRows = yield* sql` SELECT payload_json @@ -1214,6 +1507,7 @@ export const layer: Layer.Layer = checkpoints, contextHandoffs, contextTransfers, + visibleTurnItems: localVisibleTurnItems(turnItems), updatedAt: thread.updatedAt, } satisfies OrchestrationV2ThreadProjection; }).pipe( @@ -1227,8 +1521,136 @@ export const layer: Layer.Layer = ), ); + const readProjection = ( + threadId: ThreadId, + seenThreadIds: ReadonlySet, + ): Effect.Effect => + Effect.gen(function* () { + const projection = yield* readCanonicalProjection(threadId); + const forkedFrom = projection.thread.forkedFrom; + if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) { + return withLocalVisibleTurnItems(projection); + } + + const sourceProjection = yield* readProjection( + forkedFrom.threadId, + new Set([...seenThreadIds, threadId]), + ); + return { + ...projection, + visibleTurnItems: buildVisibleTurnItems({ + projection, + sourceProjection, + }), + }; + }); + + const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) => + readProjection(threadId, new Set()); + + const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () => + Effect.gen(function* () { + const [threadRows, runRows, itemCountRows] = yield* Effect.all([ + sql` + SELECT + t.thread_id, + t.payload_json, + ( + SELECT r.run_id + FROM orchestration_v2_projection_runs r + WHERE r.thread_id = t.thread_id + ORDER BY r.ordinal DESC, r.run_id DESC + LIMIT 1 + ) AS latest_run_id, + ( + SELECT r.status + FROM orchestration_v2_projection_runs r + WHERE r.thread_id = t.thread_id + ORDER BY r.ordinal DESC, r.run_id DESC + LIMIT 1 + ) AS latest_run_status, + ( + SELECT COUNT(*) + FROM orchestration_v2_projection_turn_items i + WHERE i.thread_id = t.thread_id + ) AS item_count + FROM orchestration_v2_projection_threads t + WHERE t.deleted_at IS NULL + ORDER BY t.updated_at ASC, t.thread_id ASC + `, + sql` + SELECT thread_id, run_id, ordinal + FROM orchestration_v2_projection_runs + `, + sql` + SELECT thread_id, run_id, COUNT(*) AS item_count + FROM orchestration_v2_projection_turn_items + WHERE run_id IS NOT NULL + GROUP BY thread_id, run_id + `, + ]); + + const runOrdinalsByThreadId = new Map>(); + for (const row of runRows) { + const threadId = ThreadId.make(row.thread_id); + const runId = RunId.make(row.run_id); + const existing = runOrdinalsByThreadId.get(threadId) ?? new Map(); + existing.set(runId, row.ordinal); + runOrdinalsByThreadId.set(threadId, existing); + } + + const itemCountsByThreadId = new Map>(); + for (const row of itemCountRows) { + const threadId = ThreadId.make(row.thread_id); + const runId = RunId.make(row.run_id); + const existing = itemCountsByThreadId.get(threadId) ?? new Map(); + existing.set(runId, row.item_count); + itemCountsByThreadId.set(threadId, existing); + } + + const states = yield* Effect.forEach(threadRows, (row) => + decodeThreadPayload(row.payload_json).pipe( + Effect.map( + (thread): ShellThreadState => ({ + thread, + latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id), + latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status), + itemCount: row.item_count, + updatedAt: thread.updatedAt, + runOrdinalById: + runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(), + itemCountByRunId: + itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(), + }), + ), + ), + ); + const statesByThreadId = new Map(states.map((state) => [state.thread.id, state])); + + return { + threads: states.map((state) => + shellFromState({ + state, + visibleItemCount: visibleItemCountForShell({ + threadId: state.thread.id, + statesByThreadId, + }), + }), + ), + }; + }).pipe( + Effect.mapError( + (cause) => + new ProjectionStoreReadError({ + threadId: ThreadId.make("thread:shell"), + cause, + }), + ), + ); + return { apply, + getShellSnapshot, getThreadProjection, } satisfies ProjectionStoreV2Shape; }), @@ -1266,10 +1688,46 @@ export const layerMemory: Layer.Layer = Layer.effect( return yield* result; } }), + getShellSnapshot: () => + Effect.gen(function* () { + const existing = yield* Ref.get(projections); + const shells = yield* Effect.forEach( + [...existing.keys()].toSorted((left, right) => + String(left).localeCompare(String(right)), + ), + (threadId) => + service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)), + ); + return { threads: shells }; + }), getThreadProjection: (threadId) => Effect.gen(function* () { const existing = yield* Ref.get(projections); - const projection = existing.get(threadId); + const readProjection = ( + targetThreadId: ThreadId, + seenThreadIds: ReadonlySet, + ): OrchestrationV2ThreadProjection | null => { + const projection = existing.get(targetThreadId); + if (!projection) { + return null; + } + const forkedFrom = projection.thread.forkedFrom; + if (forkedFrom?.type !== "run" || seenThreadIds.has(forkedFrom.threadId)) { + return withLocalVisibleTurnItems(projection); + } + const sourceProjection = readProjection( + forkedFrom.threadId, + new Set([...seenThreadIds, targetThreadId]), + ); + return { + ...projection, + visibleTurnItems: buildVisibleTurnItems({ + projection, + sourceProjection, + }), + }; + }; + const projection = readProjection(threadId, new Set()); if (!projection) { return yield* new ProjectionStoreThreadNotFoundError({ threadId }); } diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.ts index 72264e2662..d115bdb757 100644 --- a/apps/server/src/orchestration-v2/ProviderSwitchService.ts +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.ts @@ -6,8 +6,7 @@ import { RunId, ThreadId, } from "@t3tools/contracts"; -import { Context, Schema } from "effect"; -import type { Effect } from "effect"; +import { Context, Schema, Effect } from "effect"; export const ProviderSwitchStrategyV2 = Schema.Literals([ "resume_with_delta_handoff", diff --git a/apps/server/src/orchestration-v2/TODO.md b/apps/server/src/orchestration-v2/TODO.md index 8a58a74b13..78179c5236 100644 --- a/apps/server/src/orchestration-v2/TODO.md +++ b/apps/server/src/orchestration-v2/TODO.md @@ -16,6 +16,8 @@ implementation checklist for `apps/server/src/orchestration-v2`. by fork-local `thread/rollback`. - Native Codex fork-from-earlier-run has a real replay-backed test fixture: `testkit/fixtures/thread_fork_native_prior_turn`. +- Merge-back from a fork into its source thread records a `merge_back` context transfer, materializes + a `fork_delta_summary` context handoff, and injects that handoff into the next source-thread run. ## Projection Hardening @@ -27,20 +29,23 @@ Target docs: TODO: -- [ ] Add end-to-end projection assertions for forked threads, not only provider-context behavior. - The fork projection should show inherited user-visible items through the source point plus an - explicit fork marker. -- [ ] Decide and implement the projection representation for inherited fork history: - referenced lineage overlay vs physically duplicated projection items. Prefer referenced overlay - unless product requirements need independent editable history. +- [x] Add end-to-end projection assertions for forked threads, not only provider-context behavior. + The fork projection should show inherited user-visible items through the source point plus an + explicit fork marker. +- [x] Decide and implement the projection representation for inherited fork history: + referenced lineage overlay vs physically duplicated projection items. Prefer referenced overlay + unless product requirements need independent editable history. +- [x] Add local visible projection assertions to non-fork replay fixtures: + `visibleTurnItems` mirrors canonical local `turnItems` for simple, multi-turn, queue, + steering, interrupt, rollback, planning, tool, and web-search fixtures. - [ ] Ensure projections render rollback state consistently: - rolled-back runs/nodes/items, stale checkpoints, and active provider thread cursor. + rolled-back runs/nodes/items, stale checkpoints, and active provider thread cursor. - [ ] Add projection tests for interrupt edge cases: - provider emits chunks after interrupt requested, provider ignores/delays interrupt, interrupt is - immediately followed by queue/steer/start. + provider emits chunks after interrupt requested, provider ignores/delays interrupt, interrupt is + immediately followed by queue/steer/start. - [ ] Add projection tests for queue/steer flows: - queued message visibility, queue reorder, promote queued message to steer, and post-interrupt - dispatch visibility. + queued message visibility, queue reorder, promote queued message to steer, and post-interrupt + dispatch visibility. ## Context Transfer And Merge-Back @@ -51,18 +56,18 @@ Target docs: TODO: -- [ ] Implement merge-back from a fork into its source thread: - source fork point as `basePoint`, fork latest stable point as `sourcePoint`, and source-thread - next user message as the consuming run. -- [ ] Materialize delta context artifacts for merge-back and persist them as auditable - `ContextHandoff` records. -- [ ] Add replay-backed integration coverage for merge-back: - fork, explore in fork, merge back, then assert source provider receives only the fork delta plus - the new user message. +- [x] Implement merge-back from a fork into its source thread: + source fork point as `basePoint`, fork latest stable point as `sourcePoint`, and source-thread + next user message as the consuming run. +- [x] Materialize delta context artifacts for merge-back and persist them as auditable + `ContextHandoff` records. +- [x] Add replay-backed integration coverage for merge-back: + fork, explore in fork, merge back, then assert source provider receives only the fork delta plus + the new user message. - [ ] Implement portable context handoff for cross-provider forks and same-thread provider switches. - [ ] Define explicit failure states for unresolved context transfers: - missing source point, unsupported provider capability, context too large, source projection not - stable, and adapter resolution failure. + missing source point, unsupported provider capability, context too large, source projection not + stable, and adapter resolution failure. ## Capability And Policy Model @@ -73,18 +78,17 @@ Target docs: TODO: -- [ ] Expand `OrchestrationV2ProviderCapabilities` toward the documented nested shape: - sessions, threads, turns, streaming, tools, approvals, planning, subagents, context, - checkpointing, and identity. +- [ ] Audit capability use against the documented nested `OrchestrationV2ProviderCapabilities` + shape and fill any behavior gaps. - [ ] Keep orchestration decisions capability/policy driven. Shared runtime code should not branch on - provider name except at adapter registration/resolution boundaries. + provider name except at adapter registration/resolution boundaries. - [ ] Make optional adapter methods impossible to call without going through a policy wrapper or a - capability-checked branch. + capability-checked branch. - [ ] Add typed capability/policy errors for: - native fork unavailable, rollback unavailable, steering unavailable, interrupt unavailable, - context handoff unavailable, and weak terminal status. + native fork unavailable, rollback unavailable, steering unavailable, interrupt unavailable, + context handoff unavailable, and weak terminal status. - [ ] Add capability-aware tests using real adapter/test layers at provider boundaries only. Do not mock - core orchestration policy. + core orchestration policy. ## Checkpoint And Rollback @@ -96,14 +100,14 @@ Target docs: TODO: - [ ] Document current `checkpoint.rollback` command semantics in contracts/docs as full revert: - filesystem restore plus provider conversation rollback. + filesystem restore plus provider conversation rollback. - [ ] Decide whether we need separate commands for conversation-only rollback and filesystem-only - restore. Do not add them until a real product flow needs them. + restore. Do not add them until a real product flow needs them. - [ ] Add tests for rollback after fork and rollback inside fork: - source rollback should not corrupt child lineage, and fork rollback should not mutate source - provider state. + source rollback should not corrupt child lineage, and fork rollback should not mutate source + provider state. - [ ] Validate rollback behavior when no active provider thread exists. Current behavior fails; decide - whether a filesystem-only rollback fallback is useful or too surprising. + whether a filesystem-only rollback fallback is useful or too surprising. ## Provider Switching And Second Adapter @@ -115,12 +119,12 @@ Target docs: TODO: - [ ] Finish single-adapter primitives first: projections, fork source points, merge-back, rollback, and - context transfer resolution. + context transfer resolution. - [ ] Add the second adapter after the single-adapter core is stable enough to validate cross-provider - behavior. + behavior. - [ ] Use the second adapter to test: - cross-provider fork, same-thread provider switch, returning to a previous provider thread with - delta handoff, and unsupported capability fallback paths. + cross-provider fork, same-thread provider switch, returning to a previous provider thread with + delta handoff, and unsupported capability fallback paths. ## Subagents @@ -133,11 +137,11 @@ TODO: - [ ] Defer subagents until lineage, context transfer, and provider capability policy are stable. - [ ] Model native subagents and app-owned cross-provider subagents as related thread/subthread graph - entries with different creator/lifecycle policy. + entries with different creator/lifecycle policy. - [ ] Preserve native provider subagent refs where available, but do not make the app graph depend on - provider-native ids as primary ids. + provider-native ids as primary ids. - [ ] Add projection support for subagent lifecycle, wait, close, result transfer, and pending approvals - originating from subagents. + originating from subagents. FOOD FOR THOUGHT: @@ -147,8 +151,10 @@ FOOD FOR THOUGHT: - Keep debugger UI useful but temporary. Backend semantics and projections should be the source of truth. +- [x] Wire the debugger thread tree to persisted V2 shell state through websocket RPC instead of + debugger-local thread discovery state. - Continue exposing lightweight controls for new backend surfaces: fork from response, new thread, full revert from user message checkpoint, merge-back, and provider switch. - Avoid adding mock backend behavior for debugger convenience. In-memory debugger state is fine for - layout/tree affordances, but backend behavior must route through V2 commands/projections. + layout affordances, but backend behavior must route through V2 commands/projections. diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 919c53e1ca..057b91b6e1 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -4,6 +4,7 @@ import { layer as codexAdapterLayer } from "./Adapters/CodexAdapterV2.ts"; import { codexAppServerClientFactoryFromSettingsLayer } from "./Adapters/CodexAdapterV2.ts"; import { layer as checkpointServiceLayer } from "./CheckpointService.ts"; import { layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts"; +import { layer as contextHandoffServiceLayer } from "./ContextHandoffService.ts"; import { layer as eventSinkLayer } from "./EventSink.ts"; import { layer as eventStoreLayer } from "./EventStore.ts"; import { layer as idAllocatorLayer } from "./IdAllocator.ts"; @@ -26,6 +27,9 @@ const providerEventIngestorProvided = providerEventIngestorLayer.pipe( ); const checkpointServiceProvided = checkpointServiceLayer.pipe(Layer.provide(idAllocatorLayer)); +const contextHandoffServiceProvided = contextHandoffServiceLayer.pipe( + Layer.provide(idAllocatorLayer), +); const codexAdapterProvided = codexAdapterLayer.pipe( Layer.provide(codexAppServerClientFactoryFromSettingsLayer), @@ -65,6 +69,7 @@ export const OrchestrationV2LayerLive = orchestratorLayer.pipe( storesLayer, eventSinkProvided, commandReceiptStoreProvided, + contextHandoffServiceProvided, idAllocatorLayer, providerEventIngestorProvided, runtimePolicyLayer, diff --git a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts index 5c796be44a..1a4485b5b5 100644 --- a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts @@ -81,6 +81,32 @@ const scenarioExpectations = { turnCompletedCount: 2, approvalRequestCount: 0, }, + plan_questions: { + outgoing: [ + "initialize", + "initialized", + "thread/start", + "turn/start", + "item/tool/requestUserInput", + ], + incoming: [ + "turn/started", + "turn/completed", + "item/tool/requestUserInput", + "serverRequest/resolved", + "item/agentMessage/delta", + ], + turnStartCount: 1, + turnCompletedCount: 1, + approvalRequestCount: 0, + }, + proposed_plan: { + outgoing: ["initialize", "initialized", "thread/start", "turn/start"], + incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"], + turnStartCount: 1, + turnCompletedCount: 1, + approvalRequestCount: 0, + }, provider_thread_resume: { outgoing: ["initialize", "initialized", "thread/start", "thread/resume", "turn/start"], incoming: ["thread/started", "turn/started", "turn/completed", "item/agentMessage/delta"], @@ -88,6 +114,13 @@ const scenarioExpectations = { turnCompletedCount: 2, approvalRequestCount: 0, }, + queued_turn: { + outgoing: ["initialize", "initialized", "thread/start", "turn/start"], + incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"], + turnStartCount: 2, + turnCompletedCount: 2, + approvalRequestCount: 0, + }, message_steering: { outgoing: ["initialize", "initialized", "thread/start", "turn/start", "turn/steer"], incoming: [ @@ -115,6 +148,20 @@ const scenarioExpectations = { turnCompletedCount: 3, approvalRequestCount: 0, }, + todo_list: { + outgoing: ["initialize", "initialized", "thread/start", "turn/start"], + incoming: ["turn/started", "turn/completed", "turn/plan/updated", "item/agentMessage/delta"], + turnStartCount: 1, + turnCompletedCount: 1, + approvalRequestCount: 0, + }, + web_search: { + outgoing: ["initialize", "initialized", "thread/start", "turn/start"], + incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"], + turnStartCount: 1, + turnCompletedCount: 1, + approvalRequestCount: 0, + }, } as const; async function readTranscript(file: URL): Promise { diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 2a8609ab26..14f402a86b 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -2,6 +2,7 @@ import type { OrchestrationV2Command, OrchestrationV2DomainEvent, OrchestrationV2RuntimeRequest, + OrchestrationV2ShellSnapshot, OrchestrationV2StoredEvent, OrchestrationV2ThreadProjection, ProviderApprovalDecision, @@ -55,6 +56,7 @@ export interface OrchestratorV2ScenarioResult { readonly storedEvents: ReadonlyArray; readonly domainEvents: ReadonlyArray; readonly projections: ReadonlyMap; + readonly shellSnapshot: OrchestrationV2ShellSnapshot; } export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass()( @@ -81,6 +83,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray stored.event), projections, + shellSnapshot, }; }), ); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 411e79d2e9..d28b22ee7e 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -14,6 +14,7 @@ import { GitCoreLive } from "../../git/Layers/GitCore.ts"; import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; import { layer as checkpointServiceLayer } from "../CheckpointService.ts"; import { layer as commandReceiptStoreLayer } from "../CommandReceiptStore.ts"; +import { layer as contextHandoffServiceLayer } from "../ContextHandoffService.ts"; import { layer as eventSinkLayer } from "../EventSink.ts"; import { layer as eventStoreLayer } from "../EventStore.ts"; import { layer as idAllocatorLayer } from "../IdAllocator.ts"; @@ -192,6 +193,9 @@ export function makeOrchestratorV2ProviderReplayLayer< const checkpointServiceProvided = checkpointServiceLayer.pipe( Layer.provide(Layer.mergeAll(checkpointStoreLayer, idAllocatorLayer)), ); + const contextHandoffServiceProvided = contextHandoffServiceLayer.pipe( + Layer.provide(idAllocatorLayer), + ); const persistenceLayer = Layer.mergeAll( storesLayer, eventSinkProvided, @@ -216,6 +220,7 @@ export function makeOrchestratorV2ProviderReplayLayer< Layer.provide( Layer.mergeAll( checkpointServiceProvided, + contextHandoffServiceProvided, persistenceLayer, runtimeLayer, providerSessionManagerProvided, diff --git a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts index d97eb6da49..2a58b2f261 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts @@ -1,6 +1,13 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; -import { CommandId, MessageId, type OrchestrationV2Command, ThreadId } from "@t3tools/contracts"; +import { + CommandId, + MessageId, + type OrchestrationV2Command, + type ProviderReplayEntry, + type ProviderReplayTranscript, + ThreadId, +} from "@t3tools/contracts"; import { Effect, FileSystem, Path } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; @@ -53,6 +60,264 @@ function readTranscript(transcriptPath: string = TRANSCRIPT_PATH) { }); } +function compactExpectedText(text: string, maxLength = 240): string { + const compacted = text.replace(/\s+/g, " ").trim(); + if (compacted.length <= maxLength) { + return compacted; + } + return `${compacted.slice(0, maxLength - 3)}...`; +} + +function findCompletedAgentMessageText(input: { + readonly transcript: ProviderReplayTranscript; + readonly threadId: string; + readonly turnId: string; +}): string { + for (const entry of input.transcript.entries) { + if (entry.type !== "emit_inbound") { + continue; + } + const frame = entry.frame as { + readonly method?: unknown; + readonly params?: { + readonly threadId?: unknown; + readonly turnId?: unknown; + readonly item?: { + readonly type?: unknown; + readonly text?: unknown; + }; + }; + }; + if ( + frame.method === "item/completed" && + frame.params?.threadId === input.threadId && + frame.params.turnId === input.turnId && + frame.params.item?.type === "agentMessage" && + typeof frame.params.item.text === "string" + ) { + return frame.params.item.text; + } + } + throw new Error(`No completed agent message found for ${input.threadId}/${input.turnId}`); +} + +function makeExpectedForkDeltaSummary(input: { + readonly sourceThreadId: string; + readonly targetThreadId: string; + readonly forkUserText: string; + readonly forkAssistantText: string; +}): string { + return [ + "Merge-back context from forked conversation.", + `Source thread: ${input.sourceThreadId}`, + `Target thread: ${input.targetThreadId}`, + "Covered fork runs: 1-1", + "", + "Fork delta:", + `- User: ${compactExpectedText(input.forkUserText)}`, + `- Assistant: ${compactExpectedText(input.forkAssistantText)}`, + "- Checkpoint: 0 files", + ].join("\n"); +} + +function transcriptWithMergeBackContinuation(input: { + readonly transcript: ProviderReplayTranscript; + readonly providerMessageText: string; + readonly projectedUserText: string; + readonly assistantText: string; +}): ProviderReplayTranscript { + const sourceNativeThreadId = "019dd6ba-2681-7bf0-b051-141b0cbcbb27"; + const mergeBackNativeTurnId = "019dd6ba-5000-7000-8000-000000000001"; + const mergeBackUserItemId = "merge-back-user-message"; + const mergeBackAgentItemId = "merge-back-agent-message"; + const entriesWithoutExit = input.transcript.entries.filter( + (entry) => entry.type !== "runtime_exit", + ); + const continuation = [ + { + type: "expect_outbound", + label: "turn/start/merge-back-source", + frame: { + id: 9, + method: "turn/start", + params: { + threadId: sourceNativeThreadId, + input: [{ type: "text", text: input.providerMessageText }], + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "turn/start/merge-back-source", + frame: { + id: 9, + result: { + turn: { + id: mergeBackNativeTurnId, + items: [], + status: "inProgress", + error: null, + startedAt: 1777424041, + completedAt: null, + durationMs: null, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "thread/status/changed/merge-back-source", + frame: { + method: "thread/status/changed", + params: { + threadId: sourceNativeThreadId, + status: { type: "active", activeFlags: [] }, + }, + }, + }, + { + type: "emit_inbound", + label: "turn/started/merge-back-source", + frame: { + method: "turn/started", + params: { + threadId: sourceNativeThreadId, + turn: { + id: mergeBackNativeTurnId, + items: [], + status: "inProgress", + error: null, + startedAt: 1777424041, + completedAt: null, + durationMs: null, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "item/userMessage/started/merge-back-source", + frame: { + method: "item/started", + params: { + item: { + type: "userMessage", + id: mergeBackUserItemId, + content: [{ type: "text", text: input.projectedUserText, text_elements: [] }], + }, + threadId: sourceNativeThreadId, + turnId: mergeBackNativeTurnId, + }, + }, + }, + { + type: "emit_inbound", + label: "item/userMessage/completed/merge-back-source", + frame: { + method: "item/completed", + params: { + item: { + type: "userMessage", + id: mergeBackUserItemId, + content: [{ type: "text", text: input.projectedUserText, text_elements: [] }], + }, + threadId: sourceNativeThreadId, + turnId: mergeBackNativeTurnId, + }, + }, + }, + { + type: "emit_inbound", + label: "item/agentMessage/started/merge-back-source", + frame: { + method: "item/started", + params: { + item: { + type: "agentMessage", + id: mergeBackAgentItemId, + text: "", + phase: "final_answer", + memoryCitation: null, + }, + threadId: sourceNativeThreadId, + turnId: mergeBackNativeTurnId, + }, + }, + }, + { + type: "emit_inbound", + label: "item/agentMessage/delta/merge-back-source", + frame: { + method: "item/agentMessage/delta", + params: { + threadId: sourceNativeThreadId, + turnId: mergeBackNativeTurnId, + itemId: mergeBackAgentItemId, + delta: input.assistantText, + }, + }, + }, + { + type: "emit_inbound", + label: "item/agentMessage/completed/merge-back-source", + frame: { + method: "item/completed", + params: { + item: { + type: "agentMessage", + id: mergeBackAgentItemId, + text: input.assistantText, + phase: "final_answer", + memoryCitation: null, + }, + threadId: sourceNativeThreadId, + turnId: mergeBackNativeTurnId, + }, + }, + }, + { + type: "emit_inbound", + label: "thread/status/changed/merge-back-source", + frame: { + method: "thread/status/changed", + params: { threadId: sourceNativeThreadId, status: { type: "idle" } }, + }, + }, + { + type: "emit_inbound", + label: "turn/completed/merge-back-source", + frame: { + method: "turn/completed", + params: { + threadId: sourceNativeThreadId, + turn: { + id: mergeBackNativeTurnId, + items: [], + status: "completed", + error: null, + startedAt: 1777424041, + completedAt: 1777424042, + durationMs: 1000, + }, + }, + }, + }, + { type: "runtime_exit", status: "success" }, + ] satisfies ReadonlyArray; + + return { + ...input.transcript, + scenario: `${input.transcript.scenario}_merge_back`, + entries: [...entriesWithoutExit, ...continuation], + }; +} + describe("orchestration V2 thread fork", () => { it.effect( "creates an idle app fork and resolves it with Codex native thread/fork on first dispatch", @@ -355,6 +620,341 @@ describe("orchestration V2 thread fork", () => { "forking from the first source run must not preserve later source turns in native Codex context", ); assert.equal(targetProjection.contextTransfers[0]?.resolution?.strategy, "native_fork"); + + const visibleItems = targetProjection.visibleTurnItems.map((row) => row.item); + assert.deepEqual( + visibleItems.slice(0, 2).map((item) => item.type), + ["user_message", "assistant_message"], + "fork target projection should expose inherited source history through the fork point", + ); + assert.equal( + visibleItems[0]?.type === "user_message" ? visibleItems[0].inputIntent : undefined, + "turn_start", + "inherited fork history should preserve source message intent", + ); + assert.equal(targetProjection.visibleTurnItems[0]?.visibility, "inherited"); + assert.equal(targetProjection.visibleTurnItems[1]?.visibility, "inherited"); + const forkMarker = targetProjection.visibleTurnItems.find( + (row) => row.item.type === "fork", + ); + assert.isDefined(forkMarker, "fork target projection should include a visible fork marker"); + assert.equal(forkMarker.visibility, "synthetic"); + const targetShell = result.shellSnapshot.threads.find( + (thread) => thread.id === materialized.targetThreadId, + ); + assert.isDefined(targetShell, "shell snapshot should include the fork target thread"); + assert.equal(targetShell.visibleItemCount, targetProjection.visibleTurnItems.length); + assert.equal(targetShell.lineage.relationshipToParent, "fork"); + assert.equal(targetShell.forkedFrom?.type, "run"); + + const visibleText = visibleItems + .filter((item) => item.type === "user_message" || item.type === "assistant_message") + .map((item) => item.text) + .join("\n"); + assert.include(visibleText, "fork boundary alpha"); + assert.notInclude( + visibleText, + "fork boundary beta", + "fork target visible projection must not inherit source turns after the fork point", + ); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.effect("merges a fork delta back into the source thread through context handoff", () => + Effect.gen(function* () { + const rawTranscript = yield* readTranscript(PRIOR_TURN_TRANSCRIPT_PATH); + const forkNativeThreadId = "019dd6ba-47b7-7092-8688-9cf7fe5f6498"; + const sourceNativeThreadId = "019dd6ba-2681-7bf0-b051-141b0cbcbb27"; + const forkRepeatNativeTurnId = "019dd6ba-47eb-7041-ad45-5abe752c28c9"; + const forkPrompt = + "Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."; + const mergeBackPrompt = "Acknowledge the fork context with exactly: merge back acknowledged"; + const mergeBackAssistantText = "merge back acknowledged"; + const materialized = yield* Effect.gen(function* () { + const ids = yield* IdAllocatorV2; + const projectId = yield* ids.allocate.project({ + fixtureName: "thread-fork-native-prior-turn", + }); + const sourceThreadId = yield* ids.allocate.thread({ + fixtureName: "thread-fork-native-prior-turn-source", + projectId, + }); + const targetThreadId = ThreadId.make("thread-fork-native-prior-turn-target"); + const firstRunId = ids.derive.run({ threadId: sourceThreadId, ordinal: 1 }); + const forkRunId = ids.derive.run({ threadId: targetThreadId, ordinal: 1 }); + + const commands = [ + { + type: "thread.create", + commandId: yield* ids.allocate.command({ + fixtureName: "thread-fork-native-prior-turn", + commandName: "thread-create-source", + }), + threadId: sourceThreadId, + projectId, + title: "Source thread", + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }, + { + type: "message.dispatch", + commandId: yield* ids.allocate.command({ + fixtureName: "thread-fork-native-prior-turn", + commandName: "source-message-alpha", + }), + threadId: sourceThreadId, + messageId: MessageId.make("message-thread-fork-native-prior-turn-alpha"), + text: "For this fork-boundary fixture, respond with exactly: fork boundary alpha", + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }, + { + type: "message.dispatch", + commandId: yield* ids.allocate.command({ + fixtureName: "thread-fork-native-prior-turn", + commandName: "source-message-beta", + }), + threadId: sourceThreadId, + messageId: MessageId.make("message-thread-fork-native-prior-turn-beta"), + text: "For this fork-boundary fixture, respond with exactly: fork boundary beta", + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }, + { + type: "thread.fork", + commandId: CommandId.make("command-thread-fork-native-prior-turn"), + sourceThreadId, + targetThreadId, + sourcePoint: { type: "run", runId: firstRunId }, + title: "Forked from first response", + }, + { + type: "message.dispatch", + commandId: yield* ids.allocate.command({ + fixtureName: "thread-fork-native-prior-turn", + commandName: "target-message-repeat", + }), + threadId: targetThreadId, + messageId: MessageId.make("message-thread-fork-native-prior-turn-repeat"), + text: forkPrompt, + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }, + { + type: "thread.merge_back", + commandId: CommandId.make("command-thread-merge-back-native-prior-turn-stale"), + sourceThreadId: targetThreadId, + targetThreadId: sourceThreadId, + sourcePoint: { type: "run", runId: forkRunId }, + }, + { + type: "thread.merge_back", + commandId: CommandId.make("command-thread-merge-back-native-prior-turn"), + sourceThreadId: targetThreadId, + targetThreadId: sourceThreadId, + sourcePoint: { type: "run", runId: forkRunId }, + }, + { + type: "message.dispatch", + commandId: yield* ids.allocate.command({ + fixtureName: "thread-fork-native-prior-turn", + commandName: "source-message-merge-back", + }), + threadId: sourceThreadId, + messageId: MessageId.make("message-thread-fork-native-prior-turn-merge-back"), + text: mergeBackPrompt, + attachments: [], + modelSelection: CODEX_MODEL_SELECTION, + dispatchMode: { type: "start_immediately" }, + }, + ] satisfies ReadonlyArray; + + return { + sourceThreadId, + targetThreadId, + firstRunId, + forkRunId, + commands, + }; + }).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime); + const expectedSummary = makeExpectedForkDeltaSummary({ + sourceThreadId: materialized.targetThreadId, + targetThreadId: materialized.sourceThreadId, + forkUserText: forkPrompt, + forkAssistantText: findCompletedAgentMessageText({ + transcript: rawTranscript, + threadId: forkNativeThreadId, + turnId: forkRepeatNativeTurnId, + }), + }); + const providerMessageText = [ + "Context handoff (merge_back / fork_delta_summary):", + expectedSummary, + "", + "User message:", + mergeBackPrompt, + ].join("\n"); + const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( + transcriptWithMergeBackContinuation({ + transcript: rawTranscript, + providerMessageText, + projectedUserText: mergeBackPrompt, + assistantText: mergeBackAssistantText, + }), + ); + const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) => + Effect.service(FileSystem.FileSystem).pipe( + Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), + Effect.orDie, + ), + ); + + const result = yield* runOrchestratorV2ProviderReplayScenario( + { + name: "thread_fork_native_prior_turn_merge_back/codex", + transcript, + commands: materialized.commands, + steps: [ + { type: "dispatch", command: materialized.commands[0]!, await: true }, + { type: "advance_clock", duration: "1 millis" }, + { type: "dispatch", command: materialized.commands[1]!, await: true }, + { type: "await_thread_idle", threadId: materialized.sourceThreadId }, + { type: "dispatch", command: materialized.commands[2]!, await: true }, + { type: "await_thread_idle", threadId: materialized.sourceThreadId }, + { type: "dispatch", command: materialized.commands[3]!, await: true }, + { type: "dispatch", command: materialized.commands[4]!, await: true }, + { type: "await_thread_idle", threadId: materialized.targetThreadId }, + { type: "dispatch", command: materialized.commands[5]!, await: true }, + { type: "dispatch", command: materialized.commands[6]!, await: true }, + { type: "dispatch", command: materialized.commands[7]!, await: true }, + { type: "await_thread_idle", threadId: materialized.sourceThreadId }, + ], + projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId], + runtimePolicyOverride: { cwd, ...CODEX_READ_ONLY_NEVER_POLICY }, + }, + CodexOrchestratorReplayHarness, + ).pipe(provideDeterministicTestRuntime); + + const sourceProjection = result.projections.get(materialized.sourceThreadId); + const forkProjection = result.projections.get(materialized.targetThreadId); + assert.isDefined(sourceProjection); + assert.isDefined(forkProjection); + + assert.equal( + sourceProjection.providerThreads[0]?.nativeThreadRef?.nativeId, + sourceNativeThreadId, + "merge-back should continue the original source provider thread", + ); + assert.lengthOf(sourceProjection.runs, 3); + assert.equal( + sourceProjection.runs[2]?.contextHandoffId, + sourceProjection.contextHandoffs[0]?.id, + ); + assert.lengthOf(sourceProjection.contextHandoffs, 1); + const handoff = sourceProjection.contextHandoffs[0]!; + assert.equal(handoff.strategy, "fork_delta_summary"); + assert.equal(handoff.status, "ready"); + assert.equal(handoff.threadId, materialized.sourceThreadId); + assert.equal(handoff.targetRunId, sourceProjection.runs[2]?.id); + assert.deepEqual(handoff.coveredRunOrdinals, { from: 1, to: 1 }); + assert.include(handoff.summaryText, "Merge-back context from forked conversation."); + assert.include(handoff.summaryText, "Repeat the user-visible conversation"); + assert.notInclude( + handoff.summaryText, + "fork boundary beta", + "merge-back context should summarize only fork-local delta after the source point", + ); + assert.equal(handoff.summaryText, expectedSummary); + + const mergeBackTransfers = sourceProjection.contextTransfers.filter( + (transfer) => transfer.type === "merge_back", + ); + assert.lengthOf(mergeBackTransfers, 2); + const supersededTransfer = mergeBackTransfers.find( + (transfer) => transfer.status === "superseded", + ); + const mergeBackTransfer = mergeBackTransfers.find( + (transfer) => transfer.status === "consumed", + ); + assert.isDefined(supersededTransfer); + assert.isDefined(mergeBackTransfer); + assert.include( + supersededTransfer.error ?? "", + mergeBackTransfer.id, + "newer merge-back preparation should supersede the previous pending transfer", + ); + assert.equal(mergeBackTransfer.sourceThreadId, materialized.targetThreadId); + assert.equal(mergeBackTransfer.targetThreadId, materialized.sourceThreadId); + assert.equal(mergeBackTransfer.sourcePoint.runId, materialized.forkRunId); + assert.equal(mergeBackTransfer.basePoint?.runId, materialized.firstRunId); + assert.equal(mergeBackTransfer.status, "consumed"); + assert.equal(mergeBackTransfer.targetRunId, sourceProjection.runs[2]?.id); + assert.equal(mergeBackTransfer.resolution?.strategy, "fork_delta_context"); + assert.equal( + mergeBackTransfer.resolution?.strategy === "fork_delta_context" + ? mergeBackTransfer.resolution.contextHandoffId + : null, + handoff.id, + ); + + const mergeBackRunItems = sourceProjection.turnItems.filter( + (item) => item.runId === sourceProjection.runs[2]?.id, + ); + assert.deepEqual( + mergeBackRunItems.map((item) => item.type), + ["handoff", "user_message", "assistant_message", "checkpoint"], + ); + const handoffItem = mergeBackRunItems[0]; + assert.equal(handoffItem?.type, "handoff"); + assert.equal( + handoffItem?.type === "handoff" ? handoffItem.contextHandoffId : null, + handoff.id, + ); + assert.equal(handoffItem?.ordinal, 299); + const mergeUserItem = mergeBackRunItems.find((item) => item.type === "user_message"); + assert.equal( + mergeUserItem?.type === "user_message" ? mergeUserItem.text : null, + mergeBackPrompt, + ); + assert.notInclude( + sourceProjection.turnItems + .filter((item) => item.type === "user_message") + .map((item) => item.text) + .join("\n"), + "Context handoff", + "context handoff text should be provider input only, not projected user-visible message text", + ); + assert.include( + sourceProjection.turnItems + .filter((item) => item.type === "assistant_message") + .map((item) => item.text) + .join("\n"), + mergeBackAssistantText, + ); + + const visibleTypes = sourceProjection.visibleTurnItems.map((row) => row.item.type); + assert.includeMembers(visibleTypes, ["handoff", "user_message", "assistant_message"]); + const sourceShell = result.shellSnapshot.threads.find( + (thread) => thread.id === materialized.sourceThreadId, + ); + assert.isDefined(sourceShell); + assert.equal(sourceShell.visibleItemCount, sourceProjection.visibleTurnItems.length); + + assert.include( + forkProjection.turnItems + .filter((item) => item.type === "user_message") + .map((item) => item.text) + .join("\n"), + forkPrompt, + "merge-back should not remove fork-local history", + ); + assert.equal(forkProjection.contextTransfers[0]?.resolution?.strategy, "native_fork"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_output.ts index 91491ee779..1832afce8e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/codex_output.ts @@ -9,7 +9,9 @@ import { assertRuntimeRequestKinds, assertSemanticProjectionIntegrity, assertTurnItemTypes, + assertUserMessageInputIntents, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, TOOL_CALL_WRITE_PROMPT, } from "../shared.ts"; @@ -22,6 +24,7 @@ export function assertMessageSteeringOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertTurnItemTypes(projection, [ "user_message", "command_execution", @@ -35,6 +38,7 @@ export function assertMessageSteeringOutput( TOOL_CALL_WRITE_PROMPT, "Actually, respond with exactly: steering fixture observed", ]); + assertUserMessageInputIntents(projection, ["turn_start", "steer"]); assert.equal(projection.runs.length, 1, "steering must attach to the active run"); assert.equal( projection.providerTurns.length, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_output.ts index c9c3c0cbc4..44e32fc2fc 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/codex_output.ts @@ -10,6 +10,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, } from "../shared.ts"; @@ -26,6 +27,7 @@ export function assertMultiTurnOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertRunOrdinals(projection, [1, 2]); assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]); assertTurnItemTypes(projection, ["user_message", "assistant_message"]); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts index d9ff9102fb..3f6e1a5313 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/plan_questions/codex_output.ts @@ -13,6 +13,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, PLAN_QUESTIONS_PROMPT, projectionFor, } from "../shared.ts"; @@ -25,6 +26,7 @@ export function assertPlanQuestionsOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertRunOrdinals(projection, [1]); assertExecutionNodeKinds(projection, ["root_turn", "user_input_request", "assistant_message"]); assertRuntimeRequestCounts(projection, { total: 1, resolved: 1 }); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_output.ts index 49531b0ffb..935ebf841d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_output.ts @@ -9,6 +9,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, PROPOSED_PLAN_PROMPT, } from "../shared.ts"; @@ -21,6 +22,7 @@ export function assertProposedPlanOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertRunOrdinals(projection, [1]); assertExecutionNodeKinds(projection, ["root_turn", "plan"]); assertTurnItemTypes(projection, ["user_message", "proposed_plan"]); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_output.ts index e21e4ff121..0ce251c069 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/queued_turn/codex_output.ts @@ -9,7 +9,9 @@ import { assertRunOrdinals, assertSemanticProjectionIntegrity, assertTurnItemTypes, + assertUserMessageInputIntents, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, } from "../shared.ts"; @@ -26,6 +28,7 @@ export function assertQueuedTurnOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertRunOrdinals(projection, [1, 2]); assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]); assertTurnItemTypes(projection, ["user_message", "assistant_message"]); @@ -33,6 +36,7 @@ export function assertQueuedTurnOutput( "Respond with exactly: first fixture turn complete", "Respond with exactly: second fixture turn complete", ]); + assertUserMessageInputIntents(projection, ["turn_start", "queued_turn"]); assert.equal(projection.turnItems.filter((item) => item.type === "user_message").length, 2); assertAssistantTextIncludes(projection, "first fixture turn complete"); assertAssistantTextIncludes(projection, "second fixture turn complete"); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index dbc5170f43..4d4f814485 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -11,6 +11,7 @@ import { type OrchestrationV2RunStatus, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, + type OrchestrationV2UserMessageInputIntent, type ProviderKind, type ProviderInteractionMode, type ProviderReplayTranscript, @@ -532,6 +533,26 @@ export function assertTurnItemsReferenceProjection(projection: OrchestrationV2Th } } +export function assertVisibleTurnItemsMirrorLocalTurnItems( + projection: OrchestrationV2ThreadProjection, +) { + assert.lengthOf( + projection.visibleTurnItems, + projection.turnItems.length, + "non-fork visible turn items must mirror local canonical turn items", + ); + + for (const [index, item] of projection.turnItems.entries()) { + const visibleItem = projection.visibleTurnItems[index]; + assert.isDefined(visibleItem, `missing visible turn item at position ${index}`); + assert.equal(visibleItem.position, index); + assert.equal(visibleItem.visibility, "local"); + assert.equal(visibleItem.sourceThreadId, item.threadId); + assert.equal(visibleItem.sourceItemId, item.id); + assert.deepEqual(visibleItem.item, item); + } +} + export function assertMessagesReferenceProjection(projection: OrchestrationV2ThreadProjection) { for (const message of projection.messages) { if (message.runId !== null) { @@ -695,3 +716,15 @@ export function assertUserMessagesInclude( ); } } + +export function assertUserMessageInputIntents( + projection: OrchestrationV2ThreadProjection, + expectedIntents: ReadonlyArray, +) { + assert.deepEqual( + projection.turnItems + .filter((item) => item.type === "user_message") + .map((item) => item.inputIntent), + expectedIntents, + ); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_output.ts index f13dec5c64..b8a30ba9f3 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/codex_output.ts @@ -10,6 +10,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, SIMPLE_PROMPT, } from "../shared.ts"; @@ -22,6 +23,7 @@ export function assertSimpleOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertRunOrdinals(projection, [1]); assertExecutionNodeKinds(projection, ["root_turn", "assistant_message"]); assertConversationMessageRoles(projection, ["user", "assistant"]); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_output.ts index 7597d43135..ce091e178f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_rollback/codex_output.ts @@ -8,6 +8,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, } from "../shared.ts"; @@ -24,6 +25,7 @@ export function assertThreadRollbackOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertRunOrdinals(projection, [1, 2, 3]); assertTurnItemTypes(projection, ["user_message", "assistant_message", "checkpoint"]); assertUserMessagesInclude(projection, [ diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts index b3e95153a7..3b1ff8379f 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts @@ -10,6 +10,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, TODO_LIST_PROMPT, } from "../shared.ts"; @@ -22,6 +23,7 @@ export function assertTodoListOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertRunOrdinals(projection, [1]); assertExecutionNodeKinds(projection, ["root_turn", "todo_list", "tool_call"]); assertTurnItemTypes(projection, ["user_message", "todo_list", "command_execution"]); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_output.ts index 166eb621f4..74948d6931 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only_on_request/codex_output.ts @@ -9,6 +9,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, TOOL_CALL_WRITE_PROMPT, } from "../shared.ts"; @@ -21,6 +22,7 @@ export function assertToolCallReadOnlyOnRequestOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertTurnItemTypes(projection, [ "user_message", "command_execution", diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.ts index bb30519e6b..7217f4005c 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.ts @@ -9,6 +9,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, TOOL_CALL_WRITE_PROMPT, } from "../shared.ts"; @@ -21,6 +22,7 @@ export function assertToolCallRestrictedGranularOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertTurnItemTypes(projection, [ "user_message", "command_execution", diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_output.ts index 1fda866cfe..d6bdc414c7 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_workspace_never/codex_output.ts @@ -8,6 +8,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, TOOL_CALL_WRITE_PROMPT, } from "../shared.ts"; @@ -20,6 +21,7 @@ export function assertToolCallWorkspaceNeverOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertTurnItemTypes(projection, ["user_message", "command_execution", "assistant_message"]); assertUserMessagesInclude(projection, [TOOL_CALL_WRITE_PROMPT]); assertRuntimeRequestCounts(projection, { total: 0 }); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_output.ts index 76ef55470f..a446c5abbb 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/codex_output.ts @@ -7,6 +7,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, TURN_INTERRUPT_PROMPT, } from "../shared.ts"; @@ -19,6 +20,7 @@ export function assertTurnInterruptOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertTurnItemTypes(projection, [ "user_message", "run_interrupt_request", diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_output.ts index ee07dc9256..eeae90be44 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/web_search/codex_output.ts @@ -11,6 +11,7 @@ import { assertSemanticProjectionIntegrity, assertTurnItemTypes, assertUserMessagesInclude, + assertVisibleTurnItemsMirrorLocalTurnItems, projectionFor, WEB_SEARCH_PROMPT, } from "../shared.ts"; @@ -25,6 +26,7 @@ export function assertWebSearchOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); + assertVisibleTurnItemsMirrorLocalTurnItems(projection); assertExecutionNodeKinds(projection, ["root_turn", "tool_call", "assistant_message"]); assertConversationMessageRoles(projection, ["user", "assistant"]); assertTurnItemTypes(projection, ["user_message", "web_search", "assistant_message"]); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 66fdbe7b3f..2840b6b956 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -21,6 +21,7 @@ import { TerminalNotRunningError, type OrchestrationCommand, type OrchestrationEvent, + type OrchestrationV2ShellStreamItem, type OrchestrationV2ThreadStreamItem, ORCHESTRATION_WS_METHODS, type ProviderKind, @@ -5953,6 +5954,22 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](createThreadCommand); assert.equal(duplicateCreateResult.sequence, createResult.sequence); + const shellItems = yield* Queue.unbounded(); + const shellFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}).pipe( + Stream.runForEach((item) => Queue.offer(shellItems, item)), + Effect.forkDetach, + ); + const shellSnapshot = yield* takeWsItem(shellItems, "orchestration V2 shell snapshot"); + assert.equal(shellSnapshot.kind, "snapshot"); + if (shellSnapshot.kind === "snapshot") { + const thread = shellSnapshot.snapshot.threads.find( + (candidate) => candidate.id === createThreadCommand.threadId, + ); + assert.isDefined(thread); + assert.equal(thread.itemCount, 0); + assert.equal(thread.status, "idle"); + } + const streamItems = yield* Queue.unbounded(); const streamFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({ threadId: createThreadCommand.threadId, @@ -5975,6 +5992,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](dispatchMessageCommand); const items: Array = []; + const shellUpdates: Array = []; const turnItemTypes = new Set(); for (let index = 0; index < 20; index += 1) { const item = yield* takeWsItem(streamItems, `orchestration V2 event ${index + 1}`); @@ -5989,13 +6007,28 @@ it.layer(NodeServices.layer)("server router seam", (it) => { break; } } + for (let index = 0; index < 20; index += 1) { + const item = yield* takeWsItem( + shellItems, + `orchestration V2 shell update ${index + 1}`, + ); + shellUpdates.push(item); + if ( + item.kind === "thread.updated" && + item.thread.id === createThreadCommand.threadId && + item.thread.visibleItemCount >= 2 + ) { + break; + } + } const projection = yield* client[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]({ threadId: createThreadCommand.threadId, }); yield* Fiber.interrupt(streamFiber); + yield* Fiber.interrupt(shellFiber); - return { items, projection }; + return { items, shellUpdates, projection }; }), ), ); @@ -6013,6 +6046,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => { received.projection.turnItems.map((item) => item.type), ["user_message", "assistant_message"], ); + assert.isTrue( + received.shellUpdates.some( + (item) => + item.kind === "thread.updated" && + item.thread.visibleItemCount === received.projection.visibleTurnItems.length, + ), + ); assert.equal( received.projection.turnItems.find((item) => item.type === "assistant_message")?.text, "fixture simple ok", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 784d84f258..61f3223e80 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -32,6 +32,7 @@ import { OrchestrationGetTurnDiffError, ORCHESTRATION_V2_WS_METHODS, OrchestrationV2DispatchCommandError, + OrchestrationV2GetShellSnapshotError, OrchestrationV2GetThreadProjectionError, ORCHESTRATION_WS_METHODS, type ProjectId, @@ -54,8 +55,7 @@ import { RpcClientId, EnvironmentAuthorizationError, ThreadId, - type TerminalAttachStreamEvent, - type TerminalError, + type OrchestrationV2ThreadShell, type TerminalEvent, type TerminalMetadataStreamEvent, WS_METHODS, @@ -975,6 +975,58 @@ const makeWsRpcLayer = ( }, ); + const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")( + function* () { + const snapshot = yield* orchestrationV2.getShellSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed to load orchestration V2 shell snapshot", + cause, + }), + ), + ); + + const liveStream = orchestrationV2.streamDomainEvents.pipe( + Stream.mapEffect((event) => + orchestrationV2.getShellSnapshot().pipe( + Effect.map( + (nextSnapshot) => + nextSnapshot.threads.find((thread) => thread.id === event.threadId) ?? null, + ), + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: `Failed while streaming orchestration V2 shell thread ${event.threadId}`, + cause, + }), + ), + ), + ), + Stream.filter((thread): thread is OrchestrationV2ThreadShell => thread !== null), + Stream.map((thread) => ({ + kind: "thread.updated" as const, + thread, + })), + Stream.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed while streaming orchestration V2 shell", + cause, + }), + ), + ); + + return Stream.concat( + Stream.make({ + kind: "snapshot" as const, + snapshot, + }), + liveStream, + ); + }, + ); + return WsRpcGroup.of({ [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => observeRpcEffect( @@ -1350,8 +1402,10 @@ const makeWsRpcLayer = ( "orchestration_v2.command_id": command.commandId, "orchestration_v2.command_type": command.type, "orchestration_v2.thread_id": - command.type === "thread.fork" ? command.targetThreadId : command.threadId, - ...(command.type === "thread.fork" + command.type === "thread.fork" || command.type === "thread.merge_back" + ? command.targetThreadId + : command.threadId, + ...(command.type === "thread.fork" || command.type === "thread.merge_back" ? { "orchestration_v2.source_thread_id": command.sourceThreadId } : {}), }, @@ -1374,6 +1428,14 @@ const makeWsRpcLayer = ( "orchestration_v2.thread_id": input.threadId, }, ), + [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (_input) => + observeRpcStreamEffect( + ORCHESTRATION_V2_WS_METHODS.subscribeShell, + subscribeOrchestrationV2Shell(), + { + "rpc.aggregate": "orchestrationV2", + }, + ), [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input) => observeRpcStreamEffect( ORCHESTRATION_V2_WS_METHODS.subscribeThread, diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index c33e2fbc01..973171fc11 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -222,6 +222,8 @@ function createMockEnvironmentApi(input: { getThreadProjection: (() => { throw new Error("Not implemented in browser test."); }) as EnvironmentApi["orchestrationV2"]["getThreadProjection"], + subscribeShell: (() => () => + undefined) as EnvironmentApi["orchestrationV2"]["subscribeShell"], subscribeThread: (() => () => undefined) as EnvironmentApi["orchestrationV2"]["subscribeThread"], }, diff --git a/apps/web/src/environmentApi.ts b/apps/web/src/environmentApi.ts index c4c20c2e81..8f48398060 100644 --- a/apps/web/src/environmentApi.ts +++ b/apps/web/src/environmentApi.ts @@ -48,6 +48,8 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi { orchestrationV2: { dispatchCommand: rpcClient.orchestrationV2.dispatchCommand, getThreadProjection: rpcClient.orchestrationV2.getThreadProjection, + subscribeShell: (callback, options) => + rpcClient.orchestrationV2.subscribeShell(callback, options), subscribeThread: (input, callback, options) => rpcClient.orchestrationV2.subscribeThread(input, callback, options), }, diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx index b874d87b9f..4d01f4763a 100644 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ b/apps/web/src/routes/debug.orchestration-v2.tsx @@ -8,6 +8,7 @@ import type { OrchestrationV2RunStatus, OrchestrationV2Checkpoint, OrchestrationV2ThreadProjection, + OrchestrationV2ThreadShell, OrchestrationV2ThreadStreamItem, OrchestrationV2TurnItem, OrchestrationV2TurnItemStatus, @@ -22,6 +23,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { getPrimaryEnvironmentConnection } from "../environments/runtime"; import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils"; +import { GitMergeIcon } from "lucide-react"; export const Route = createFileRoute("/debug/orchestration-v2")({ component: OrchestrationV2DebugRoute, @@ -64,6 +66,13 @@ function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null; } +function formatErrorMessage(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; + } + return String(error); +} + function formatLabel(value: string): string { return value .split(/[._-]+/g) @@ -309,6 +318,30 @@ function upsertProjectionEntity( return next; } +function upsertVisibleTurnItem( + projection: OrchestrationV2ThreadProjection, + item: OrchestrationV2TurnItem, +): OrchestrationV2ThreadProjection["visibleTurnItems"] { + const existingIndex = projection.visibleTurnItems.findIndex( + (row) => row.sourceItemId === item.id, + ); + if (existingIndex === -1) { + return [ + ...projection.visibleTurnItems, + { + position: projection.visibleTurnItems.length, + visibility: "local", + sourceThreadId: item.threadId, + sourceItemId: item.id, + item, + }, + ]; + } + return projection.visibleTurnItems.map((row, index) => + index === existingIndex ? { ...row, item } : row, + ); +} + function applyStreamEventToProjection( projection: OrchestrationV2ThreadProjection | null, event: OrchestrationV2DomainEvent, @@ -327,12 +360,21 @@ function applyStreamEventToProjection( return { ...base, thread: event.payload }; case "run.created": case "run.updated": - return { ...base, runs: upsertProjectionEntity(base.runs, event.payload) }; + return { + ...base, + runs: upsertProjectionEntity(base.runs, event.payload), + }; case "run-attempt.created": case "run-attempt.updated": - return { ...base, attempts: upsertProjectionEntity(base.attempts, event.payload) }; + return { + ...base, + attempts: upsertProjectionEntity(base.attempts, event.payload), + }; case "node.updated": - return { ...base, nodes: upsertProjectionEntity(base.nodes, event.payload) }; + return { + ...base, + nodes: upsertProjectionEntity(base.nodes, event.payload), + }; case "provider-session.updated": return { ...base, @@ -354,18 +396,31 @@ function applyStreamEventToProjection( runtimeRequests: upsertProjectionEntity(base.runtimeRequests, event.payload), }; case "message.updated": - return { ...base, messages: upsertProjectionEntity(base.messages, event.payload) }; + return { + ...base, + messages: upsertProjectionEntity(base.messages, event.payload), + }; case "plan.updated": - return { ...base, plans: upsertProjectionEntity(base.plans, event.payload) }; + return { + ...base, + plans: upsertProjectionEntity(base.plans, event.payload), + }; case "turn-item.updated": - return { ...base, turnItems: upsertProjectionEntity(base.turnItems, event.payload) }; + return { + ...base, + turnItems: upsertProjectionEntity(base.turnItems, event.payload), + visibleTurnItems: upsertVisibleTurnItem(base, event.payload), + }; case "checkpoint-scope.created": return { ...base, checkpointScopes: upsertProjectionEntity(base.checkpointScopes, event.payload), }; case "checkpoint.captured": - return { ...base, checkpoints: upsertProjectionEntity(base.checkpoints, event.payload) }; + return { + ...base, + checkpoints: upsertProjectionEntity(base.checkpoints, event.payload), + }; case "context-handoff.updated": return { ...base, @@ -520,15 +575,17 @@ interface QueuedRunRow { readonly messageText: string; } -interface DebugThreadOption { - readonly threadId: ThreadId; - readonly label: string; - readonly relationship: "source" | "fork"; +interface MergeBackCandidate { + readonly sourceThreadId: ThreadId; + readonly targetThreadId: ThreadId; + readonly latestCompletedRun: OrchestrationV2Run | null; } +type PendingMergeBackTransfer = OrchestrationV2ThreadProjection["contextTransfers"][number]; + interface DebugThreadTreeNode { readonly threadId: ThreadId; - readonly projection: OrchestrationV2ThreadProjection | null; + readonly thread: OrchestrationV2ThreadShell; readonly children: ReadonlyArray; } @@ -537,6 +594,26 @@ function buildItemTimeline(input: { readonly projectionsByThread: ReadonlyMap; readonly logEntries: ReadonlyArray; }): ReadonlyArray { + if (input.projection !== null && input.projection.visibleTurnItems.length > 0) { + return input.projection.visibleTurnItems.map((row): ItemTimelineRow => { + const item = row.item; + if (item.type === "fork" && row.visibility === "synthetic") { + return { + kind: "fork-marker", + sourceThreadId: row.sourceThreadId, + targetThreadId: item.targetThreadId, + entry: itemTimelineEntry(item, `visible:${input.projection?.thread.id}:${row.position}`), + }; + } + return { + kind: "item", + item, + inheritedFromThreadId: row.visibility === "inherited" ? row.sourceThreadId : undefined, + entry: itemTimelineEntry(item, `visible:${input.projection?.thread.id}:${row.position}`), + }; + }); + } + const items = new Map< string, { @@ -660,40 +737,27 @@ function itemTimelineEntry( }; } -function forkSourceThreadId(projection: OrchestrationV2ThreadProjection | null): ThreadId | null { - const forkedFrom = projection?.thread.forkedFrom; +function forkSourceThreadId(thread: OrchestrationV2ThreadShell): ThreadId | null { + const forkedFrom = thread.forkedFrom; if (forkedFrom?.type === "run") return forkedFrom.threadId; - return projection?.thread.lineage.parentThreadId ?? null; + return thread.lineage.parentThreadId ?? null; } -function projectionCreatedMs(projection: OrchestrationV2ThreadProjection | null): number { - const iso = formatTimestamp(projection?.thread.createdAt); +function threadShellCreatedMs(thread: OrchestrationV2ThreadShell): number { + const iso = formatTimestamp(thread.createdAt); if (iso === undefined) return 0; const parsed = new Date(iso).getTime(); return Number.isNaN(parsed) ? 0 : parsed; } function buildThreadTree(input: { - readonly projections: ReadonlyMap; - readonly debugThreads: ReadonlyArray; + readonly threads: ReadonlyMap; }): ReadonlyArray { - const entries = new Map(); - for (const thread of input.debugThreads) { - entries.set(thread.threadId, input.projections.get(thread.threadId) ?? null); - } - for (const [threadId, projection] of input.projections) { - entries.set(threadId, projection); - const parentThreadId = forkSourceThreadId(projection); - if (parentThreadId !== null && !entries.has(parentThreadId)) { - entries.set(parentThreadId, input.projections.get(parentThreadId) ?? null); - } - } - const childIds = new Map>(); const rootIds: Array = []; - for (const [threadId, projection] of entries) { - const parentThreadId = forkSourceThreadId(projection); - if (parentThreadId !== null && entries.has(parentThreadId)) { + for (const [threadId, thread] of input.threads) { + const parentThreadId = forkSourceThreadId(thread); + if (parentThreadId !== null && input.threads.has(parentThreadId)) { const children = childIds.get(parentThreadId) ?? []; children.push(threadId); childIds.set(parentThreadId, children); @@ -704,19 +768,24 @@ function buildThreadTree(input: { const sortThreadIds = (threadIds: Array) => threadIds.toSorted((left, right) => { - const leftProjection = entries.get(left) ?? null; - const rightProjection = entries.get(right) ?? null; + const leftThread = input.threads.get(left); + const rightThread = input.threads.get(right); return ( - projectionCreatedMs(leftProjection) - projectionCreatedMs(rightProjection) || + (leftThread === undefined ? 0 : threadShellCreatedMs(leftThread)) - + (rightThread === undefined ? 0 : threadShellCreatedMs(rightThread)) || String(left).localeCompare(String(right)) ); }); const buildNode = (threadId: ThreadId): DebugThreadTreeNode => { + const thread = input.threads.get(threadId); + if (thread === undefined) { + throw new Error(`Missing orchestration V2 shell thread ${threadId}`); + } const children = sortThreadIds(childIds.get(threadId) ?? []).map(buildNode); return { threadId, - projection: entries.get(threadId) ?? null, + thread, children, }; }; @@ -1053,13 +1122,13 @@ function ThreadTreeRow(props: { readonly activeThreadId: ThreadId | null; readonly onOpenThread: (threadId: ThreadId) => void; }) { - const projection = props.node.projection; + const thread = props.node.thread; const active = props.node.threadId === props.activeThreadId; - const relationship = projection?.thread.lineage.relationshipToParent ?? "source"; - const provider = projection?.thread.modelSelection.provider ?? "unknown"; - const model = projection?.thread.modelSelection.model ?? "unknown"; - const itemCount = projection?.turnItems.length ?? 0; - const createdAt = formatTimestamp(projection?.thread.createdAt); + const relationship = thread.lineage.relationshipToParent ?? "source"; + const provider = thread.modelSelection.provider; + const model = thread.modelSelection.model; + const itemCount = thread.visibleItemCount; + const createdAt = formatTimestamp(thread.createdAt); return (
  • - - {projection?.thread.title ?? "Unknown thread"} - + {thread.title} void; -}) { - const latestCompletedRun = latestCompletedRunInProjection(props.projection); - const canFork = latestCompletedRun !== null; - if (props.projection === null) { - return null; - } - - return ( -
    -
    -
    -

    Fork

    -

    - {canFork - ? `Latest completed run: ${compactId(latestCompletedRun.id) ?? latestCompletedRun.id}` - : "Run once, then fork from the latest completed run."} -

    -
    - -
    -
    - ); -} - function QueueControls(props: { readonly rows: ReadonlyArray; readonly activeTurn: ActiveTurn | null; @@ -1251,6 +1278,57 @@ function QueueControls(props: { ); } +function MergeBackControls(props: { + readonly candidate: MergeBackCandidate | null; + readonly disabled: boolean; + readonly onMergeBack: () => void; +}) { + if (props.candidate === null) { + return null; + } + + const canMerge = props.candidate.latestCompletedRun !== null; + if (!canMerge) return null; + return ( + + ); +} + +function PendingMergeBackNotice(props: { readonly transfer: PendingMergeBackTransfer | null }) { + if (props.transfer === null) { + return null; + } + + return ( +
    + +

    + Merge back pending from{" "} + + {compactId(props.transfer.sourceThreadId) ?? props.transfer.sourceThreadId} + + . Your next message will include that fork context. +

    +
    + ); +} + function QueueActionButton(props: { readonly label: string; readonly disabled: boolean; @@ -1321,8 +1399,11 @@ function OrchestrationV2DebugRoute() { const [prompt, setPrompt] = useState(DEFAULT_PROMPT); const [threadId, setThreadId] = useState(null); const [projection, setProjection] = useState(null); + const [projectionError, setProjectionError] = useState(null); const [logEntries, setLogEntries] = useState>([]); - const [debugThreads, setDebugThreads] = useState>([]); + const [shellThreadsById, setShellThreadsById] = useState< + ReadonlyMap + >(() => new Map()); const [projectionByThread, setProjectionByThread] = useState< ReadonlyMap >(() => new Map()); @@ -1330,6 +1411,7 @@ function OrchestrationV2DebugRoute() { const [visiblePanels, setVisiblePanels] = useState>(DEFAULT_VISIBLE_PANELS); const unsubscribeRef = useRef<(() => void) | null>(null); + const shellUnsubscribeRef = useRef<(() => void) | null>(null); const hiddenPanels = useMemo( () => ALL_PANEL_KEYS.filter((key) => !visiblePanels.includes(key)), @@ -1367,23 +1449,21 @@ function OrchestrationV2DebugRoute() { [logEntries, projection, projectionByThread], ); const threadTree = useMemo( - () => buildThreadTree({ projections: projectionByThread, debugThreads }), - [debugThreads, projectionByThread], + () => buildThreadTree({ threads: shellThreadsById }), + [shellThreadsById], ); const activeTurn = useMemo(() => deriveActiveTurn(projection), [projection]); const queuedRuns = useMemo(() => buildQueuedRunRows(projection), [projection]); + const mergeBackCandidate = useMemo(() => deriveMergeBackCandidate(projection), [projection]); + const pendingMergeBackTransfer = useMemo( + () => derivePendingMergeBackTransfer(projection), + [projection], + ); const appendLog = useCallback((entry: LogEntry) => { setLogEntries((entries) => [...entries, entry]); }, []); - const rememberDebugThread = useCallback((option: DebugThreadOption) => { - setDebugThreads((threads) => { - const withoutExisting = threads.filter((thread) => thread.threadId !== option.threadId); - return [...withoutExisting, option]; - }); - }, []); - const cacheProjection = useCallback((nextProjection: OrchestrationV2ThreadProjection) => { setProjectionByThread((current) => { const next = new Map(current); @@ -1399,14 +1479,45 @@ function OrchestrationV2DebugRoute() { useEffect(() => clearSubscription, [clearSubscription]); + useEffect(() => { + shellUnsubscribeRef.current = api.subscribeShell((item) => { + if (item.kind === "snapshot") { + setShellThreadsById(new Map(item.snapshot.threads.map((thread) => [thread.id, thread]))); + return; + } + + setShellThreadsById((current) => { + const next = new Map(current); + next.set(item.thread.id, item.thread); + return next; + }); + }); + + return () => { + shellUnsubscribeRef.current?.(); + shellUnsubscribeRef.current = null; + }; + }, [api]); + const refreshProjection = useCallback( async (nextThreadId: ThreadId) => { - const nextProjection = await api.getThreadProjection({ threadId: nextThreadId }); - setProjection(nextProjection); - cacheProjection(nextProjection); - return nextProjection; + try { + const nextProjection = await api.getThreadProjection({ + threadId: nextThreadId, + }); + setProjectionError(null); + setProjection(nextProjection); + cacheProjection(nextProjection); + return nextProjection; + } catch (error) { + const message = formatErrorMessage(error); + setProjection(null); + setProjectionError(message); + appendLog({ type: "error", message }); + return null; + } }, - [api, cacheProjection], + [api, appendLog, cacheProjection], ); const subscribeToThread = useCallback( @@ -1418,6 +1529,7 @@ function OrchestrationV2DebugRoute() { (item) => { appendLog({ type: "stream", value: item }); if (item.kind === "snapshot") { + setProjectionError(null); setProjection(item.projection); cacheProjection(item.projection); return; @@ -1426,6 +1538,7 @@ function OrchestrationV2DebugRoute() { setProjection((current) => { const nextProjection = applyStreamEventToProjection(current, item.event); if (nextProjection !== null) { + setProjectionError(null); cacheProjection(nextProjection); } return nextProjection; @@ -1440,6 +1553,11 @@ function OrchestrationV2DebugRoute() { value: { threadId: nextThreadId }, }); }, + onError: (message) => { + setProjection(null); + setProjectionError(message); + appendLog({ type: "error", message }); + }, }, ); }, @@ -1450,15 +1568,9 @@ function OrchestrationV2DebugRoute() { async (nextThreadId: ThreadId) => { setThreadId(nextThreadId); subscribeToThread(nextThreadId); - const openedProjection = await refreshProjection(nextThreadId); - rememberDebugThread({ - threadId: nextThreadId, - label: openedProjection.thread.lineage.relationshipToParent === "fork" ? "Fork" : "Source", - relationship: - openedProjection.thread.lineage.relationshipToParent === "fork" ? "fork" : "source", - }); + await refreshProjection(nextThreadId); }, - [refreshProjection, rememberDebugThread, subscribeToThread], + [refreshProjection, subscribeToThread], ); const createDebugThread = useCallback(async () => { @@ -1477,16 +1589,11 @@ function OrchestrationV2DebugRoute() { }); setThreadId(nextThreadId); - rememberDebugThread({ - threadId: nextThreadId, - label: "Source", - relationship: "source", - }); subscribeToThread(nextThreadId); appendLog({ type: "command", label: "thread.create", value: result }); await refreshProjection(nextThreadId); return nextThreadId; - }, [api, appendLog, refreshProjection, rememberDebugThread, subscribeToThread]); + }, [api, appendLog, refreshProjection, subscribeToThread]); const ensureThread = useCallback(async () => { if (threadId !== null) { @@ -1537,7 +1644,11 @@ function OrchestrationV2DebugRoute() { ? { type: "queue_after_active" } : { type: "start_immediately" }, }); - appendLog({ type: "command", label: "message.dispatch", value: result }); + appendLog({ + type: "command", + label: "message.dispatch", + value: result, + }); await refreshProjection(activeThreadId); } catch (error) { appendLog({ @@ -1563,7 +1674,11 @@ function OrchestrationV2DebugRoute() { queuedRunId, targetRunId: activeTurn.targetRunId, }); - appendLog({ type: "command", label: "queued-message.promote-to-steer", value: result }); + appendLog({ + type: "command", + label: "queued-message.promote-to-steer", + value: result, + }); await refreshProjection(threadId); } catch (error) { appendLog({ @@ -1611,7 +1726,11 @@ function OrchestrationV2DebugRoute() { runId, beforeRunId, }); - appendLog({ type: "command", label: "queued-run.reorder", value: result }); + appendLog({ + type: "command", + label: "queued-run.reorder", + value: result, + }); await refreshProjection(threadId); } catch (error) { appendLog({ @@ -1641,18 +1760,6 @@ function OrchestrationV2DebugRoute() { sourcePoint: { type: "run", runId: input.runId }, title: `${sourceProjection.thread.title} fork`, }); - rememberDebugThread({ - threadId: input.threadId, - label: - sourceProjection.thread.lineage.relationshipToParent === "fork" ? "Fork" : "Source", - relationship: - sourceProjection.thread.lineage.relationshipToParent === "fork" ? "fork" : "source", - }); - rememberDebugThread({ - threadId: targetThreadId, - label: "Fork", - relationship: "fork", - }); appendLog({ type: "command", label: "thread.fork", value: result }); await openThread(targetThreadId); } catch (error) { @@ -1664,19 +1771,37 @@ function OrchestrationV2DebugRoute() { setIsBusy(false); } }, - [api, appendLog, isBusy, openThread, projectionByThread, rememberDebugThread], + [api, appendLog, isBusy, openThread, projectionByThread], ); - const forkLatestStable = useCallback(async () => { - if (threadId === null || projection === null) return; - const latestCompletedRun = latestCompletedRunInProjection(projection); - if (latestCompletedRun === null) return; + const mergeBackToSource = useCallback(async () => { + if (mergeBackCandidate === null || mergeBackCandidate.latestCompletedRun === null || isBusy) { + return; + } - await forkFromRun({ - threadId, - runId: latestCompletedRun.id, - }); - }, [forkFromRun, projection, threadId]); + setIsBusy(true); + try { + const result = await api.dispatchCommand({ + type: "thread.merge_back", + commandId: newCommandId(), + sourceThreadId: mergeBackCandidate.sourceThreadId, + targetThreadId: mergeBackCandidate.targetThreadId, + sourcePoint: { + type: "run", + runId: mergeBackCandidate.latestCompletedRun.id, + }, + }); + appendLog({ type: "command", label: "thread.merge_back", value: result }); + await openThread(mergeBackCandidate.targetThreadId); + } catch (error) { + appendLog({ + type: "error", + message: error instanceof Error ? error.message : String(error), + }); + } finally { + setIsBusy(false); + } + }, [api, appendLog, isBusy, mergeBackCandidate, openThread]); const rollbackToCheckpoint = useCallback( async (input: { readonly checkpointId: CheckpointId; readonly scopeId: CheckpointScopeId }) => { @@ -1690,7 +1815,11 @@ function OrchestrationV2DebugRoute() { scopeId: input.scopeId, checkpointId: input.checkpointId, }); - appendLog({ type: "command", label: "checkpoint.rollback", value: result }); + appendLog({ + type: "command", + label: "checkpoint.rollback", + value: result, + }); await refreshProjection(threadId); } catch (error) { appendLog({ @@ -1708,8 +1837,8 @@ function OrchestrationV2DebugRoute() { clearSubscription(); setThreadId(null); setProjection(null); + setProjectionError(null); setLogEntries([]); - setDebugThreads([]); setProjectionByThread(new Map()); }, [clearSubscription]); @@ -1749,6 +1878,7 @@ function OrchestrationV2DebugRoute() { +