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
This commit is contained in:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:44:57 -04:00
1 parent 74f73e39ea
commit 7cfdb4e79e
36 files changed
+2921 -301

No files matched your search

@@ -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>()(
"ContextHandoffPrepareError",
@@ -32,9 +35,193 @@ export interface ContextHandoffServiceV2Shape {
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
readonly toProviderThreadId: ProviderThreadId;
}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
readonly prepareForkDelta: (input: {
readonly sourceThreadId: ThreadId;
readonly targetThreadId: ThreadId;
readonly targetRunId: RunId;
readonly transferId: OrchestrationV2ContextHandoff["transferId"];
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
readonly toProviderThreadId: ProviderThreadId;
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
readonly createdAt: DateTime.Utc;
}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
}
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<OrchestrationV2TurnItem>;
}): 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<ProviderThreadId>;
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<ProviderThreadId>;
readonly toProviderThreadId: ProviderThreadId;
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
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<ContextHandoffServiceV2, never, IdAllocatorV2> = Layer.effect(
ContextHandoffServiceV2,
makeContextHandoffService(),
);
+450 -19
View File
@@ -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<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
readonly getShellSnapshot: () => Effect.Effect<OrchestrationV2ShellSnapshot, OrchestratorV2Error>;
readonly getThreadEventSequence: (
threadId: ThreadId,
) => Effect.Effect<number, OrchestratorV2Error>;
@@ -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<OrchestrationV2ContextTransfer> {
return projection.contextTransfers.filter(
(transfer) =>
transfer.type === "merge_back" &&
transfer.targetThreadId === projection.thread.id &&
transfer.status === "pending",
);
}
function latestContextTransfer(
transfers: ReadonlyArray<OrchestrationV2ContextTransfer>,
): OrchestrationV2ContextTransfer | undefined {
return transfers.reduce<OrchestrationV2ContextTransfer | undefined>((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<OrchestrationV2TurnItem>,
): 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<OrchestrationV2Command, { readonly type: "thread.merge_back" }>,
events: Ref.Ref<Array<OrchestrationV2StoredEvent>>,
) {
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<OrchestratorV2> = 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({
@@ -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");
}),
);
});
@@ -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<void, ProjectionStoreV2Error>;
readonly getShellSnapshot: () => Effect.Effect<
OrchestrationV2ShellSnapshot,
ProjectionStoreV2Error
>;
readonly getThreadProjection: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error>;
@@ -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<OrchestrationV2TurnItem>,
): Array<OrchestrationV2ProjectedTurnItem> {
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<Omit<OrchestrationV2ProjectedTurnItem, "position">>,
): Array<OrchestrationV2ProjectedTurnItem> {
return rows.map((row, position) => ({ ...row, position }));
}
function makeForkMarkerTurnItem(input: {
readonly targetProjection: OrchestrationV2ThreadProjection;
readonly sourceThreadId: ThreadId;
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
}): 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<OrchestrationV2TurnItem["runId"]>;
}): Array<Omit<OrchestrationV2ProjectedTurnItem, "position">> {
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<OrchestrationV2ProjectedTurnItem> {
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<RunId, number>;
readonly itemCountByRunId: ReadonlyMap<RunId, number>;
};
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<ThreadId, ShellThreadState>;
readonly seenThreadIds?: ReadonlySet<ThreadId>;
}): 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<ThreadId>();
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<ProjectionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
ProjectionStoreV2,
Effect.gen(function* () {
@@ -1048,7 +1341,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
),
);
const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
const readCanonicalProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
Effect.gen(function* () {
const threadRows = yield* sql<PayloadRow>`
SELECT payload_json
@@ -1214,6 +1507,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
checkpoints,
contextHandoffs,
contextTransfers,
visibleTurnItems: localVisibleTurnItems(turnItems),
updatedAt: thread.updatedAt,
} satisfies OrchestrationV2ThreadProjection;
}).pipe(
@@ -1227,8 +1521,136 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
),
);
const readProjection = (
threadId: ThreadId,
seenThreadIds: ReadonlySet<ThreadId>,
): Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error> =>
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<ShellThreadRow>`
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<ShellRunRow>`
SELECT thread_id, run_id, ordinal
FROM orchestration_v2_projection_runs
`,
sql<ShellRunItemCountRow>`
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<ThreadId, Map<RunId, number>>();
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<RunId, number>();
existing.set(runId, row.ordinal);
runOrdinalsByThreadId.set(threadId, existing);
}
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
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<RunId, number>();
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<ProjectionStoreV2> = 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<ThreadId>,
): 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 });
}
@@ -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",
+48 -42
View File
@@ -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.
@@ -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,
@@ -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<ProviderReplayTranscript> {
@@ -2,6 +2,7 @@ import type {
OrchestrationV2Command,
OrchestrationV2DomainEvent,
OrchestrationV2RuntimeRequest,
OrchestrationV2ShellSnapshot,
OrchestrationV2StoredEvent,
OrchestrationV2ThreadProjection,
ProviderApprovalDecision,
@@ -55,6 +56,7 @@ export interface OrchestratorV2ScenarioResult {
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
readonly domainEvents: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly projections: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
readonly shellSnapshot: OrchestrationV2ShellSnapshot;
}
export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass<OrchestratorV2ScenarioStepError>()(
@@ -81,6 +83,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
case "provider.switch":
return [command.threadId];
case "thread.fork":
case "thread.merge_back":
return [command.sourceThreadId, command.targetThreadId];
}
}
@@ -263,6 +266,7 @@ export function runOrchestratorV2Scenario(
for (const threadId of collectProjectionThreadIds(scenario)) {
projections.set(threadId, yield* orchestrator.getThreadProjection(threadId));
}
const shellSnapshot = yield* orchestrator.getShellSnapshot();
yield* Effect.yieldNow;
@@ -274,6 +278,7 @@ export function runOrchestratorV2Scenario(
storedEvents,
domainEvents: storedEvents.map((stored) => stored.event),
projections,
shellSnapshot,
};
}),
);
@@ -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,
@@ -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<ProviderReplayEntry>;
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<OrchestrationV2Command>;
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)),
);
});
@@ -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,
@@ -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"]);
@@ -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 });
@@ -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"]);
@@ -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");
@@ -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<OrchestrationV2UserMessageInputIntent>,
) {
assert.deepEqual(
projection.turnItems
.filter((item) => item.type === "user_message")
.map((item) => item.inputIntent),
expectedIntents,
);
}
@@ -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"]);
@@ -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, [
@@ -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"]);
@@ -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",
@@ -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",
@@ -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 });
@@ -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",
@@ -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"]);
+41 -1
View File
@@ -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<OrchestrationV2ShellStreamItem>();
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<OrchestrationV2ThreadStreamItem>();
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<OrchestrationV2ThreadStreamItem> = [];
const shellUpdates: Array<OrchestrationV2ShellStreamItem> = [];
const turnItemTypes = new Set<string>();
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",
+66 -4
View File
@@ -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,
@@ -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"],
},
+2
View File
@@ -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),
},
+386 -226
View File
@@ -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<string, unknown> {
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<T extends { readonly id: unknown }>(
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<DebugThreadTreeNode>;
}
@@ -537,6 +594,26 @@ function buildItemTimeline(input: {
readonly projectionsByThread: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
readonly logEntries: ReadonlyArray<LogEntry>;
}): ReadonlyArray<ItemTimelineRow> {
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<ThreadId, OrchestrationV2ThreadProjection>;
readonly debugThreads: ReadonlyArray<DebugThreadOption>;
readonly threads: ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>;
}): ReadonlyArray<DebugThreadTreeNode> {
const entries = new Map<ThreadId, OrchestrationV2ThreadProjection | null>();
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<ThreadId, Array<ThreadId>>();
const rootIds: Array<ThreadId> = [];
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<ThreadId>) =>
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 (
<li
@@ -1088,9 +1157,7 @@ function ThreadTreeRow(props: {
/>
<span className="min-w-0">
<span className="flex min-w-0 items-baseline gap-1.5">
<span className="truncate font-medium">
{projection?.thread.title ?? "Unknown thread"}
</span>
<span className="truncate font-medium">{thread.title}</span>
<span
className={`shrink-0 rounded-full border px-1.5 py-px text-[10px] font-medium uppercase ${
active
@@ -1132,46 +1199,6 @@ function ThreadTreeRow(props: {
);
}
function ForkControls(props: {
readonly projection: OrchestrationV2ThreadProjection | null;
readonly disabled: boolean;
readonly onForkLatestStable: () => void;
}) {
const latestCompletedRun = latestCompletedRunInProjection(props.projection);
const canFork = latestCompletedRun !== null;
if (props.projection === null) {
return null;
}
return (
<section className="rounded-md border border-border bg-card px-3 py-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<h2 className="text-sm font-semibold">Fork</h2>
<p className="truncate text-xs text-muted-foreground">
{canFork
? `Latest completed run: ${compactId(latestCompletedRun.id) ?? latestCompletedRun.id}`
: "Run once, then fork from the latest completed run."}
</p>
</div>
<button
type="button"
disabled={props.disabled || !canFork}
onClick={props.onForkLatestStable}
className="inline-flex h-8 shrink-0 items-center rounded-md border border-border bg-background px-3 text-sm font-medium disabled:cursor-not-allowed disabled:opacity-50 hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
title={
canFork
? "Create an idle fork and switch the debugger to it"
: "A completed source run is required before forking"
}
>
Fork latest
</button>
</div>
</section>
);
}
function QueueControls(props: {
readonly rows: ReadonlyArray<QueuedRunRow>;
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 (
<button
type="button"
disabled={props.disabled || !canMerge}
onClick={props.onMergeBack}
className="inline-flex h-7 shrink-0 items-center justify-center gap-1 rounded-md border border-emerald-200 bg-emerald-50 px-2.5 text-xs font-medium text-emerald-900 disabled:cursor-not-allowed disabled:border-border disabled:bg-muted disabled:text-muted-foreground hover:bg-emerald-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
title={
canMerge
? "Create a merge-back context transfer and open the source thread"
: "No completed fork run is available to merge"
}
>
<GitMergeIcon className="size-3" />
Merge back
<span className="font-mono text-foreground" title={props.candidate.targetThreadId}>
{compactId(props.candidate.targetThreadId) ?? props.candidate.targetThreadId}
</span>
</button>
);
}
function PendingMergeBackNotice(props: { readonly transfer: PendingMergeBackTransfer | null }) {
if (props.transfer === null) {
return null;
}
return (
<div className="flex min-w-0 items-center gap-2 rounded-md border border-sky-200 bg-sky-50 px-3 py-2 text-xs text-sky-950 dark:border-sky-500/30 dark:bg-sky-500/10 dark:text-sky-100">
<GitMergeIcon className="size-3 shrink-0" />
<p className="min-w-0 truncate">
Merge back pending from{" "}
<span className="font-mono font-medium" title={props.transfer.sourceThreadId}>
{compactId(props.transfer.sourceThreadId) ?? props.transfer.sourceThreadId}
</span>
. Your next message will include that fork context.
</p>
</div>
);
}
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<ThreadId | null>(null);
const [projection, setProjection] = useState<OrchestrationV2ThreadProjection | null>(null);
const [projectionError, setProjectionError] = useState<string | null>(null);
const [logEntries, setLogEntries] = useState<ReadonlyArray<LogEntry>>([]);
const [debugThreads, setDebugThreads] = useState<ReadonlyArray<DebugThreadOption>>([]);
const [shellThreadsById, setShellThreadsById] = useState<
ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>
>(() => new Map());
const [projectionByThread, setProjectionByThread] = useState<
ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>
>(() => new Map());
@@ -1330,6 +1411,7 @@ function OrchestrationV2DebugRoute() {
const [visiblePanels, setVisiblePanels] =
useState<ReadonlyArray<PanelKey>>(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() {
<ItemTimelinePanel
title={PANEL_TITLES.item}
projection={projection}
errorMessage={projectionError}
rows={itemTimeline}
activeTurn={activeTurn}
disabled={isBusy}
@@ -1824,6 +1954,7 @@ function OrchestrationV2DebugRoute() {
void sendPrompt("send");
}}
>
<PendingMergeBackNotice transfer={pendingMergeBackTransfer} />
<label className="flex min-w-0 flex-col gap-1.5 text-sm font-medium">
<textarea
name="prompt"
@@ -1842,6 +1973,13 @@ function OrchestrationV2DebugRoute() {
/>
</label>
<div className="flex flex-wrap items-center justify-end gap-2">
<MergeBackControls
candidate={mergeBackCandidate}
disabled={isBusy}
onMergeBack={() => {
void mergeBackToSource();
}}
/>
<kbd className="font-mono text-xs font-normal text-muted-foreground">
{IS_MAC ? "⌘ + ↵" : "Ctrl + ↵"} to {activeTurn === null ? "send" : "queue"}
</kbd>
@@ -1890,15 +2028,6 @@ function OrchestrationV2DebugRoute() {
</button>
</div>
</form>
<div className="mt-3">
<ForkControls
projection={projection}
disabled={isBusy}
onForkLatestStable={() => {
void forkLatestStable();
}}
/>
</div>
<QueueControls
rows={queuedRuns}
activeTurn={activeTurn}
@@ -2124,6 +2253,7 @@ type ItemViewMode = "chat" | "raw";
function ItemTimelinePanel(props: {
readonly title: string;
readonly projection: OrchestrationV2ThreadProjection | null;
readonly errorMessage: string | null;
readonly rows: ReadonlyArray<ItemTimelineRow>;
readonly activeTurn: ActiveTurn | null;
readonly disabled: boolean;
@@ -2161,7 +2291,12 @@ function ItemTimelinePanel(props: {
</>
}
/>
{rowCount === 0 && activeTurnStartMs === null ? (
{rowCount === 0 && activeTurnStartMs === null && props.errorMessage !== null ? (
<div className="flex min-h-48 flex-col items-center justify-center gap-2 p-6 text-center">
<p className="text-sm font-medium text-destructive">Failed to load projection.</p>
<p className="max-w-lg text-xs text-muted-foreground">{props.errorMessage}</p>
</div>
) : rowCount === 0 && activeTurnStartMs === null ? (
<div className="flex min-h-48 items-center justify-center p-6 text-base text-muted-foreground sm:text-sm">
No items yet.
</div>
@@ -2287,10 +2422,12 @@ type ChatScene =
readonly kind: "fork-marker";
readonly key: string;
readonly sourceThreadId: ThreadId;
readonly targetThreadId: ThreadId;
readonly timestamp: string | undefined;
}
| { readonly kind: "response"; readonly duration: string | undefined; readonly anchorId: string }
| {
readonly kind: "response";
readonly duration: string | undefined;
readonly anchorId: string;
}
| {
readonly kind: "work-log";
readonly key: string;
@@ -2401,6 +2538,43 @@ function latestCompletedRunInProjection(
);
}
function deriveMergeBackCandidate(
projection: OrchestrationV2ThreadProjection | null,
): MergeBackCandidate | null {
if (projection === null || projection.thread.lineage.relationshipToParent !== "fork") {
return null;
}
const targetThreadId =
projection.thread.forkedFrom?.type === "run"
? projection.thread.forkedFrom.threadId
: projection.thread.lineage.parentThreadId;
if (targetThreadId === null) {
return null;
}
return {
sourceThreadId: projection.thread.id,
targetThreadId,
latestCompletedRun: latestCompletedRunInProjection(projection),
};
}
function derivePendingMergeBackTransfer(
projection: OrchestrationV2ThreadProjection | null,
): PendingMergeBackTransfer | null {
if (projection === null) return null;
for (let index = projection.contextTransfers.length - 1; index >= 0; index--) {
const transfer = projection.contextTransfers[index];
if (
transfer?.type === "merge_back" &&
transfer.status === "pending" &&
transfer.targetThreadId === projection.thread.id
) {
return transfer;
}
}
return null;
}
function readyCheckpointsInProjection(
projection: OrchestrationV2ThreadProjection | null,
): ReadonlyArray<OrchestrationV2Checkpoint> {
@@ -2443,8 +2617,6 @@ function buildChatScenes(
kind: "fork-marker",
key: row.entry.key,
sourceThreadId: row.sourceThreadId,
targetThreadId: row.targetThreadId,
timestamp: row.entry.timestamp,
});
pendingResponse = false;
continue;
@@ -2579,6 +2751,10 @@ function ChatScenes(props: {
<div className="flex flex-col gap-2">
{scenes.map((scene) => {
if (scene.kind === "standalone") {
const isSteeringMessage =
scene.item.type === "user_message" &&
(scene.item.inputIntent === "steer" ||
scene.item.inputIntent === "promoted_queued_to_steer");
return (
<ChatItem
key={scene.key}
@@ -2586,8 +2762,11 @@ function ChatScenes(props: {
inheritedFromThreadId={scene.inheritedFromThreadId}
nowMs={props.nowMs}
disabled={props.disabled}
isSteeringMessage={isSteeringMessage}
rollbackCheckpoint={
scene.item.type === "user_message" && scene.item.runId !== null
scene.item.type === "user_message" &&
scene.item.runId !== null &&
!isSteeringMessage
? checkpointByRunId.get(scene.item.runId)
: undefined
}
@@ -2602,9 +2781,6 @@ function ChatScenes(props: {
<ChatForkMarker
key={scene.key}
sourceThreadId={scene.sourceThreadId}
targetThreadId={scene.targetThreadId}
timestamp={scene.timestamp}
nowMs={props.nowMs}
onOpenThread={props.onOpenThread}
/>
);
@@ -2896,6 +3072,7 @@ function ChatItem(props: {
readonly inheritedFromThreadId?: ThreadId | undefined;
readonly nowMs: number;
readonly disabled: boolean;
readonly isSteeringMessage?: boolean | undefined;
readonly rollbackCheckpoint?: OrchestrationV2Checkpoint | undefined;
readonly onOpenThread: (threadId: ThreadId) => void;
readonly onForkFromRun: (input: { readonly threadId: ThreadId; readonly runId: RunId }) => void;
@@ -2916,6 +3093,14 @@ function ChatItem(props: {
</div>
<ChatMeta side="right">
<ChatStatusPill status={item.status} />
{props.isSteeringMessage ? (
<span
className="rounded-full border border-sky-200 bg-sky-50 px-1.5 text-xs font-medium text-sky-800 dark:border-sky-500/30 dark:bg-sky-500/10 dark:text-sky-200"
title="Steer message appended to the active turn"
>
steer
</span>
) : null}
{props.rollbackCheckpoint === undefined ? null : (
<button
type="button"
@@ -3233,14 +3418,7 @@ function ChatItem(props: {
);
case "fork":
return (
<ChatForkDivider
item={item}
timestamp={timestamp}
nowMs={nowMs}
onOpenThread={props.onOpenThread}
/>
);
return <ChatForkDivider item={item} onOpenThread={props.onOpenThread} />;
}
}
@@ -3259,7 +3437,7 @@ function ChatBubbleRow(props: { readonly side: "left" | "right"; readonly childr
function ChatMeta(props: { readonly side: "left" | "right"; readonly children: ReactNode }) {
return (
<div
className={`flex items-center gap-1.5 text-xs ${
className={`flex min-h-6 items-center gap-1.5 text-xs ${
props.side === "right" ? "flex-row-reverse" : ""
}`}
>
@@ -3377,38 +3555,48 @@ function ChatSystemDivider(props: {
);
}
function ChatForkSourceButton(props: {
readonly sourceThreadId: ThreadId | null;
readonly onOpenThread: (threadId: ThreadId) => void;
}) {
const className =
"inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 font-medium text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500";
if (props.sourceThreadId === null) {
return (
<span className={className}>
<ForkIcon />
<span>Forked from conversation</span>
</span>
);
}
const sourceThreadId = props.sourceThreadId;
return (
<button
type="button"
onClick={() => {
props.onOpenThread(sourceThreadId);
}}
className={`${className} hover:bg-muted`}
title="Open source conversation"
>
<ForkIcon />
<span>Forked from conversation</span>
</button>
);
}
function ChatForkMarker(props: {
readonly sourceThreadId: ThreadId;
readonly targetThreadId: ThreadId;
readonly timestamp: string | undefined;
readonly nowMs: number;
readonly onOpenThread: (threadId: ThreadId) => void;
}) {
return (
<div className="flex min-w-0 items-center gap-2 py-2 text-xs text-muted-foreground">
<span aria-hidden="true" className="h-px flex-1 bg-border" />
<button
type="button"
onClick={() => {
props.onOpenThread(props.sourceThreadId);
}}
className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 font-medium text-foreground hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
title={props.sourceThreadId}
>
<ForkIcon />
<span>Forked from conversation</span>
</button>
<button
type="button"
onClick={() => {
props.onOpenThread(props.targetThreadId);
}}
className="min-w-0 max-w-[10rem] truncate rounded-md border border-border bg-background px-2 py-0.5 font-mono text-xs text-foreground hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
title={props.targetThreadId}
>
{compactId(props.targetThreadId) ?? props.targetThreadId}
</button>
<ChatClock iso={props.timestamp} nowMs={props.nowMs} />
<ChatForkSourceButton
sourceThreadId={props.sourceThreadId}
onOpenThread={props.onOpenThread}
/>
<span aria-hidden="true" className="h-px flex-1 bg-border" />
</div>
);
@@ -3416,41 +3604,13 @@ function ChatForkMarker(props: {
function ChatForkDivider(props: {
readonly item: Extract<OrchestrationV2TurnItem, { readonly type: "fork" }>;
readonly timestamp: string | undefined;
readonly nowMs: number;
readonly onOpenThread: (threadId: ThreadId) => void;
}) {
const sourceThreadId = props.item.source.type === "run" ? props.item.source.threadId : null;
return (
<div className="flex min-w-0 items-center gap-2 py-1 text-xs text-muted-foreground">
<div className="flex min-w-0 items-center gap-2 py-2 text-xs text-muted-foreground">
<span aria-hidden="true" className="h-px flex-1 bg-border" />
<span className="shrink-0 rounded-full border border-border bg-background px-2 py-0.5 font-mono font-medium tracking-wide uppercase">
Forked from
</span>
{sourceThreadId === null ? null : (
<button
type="button"
onClick={() => {
props.onOpenThread(sourceThreadId);
}}
className="min-w-0 max-w-[10rem] truncate rounded-md border border-border bg-background px-2 py-0.5 font-mono text-xs text-foreground hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
title={sourceThreadId}
>
{compactId(sourceThreadId) ?? sourceThreadId}
</button>
)}
<span className="font-mono text-muted-foreground/70">→</span>
<button
type="button"
onClick={() => {
props.onOpenThread(props.item.targetThreadId);
}}
className="min-w-0 max-w-[10rem] truncate rounded-md border border-border bg-background px-2 py-0.5 font-mono text-xs text-foreground hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
title={props.item.targetThreadId}
>
{compactId(props.item.targetThreadId) ?? props.item.targetThreadId}
</button>
<ChatClock iso={props.timestamp} nowMs={props.nowMs} />
<ChatForkSourceButton sourceThreadId={sourceThreadId} onOpenThread={props.onOpenThread} />
<span aria-hidden="true" className="h-px flex-1 bg-border" />
</div>
);
+8
View File
@@ -23,6 +23,7 @@ type RpcInput<TTag extends RpcTag> = Parameters<RpcMethod<TTag>>[0];
interface StreamSubscriptionOptions {
readonly onResubscribe?: () => void;
readonly onError?: (message: string) => void;
}
type RpcUnaryMethod<TTag extends RpcTag> =
@@ -125,6 +126,7 @@ export interface WsRpcClient {
readonly getThreadProjection: RpcUnaryMethod<
typeof ORCHESTRATION_V2_WS_METHODS.getThreadProjection
>;
readonly subscribeShell: RpcStreamMethod<typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell>;
readonly subscribeThread: RpcInputStreamMethod<
typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread
>;
@@ -269,6 +271,12 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
transport.request((client) =>
client[ORCHESTRATION_V2_WS_METHODS.getThreadProjection](input),
),
subscribeShell: (listener, options) =>
transport.subscribe(
(client) => client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}),
listener,
options,
),
subscribeThread: (input, listener, options) =>
transport.subscribe(
(client) => client[ORCHESTRATION_V2_WS_METHODS.subscribeThread](input),
+289
View File
@@ -0,0 +1,289 @@
import {
Cause,
Duration,
Effect,
Exit,
Layer,
ManagedRuntime,
Option,
Scope,
Stream,
} from "effect";
import { RpcClient } from "effect/unstable/rpc";
import { ClientTracingLive } from "../observability/clientTracing";
import { clearAllTrackedRpcRequests } from "./requestLatencyState";
import {
createWsRpcProtocolLayer,
makeWsRpcProtocolClient,
type WsProtocolLifecycleHandlers,
type WsRpcProtocolClient,
type WsRpcProtocolSocketUrlProvider,
} from "./protocol";
import { isTransportConnectionErrorMessage } from "./transportError";
interface SubscribeOptions {
readonly retryDelay?: Duration.Input;
readonly onResubscribe?: () => void;
readonly onError?: (message: string) => void;
}
interface RequestOptions {
readonly timeout?: Option.Option<Duration.Input>;
}
const DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS = Duration.millis(250);
const NOOP: () => void = () => undefined;
interface TransportSession {
readonly clientPromise: Promise<WsRpcProtocolClient>;
readonly clientScope: Scope.Closeable;
readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
}
function formatErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return String(error);
}
export class WsTransport {
private readonly url: WsRpcProtocolSocketUrlProvider;
private readonly lifecycleHandlers: WsProtocolLifecycleHandlers | undefined;
private disposed = false;
private hasReportedTransportDisconnect = false;
private reconnectChain: Promise<void> = Promise.resolve();
private session: TransportSession;
constructor(
url: WsRpcProtocolSocketUrlProvider,
lifecycleHandlers?: WsProtocolLifecycleHandlers,
) {
this.url = url;
this.lifecycleHandlers = lifecycleHandlers;
this.session = this.createSession();
}
async request<TSuccess>(
execute: (client: WsRpcProtocolClient) => Effect.Effect<TSuccess, Error, never>,
_options?: RequestOptions,
): Promise<TSuccess> {
if (this.disposed) {
throw new Error("Transport disposed");
}
const session = this.session;
const client = await session.clientPromise;
return await session.runtime.runPromise(Effect.suspend(() => execute(client)));
}
async requestStream<TValue>(
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
listener: (value: TValue) => void,
): Promise<void> {
if (this.disposed) {
throw new Error("Transport disposed");
}
const session = this.session;
const client = await session.clientPromise;
await session.runtime.runPromise(
Stream.runForEach(connect(client), (value) =>
Effect.sync(() => {
try {
listener(value);
} catch {
// Swallow listener errors so the stream can finish cleanly.
}
}),
),
);
}
subscribe<TValue>(
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
listener: (value: TValue) => void,
options?: SubscribeOptions,
): () => void {
if (this.disposed) {
return () => undefined;
}
let active = true;
let hasReceivedValue = false;
const retryDelayMs = Duration.toMillis(
Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS),
);
let cancelCurrentStream: () => void = NOOP;
void (async () => {
for (;;) {
if (!active || this.disposed) {
return;
}
const session = this.session;
try {
if (hasReceivedValue) {
try {
options?.onResubscribe?.();
} catch {
// Swallow reconnect hook errors so the stream can recover.
}
}
const runningStream = this.runStreamOnSession(
session,
connect,
listener,
() => active,
() => {
this.hasReportedTransportDisconnect = false;
hasReceivedValue = true;
},
);
cancelCurrentStream = runningStream.cancel;
await runningStream.completed;
cancelCurrentStream = NOOP;
} catch (error) {
cancelCurrentStream = NOOP;
if (!active || this.disposed) {
return;
}
if (session !== this.session) {
continue;
}
const formattedError = formatErrorMessage(error);
if (!isTransportConnectionErrorMessage(formattedError)) {
console.warn("WebSocket RPC subscription failed", {
error: formattedError,
});
options?.onError?.(formattedError);
return;
}
if (!this.hasReportedTransportDisconnect) {
console.warn("WebSocket RPC subscription disconnected", {
error: formattedError,
});
}
this.hasReportedTransportDisconnect = true;
await sleep(retryDelayMs);
}
}
})();
return () => {
active = false;
cancelCurrentStream();
};
}
async reconnect() {
if (this.disposed) {
throw new Error("Transport disposed");
}
const reconnectOperation = this.reconnectChain.then(async () => {
if (this.disposed) {
throw new Error("Transport disposed");
}
clearAllTrackedRpcRequests();
const previousSession = this.session;
this.session = this.createSession();
await this.closeSession(previousSession);
});
this.reconnectChain = reconnectOperation.catch(() => undefined);
await reconnectOperation;
}
async dispose() {
if (this.disposed) {
return;
}
this.disposed = true;
await this.closeSession(this.session);
}
private closeSession(session: TransportSession) {
return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
session.runtime.dispose();
});
}
private createSession(): TransportSession {
const runtime = ManagedRuntime.make(
Layer.mergeAll(createWsRpcProtocolLayer(this.url, this.lifecycleHandlers), ClientTracingLive),
);
const clientScope = runtime.runSync(Scope.make());
return {
runtime,
clientScope,
clientPromise: runtime.runPromise(Scope.provide(clientScope)(makeWsRpcProtocolClient)),
};
}
private runStreamOnSession<TValue>(
session: TransportSession,
connect: (client: WsRpcProtocolClient) => Stream.Stream<TValue, Error, never>,
listener: (value: TValue) => void,
isActive: () => boolean,
markValueReceived: () => void,
): {
readonly cancel: () => void;
readonly completed: Promise<void>;
} {
let resolveCompleted!: () => void;
let rejectCompleted!: (error: unknown) => void;
const completed = new Promise<void>((resolve, reject) => {
resolveCompleted = resolve;
rejectCompleted = reject;
});
const cancel = session.runtime.runCallback(
Effect.promise(() => session.clientPromise).pipe(
Effect.flatMap((client) =>
Stream.runForEach(connect(client), (value) =>
Effect.sync(() => {
if (!isActive()) {
return;
}
markValueReceived();
try {
listener(value);
} catch {
// Swallow listener errors so the stream stays live.
}
}),
),
),
),
{
onExit: (exit) => {
if (Exit.isSuccess(exit)) {
resolveCompleted();
return;
}
rejectCompleted(Cause.squash(exit.cause));
},
},
);
return {
cancel,
completed,
};
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
@@ -613,6 +613,12 @@ The frontend should not reconstruct display order by merging `messages`, `plans`
`turnItems` are projection records, not the canonical source of truth. The canonical graph remains normalized in runs, attempts, nodes, requests, messages, plans, and checkpoints. Provider-native item refs live directly on nodes and turn items where correlation is needed.
Forked threads also expose a derived `visibleTurnItems` projection. `turnItems` remains the canonical
items emitted on that app thread. `visibleTurnItems` is the user-visible ordered read model: it may
reference inherited source items through the fork source point, include synthetic lifecycle markers
such as "forked from conversation", and then continue with local target-thread items. This keeps
storage normalized while giving thread detail views and tests one backend-owned surface to assert.
Known common tools should have structured item variants so the frontend can render stable custom components without parsing provider text:
```ts
+12
View File
@@ -86,6 +86,7 @@ import type {
OrchestrationV2Command,
OrchestrationV2DispatchCommandResult,
OrchestrationV2GetThreadProjectionInput,
OrchestrationV2ShellStreamItem,
OrchestrationV2ThreadProjection,
OrchestrationV2ThreadStreamItem,
} from "./orchestrationV2.ts";
@@ -1189,6 +1190,7 @@ export interface EnvironmentApi {
callback: (status: VcsStatusResult) => void,
options?: {
onResubscribe?: () => void;
onError?: (message: string) => void;
},
) => () => void;
};
@@ -1212,6 +1214,7 @@ export interface EnvironmentApi {
callback: (event: OrchestrationShellStreamItem) => void,
options?: {
onResubscribe?: () => void;
onError?: (message: string) => void;
},
) => () => void;
subscribeThread: (
@@ -1219,6 +1222,7 @@ export interface EnvironmentApi {
callback: (event: OrchestrationThreadStreamItem) => void,
options?: {
onResubscribe?: () => void;
onError?: (message: string) => void;
},
) => () => void;
};
@@ -1229,11 +1233,19 @@ export interface EnvironmentApi {
getThreadProjection: (
input: OrchestrationV2GetThreadProjectionInput,
) => Promise<OrchestrationV2ThreadProjection>;
subscribeShell: (
callback: (event: OrchestrationV2ShellStreamItem) => void,
options?: {
onResubscribe?: () => void;
onError?: (message: string) => void;
},
) => () => void;
subscribeThread: (
input: OrchestrationV2GetThreadProjectionInput,
callback: (event: OrchestrationV2ThreadStreamItem) => void,
options?: {
onResubscribe?: () => void;
onError?: (message: string) => void;
},
) => () => void;
};
+93
View File
@@ -94,6 +94,10 @@ export const OrchestrationV2ContextTransferResolution = Schema.Union([
strategy: Schema.Literal("delta_context"),
contextHandoffId: ContextHandoffId,
}),
Schema.Struct({
strategy: Schema.Literal("fork_delta_context"),
contextHandoffId: ContextHandoffId,
}),
Schema.Struct({
strategy: Schema.Literal("checkpoint_context"),
contextHandoffId: ContextHandoffId,
@@ -450,6 +454,7 @@ export const OrchestrationV2ContextHandoff = Schema.Struct({
}),
strategy: Schema.Literals([
"delta_since_target_last_seen",
"fork_delta_summary",
"full_thread_summary",
"checkpoint_summary",
"manual_context",
@@ -594,6 +599,15 @@ export const OrchestrationV2TurnItemStatus = Schema.Literals([
]);
export type OrchestrationV2TurnItemStatus = typeof OrchestrationV2TurnItemStatus.Type;
export const OrchestrationV2UserMessageInputIntent = Schema.Literals([
"turn_start",
"queued_turn",
"steer",
"promoted_queued_to_steer",
]);
export type OrchestrationV2UserMessageInputIntent =
typeof OrchestrationV2UserMessageInputIntent.Type;
const OrchestrationV2TurnItemBaseFields = {
id: TurnItemId,
threadId: ThreadId,
@@ -631,6 +645,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
...OrchestrationV2TurnItemBaseFields,
type: Schema.Literal("user_message"),
messageId: MessageId,
inputIntent: OrchestrationV2UserMessageInputIntent,
text: Schema.String,
attachments: Schema.Array(ChatAttachment),
}),
@@ -738,6 +753,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
toProvider: ProviderKind,
strategy: Schema.Literals([
"delta_since_target_last_seen",
"fork_delta_summary",
"full_thread_summary",
"checkpoint_summary",
"manual_context",
@@ -769,6 +785,15 @@ export const OrchestrationV2TurnItem = Schema.Union([
]);
export type OrchestrationV2TurnItem = typeof OrchestrationV2TurnItem.Type;
export const OrchestrationV2ProjectedTurnItem = Schema.Struct({
position: NonNegativeInt,
visibility: Schema.Literals(["local", "inherited", "synthetic"]),
sourceThreadId: ThreadId,
sourceItemId: TurnItemId,
item: OrchestrationV2TurnItem,
});
export type OrchestrationV2ProjectedTurnItem = typeof OrchestrationV2ProjectedTurnItem.Type;
export const OrchestrationV2RawProviderEvent = Schema.Struct({
id: RawEventId,
provider: ProviderKind,
@@ -903,10 +928,54 @@ export const OrchestrationV2ThreadProjection = Schema.Struct({
checkpoints: Schema.Array(OrchestrationV2Checkpoint),
contextHandoffs: Schema.Array(OrchestrationV2ContextHandoff),
contextTransfers: Schema.Array(OrchestrationV2ContextTransfer),
visibleTurnItems: Schema.Array(OrchestrationV2ProjectedTurnItem),
updatedAt: Schema.DateTimeUtc,
});
export type OrchestrationV2ThreadProjection = typeof OrchestrationV2ThreadProjection.Type;
export const OrchestrationV2ShellThreadStatus = Schema.Union([
Schema.Literal("idle"),
OrchestrationV2RunStatus,
]);
export type OrchestrationV2ShellThreadStatus = typeof OrchestrationV2ShellThreadStatus.Type;
export const OrchestrationV2ThreadShell = Schema.Struct({
id: ThreadId,
projectId: ProjectId,
title: Schema.String,
defaultProvider: ProviderKind,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
lineage: OrchestrationV2AppThreadLineage,
forkedFrom: Schema.NullOr(OrchestrationV2AppThread.fields.forkedFrom),
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
latestRunId: Schema.NullOr(RunId),
status: OrchestrationV2ShellThreadStatus,
itemCount: NonNegativeInt,
visibleItemCount: NonNegativeInt,
createdAt: Schema.DateTimeUtc,
updatedAt: Schema.DateTimeUtc,
});
export type OrchestrationV2ThreadShell = typeof OrchestrationV2ThreadShell.Type;
export const OrchestrationV2ShellSnapshot = Schema.Struct({
threads: Schema.Array(OrchestrationV2ThreadShell),
});
export type OrchestrationV2ShellSnapshot = typeof OrchestrationV2ShellSnapshot.Type;
export const OrchestrationV2ShellStreamItem = Schema.Union([
Schema.Struct({
kind: Schema.Literal("snapshot"),
snapshot: OrchestrationV2ShellSnapshot,
}),
Schema.Struct({
kind: Schema.Literal("thread.updated"),
thread: OrchestrationV2ThreadShell,
}),
]);
export type OrchestrationV2ShellStreamItem = typeof OrchestrationV2ShellStreamItem.Type;
export const OrchestrationV2StoredEvent = Schema.Struct({
sequence: NonNegativeInt,
commandId: Schema.NullOr(CommandId),
@@ -1036,6 +1105,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
...OrchestrationV2TurnItemJsonBaseFields,
type: Schema.Literal("user_message"),
messageId: MessageId,
inputIntent: OrchestrationV2UserMessageInputIntent,
text: Schema.String,
attachments: Schema.Array(ChatAttachment),
}),
@@ -1143,6 +1213,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
toProvider: ProviderKind,
strategy: Schema.Literals([
"delta_since_target_last_seen",
"fork_delta_summary",
"full_thread_summary",
"checkpoint_summary",
"manual_context",
@@ -1360,6 +1431,14 @@ export const OrchestrationV2Command = Schema.Union([
title: Schema.optional(TrimmedNonEmptyString),
createdAt: Schema.optional(Schema.DateTimeUtc),
}),
Schema.Struct({
type: Schema.Literal("thread.merge_back"),
commandId: CommandId,
sourceThreadId: ThreadId,
targetThreadId: ThreadId,
sourcePoint: OrchestrationV2ThreadForkSourcePoint,
createdAt: Schema.optional(Schema.DateTimeUtc),
}),
Schema.Struct({
type: Schema.Literal("provider.switch"),
commandId: CommandId,
@@ -1373,6 +1452,7 @@ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type;
export const ORCHESTRATION_V2_WS_METHODS = {
dispatchCommand: "orchestrationV2.dispatchCommand",
getThreadProjection: "orchestrationV2.getThreadProjection",
subscribeShell: "orchestrationV2.subscribeShell",
subscribeThread: "orchestrationV2.subscribeThread",
} as const;
@@ -1420,9 +1500,18 @@ export class OrchestrationV2GetThreadProjectionError extends Schema.TaggedErrorC
},
) {}
export class OrchestrationV2GetShellSnapshotError extends Schema.TaggedErrorClass<OrchestrationV2GetShellSnapshotError>()(
"OrchestrationV2GetShellSnapshotError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
export const OrchestrationV2RpcError = Schema.Union([
OrchestrationV2DispatchCommandError,
OrchestrationV2GetThreadProjectionError,
OrchestrationV2GetShellSnapshotError,
]);
export type OrchestrationV2RpcError = typeof OrchestrationV2RpcError.Type;
@@ -1435,6 +1524,10 @@ export const OrchestrationV2RpcSchemas = {
input: OrchestrationV2GetThreadProjectionInput,
output: OrchestrationV2ThreadProjection,
},
subscribeShell: {
input: Schema.Struct({}),
output: OrchestrationV2ShellStreamItem,
},
subscribeThread: {
input: OrchestrationV2GetThreadProjectionInput,
output: OrchestrationV2ThreadStreamItem,
+12
View File
@@ -67,6 +67,7 @@ import { ProviderInstanceId } from "./providerInstance.ts";
import {
ORCHESTRATION_V2_WS_METHODS,
OrchestrationV2DispatchCommandError,
OrchestrationV2GetShellSnapshotError,
OrchestrationV2GetThreadProjectionError,
OrchestrationV2RpcSchemas,
} from "./orchestrationV2.ts";
@@ -744,6 +745,16 @@ export const WsOrchestrationV2GetThreadProjectionRpc = Rpc.make(
},
);
export const WsOrchestrationV2SubscribeShellRpc = Rpc.make(
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
{
payload: OrchestrationV2RpcSchemas.subscribeShell.input,
success: OrchestrationV2RpcSchemas.subscribeShell.output,
error: OrchestrationV2GetShellSnapshotError,
stream: true,
},
);
export const WsOrchestrationV2SubscribeThreadRpc = Rpc.make(
ORCHESTRATION_V2_WS_METHODS.subscribeThread,
{
@@ -885,5 +896,6 @@ export const WsRpcGroup = RpcGroup.make(
WsOrchestrationSubscribeThreadRpc,
WsOrchestrationV2DispatchCommandRpc,
WsOrchestrationV2GetThreadProjectionRpc,
WsOrchestrationV2SubscribeShellRpc,
WsOrchestrationV2SubscribeThreadRpc,
);