fix(orchestration): handle checkpoint-wait runs

Allow merge-back from provider-finished runs awaiting checkpoint capture while keeping waiting runs visible but non-interruptible in mobile.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-07-28 12:53:42 +02:00
1 parent 32036d2585
commit f61653209a
8 files changed
+238 -14

No files matched your search

@@ -6,7 +6,10 @@ import {
resolveMergeBackTargetThreadId,
type ThreadRelationshipEdge,
} from "@t3tools/client-runtime/state/thread-relationships";
import { canDetachThreadProviderSession } from "@t3tools/client-runtime/state/thread-workflows";
import {
canDetachThreadProviderSession,
resolveLatestMergeBackRun,
} from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { copySorted } from "@t3tools/shared/Array";
import { useNavigation } from "@react-navigation/native";
@@ -87,8 +90,8 @@ export function ThreadRelationshipsBanner(props: {
),
[graph, mergeTargetThreadId, props.threadId],
);
const latestCompletedRun = projection?.runs.findLast((run) => run.status === "completed") ?? null;
const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;
const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
const [visible, setVisible] = useState(false);
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
@@ -122,14 +125,14 @@ export function ThreadRelationshipsBanner(props: {
};
const merge = async () => {
if (!canMerge || mergeTargetThreadId === null || latestCompletedRun === null) return;
if (!canMerge || mergeTargetThreadId === null || latestMergeBackRun === null) return;
setBusyAction("merge");
const result = await mergeBack({
environmentId: props.environmentId,
input: {
sourceThreadId: props.threadId,
targetThreadId: mergeTargetThreadId,
runId: latestCompletedRun.id,
runId: latestMergeBackRun.id,
creationSource: "mobile",
},
});
@@ -1486,11 +1486,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: `No stable source run was found for merge-back source ${command.sourcePoint.type}.`,
});
}
if (sourceRun.status !== "completed") {
if (sourceRun.status !== "completed" && sourceRun.status !== "waiting") {
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.`,
cause: `Merge-back source run ${sourceRun.id} is ${sourceRun.status}; only provider-finished runs are supported.`,
});
}
@@ -3,11 +3,15 @@ import { assert, it } from "@effect/vitest";
import {
type ApplicationStoredEvent,
CommandId,
ContextTransferId,
EventId,
MessageId,
type ModelSelection,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderThreadId,
RunId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -38,9 +42,10 @@ import {
OrchestratorV2,
} from "./Orchestrator.ts";
import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts";
import { EventSinkV2 } from "./EventSink.ts";
import { ProjectionMaintenanceV2 } from "./ProjectionMaintenance.ts";
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
import { OrchestrationV2EventSinkLayerLive, OrchestrationV2LayerLive } from "./runtimeLayer.ts";
import { shellStreamItemFromSnapshot } from "./ShellStream.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import { ThreadManagementService } from "./ThreadManagementService.ts";
@@ -95,7 +100,7 @@ const TestProviderInstanceRegistry = Layer.succeed(ProviderInstanceRegistry, {
subscribeChanges: Effect.never,
});
const TestLayer = OrchestrationV2LayerLive.pipe(
const TestLayer = Layer.merge(OrchestrationV2LayerLive, OrchestrationV2EventSinkLayerLive).pipe(
Layer.provide(mcpSessionRegistryTestLayer),
Layer.provide(SqlitePersistenceMemory),
Layer.provide(CheckpointStoreTestLayer),
@@ -178,6 +183,175 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
assert.deepEqual(projection.runs, []);
}),
);
it.effect("merges an explicit provider-finished run while checkpoint capture is pending", () =>
Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
const eventSink = yield* EventSinkV2;
const now = yield* DateTime.now;
const projectId = ProjectId.make("runtime-layer-waiting-merge-project");
const targetThreadId = ThreadId.make("runtime-layer-waiting-merge-target");
const sourceThreadId = ThreadId.make("runtime-layer-waiting-merge-source");
const baseRunId = RunId.make("runtime-layer-waiting-merge-base-run");
const sourceRunId = RunId.make("runtime-layer-waiting-merge-source-run");
const sourceProviderThreadId = ProviderThreadId.make(
"runtime-layer-waiting-merge-provider-thread",
);
const forkTransferId = ContextTransferId.make("runtime-layer-waiting-merge-fork-transfer");
yield* orchestrator.dispatch({
type: "thread.create",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make("runtime-layer-waiting-merge-create-target"),
threadId: targetThreadId,
projectId,
title: "Waiting merge target",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
});
const target = yield* orchestrator.getThreadProjection(targetThreadId);
yield* eventSink.write({
commandId: CommandId.make("runtime-layer-waiting-merge-seed"),
events: [
{
id: EventId.make("runtime-layer-waiting-merge-source-thread-event"),
type: "thread.created",
threadId: sourceThreadId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
payload: {
...target.thread,
id: sourceThreadId,
title: "Waiting merge source",
activeProviderThreadId: null,
lineage: {
parentThreadId: targetThreadId,
relationshipToParent: "fork",
rootThreadId: targetThreadId,
},
forkedFrom: {
type: "run",
threadId: targetThreadId,
runId: baseRunId,
},
createdAt: now,
updatedAt: now,
},
},
{
id: EventId.make("runtime-layer-waiting-merge-fork-transfer-event"),
type: "context-transfer.created",
threadId: sourceThreadId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
payload: {
id: forkTransferId,
type: "fork",
sourceThreadId: targetThreadId,
targetThreadId: sourceThreadId,
sourcePoint: { threadId: targetThreadId, runId: baseRunId },
basePoint: null,
sourceProviderInstanceId: modelSelection.instanceId,
targetProviderInstanceId: modelSelection.instanceId,
targetRunId: null,
status: "consumed",
resolution: null,
createdBy: "user",
error: null,
createdAt: now,
updatedAt: now,
consumedAt: now,
},
},
{
id: EventId.make("runtime-layer-waiting-merge-provider-thread-event"),
type: "provider-thread.updated",
threadId: sourceThreadId,
driver,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
payload: {
id: sourceProviderThreadId,
driver,
providerInstanceId: modelSelection.instanceId,
providerSessionId: null,
appThreadId: sourceThreadId,
ownerNodeId: null,
nativeThreadRef: {
driver,
nativeId: "native-waiting-merge-source",
strength: "strong",
},
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: 1,
lastRunOrdinal: 1,
handoffIds: [],
forkedFrom: null,
createdAt: now,
updatedAt: now,
},
},
{
id: EventId.make("runtime-layer-waiting-merge-source-run-event"),
type: "run.created",
threadId: sourceThreadId,
runId: sourceRunId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
payload: {
id: sourceRunId,
threadId: sourceThreadId,
ordinal: 1,
providerInstanceId: modelSelection.instanceId,
modelSelection,
providerThreadId: sourceProviderThreadId,
userMessageId: MessageId.make("runtime-layer-waiting-merge-message"),
rootNodeId: null,
activeAttemptId: null,
status: "waiting",
queuePosition: null,
requestedAt: now,
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
},
},
],
});
yield* orchestrator.dispatch({
type: "thread.merge_back",
createdBy: "user",
creationSource: "mobile",
commandId: CommandId.make("runtime-layer-waiting-merge"),
sourceThreadId,
targetThreadId,
sourcePoint: { type: "run", runId: sourceRunId },
createdAt: now,
});
const mergedTarget = yield* orchestrator.getThreadProjection(targetThreadId);
const transfer = mergedTarget.contextTransfers.find(
(candidate) => candidate.type === "merge_back",
);
assert.isDefined(transfer);
assert.equal(transfer.status, "pending");
assert.equal(transfer.sourceThreadId, sourceThreadId);
assert.equal(transfer.targetThreadId, targetThreadId);
assert.equal(transfer.sourcePoint.runId, sourceRunId);
assert.isUndefined(transfer.sourcePoint.checkpointId);
assert.equal(transfer.sourcePoint.providerThreadRef?.nativeId, "native-waiting-merge-source");
assert.equal(transfer.basePoint?.runId, baseRunId);
assert.isNull(transfer.error);
}),
);
});
it.layer(LegacyImportTestLayer)("OrchestrationV2 legacy import", (it) => {
@@ -67,7 +67,8 @@ const storesLayer = Layer.mergeAll(
turnItemPositionStoreLayer,
);
const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesLayer));
export const OrchestrationV2EventSinkLayerLive = eventSinkLayer.pipe(Layer.provide(storesLayer));
const eventSinkProvided = OrchestrationV2EventSinkLayerLive;
const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesLayer));
const legacyV1ThreadImporterProvided = legacyV1ThreadImporterLayer.pipe(
Layer.provide(Layer.mergeAll(eventSinkProvided, eventStoreProvided)),
@@ -68,4 +68,21 @@ describe("thread execution presentation", () => {
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
});
it("keeps checkpoint-wait activity visible without exposing a non-functional interrupt", () => {
const waitingRun = run("run-waiting", 1, "waiting");
const projection = { ...v2Projection, runs: [waitingRun], updatedAt: now };
expect(deriveThreadActivityRun(projection)).toMatchObject({
runId: waitingRun.id,
status: "waiting",
});
const runtime = deriveThreadRuntime(projection);
expect(runtime).toMatchObject({
status: "waiting",
activeRunId: null,
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
});
});
@@ -3,7 +3,8 @@ import * as DateTime from "effect/DateTime";
import type { ThreadRunSummary, ThreadRuntimeSummary } from "./models.ts";
const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
function latestMatchingRun(
projection: OrchestrationV2ThreadProjection,
@@ -52,9 +53,8 @@ export function deriveThreadActivityRun(
projection: OrchestrationV2ThreadProjection,
): ThreadRunSummary | null {
const run =
latestMatchingRun(projection, (candidate) =>
INTERRUPTIBLE_RUN_STATUSES.has(candidate.status),
) ?? latestMatchingRun(projection, () => true);
latestMatchingRun(projection, (candidate) => ACTIVITY_RUN_STATUSES.has(candidate.status)) ??
latestMatchingRun(projection, () => true);
return run === null ? null : summarizeThreadRun(projection, run);
}
@@ -4,6 +4,7 @@ import {
canDetachThreadProviderSession,
canForkProjectedAssistantItem,
deriveThreadQueueWorkflowState,
resolveLatestMergeBackRun,
} from "./threadWorkflows.ts";
const capabilities = (input?: {
@@ -130,4 +131,16 @@ describe("thread workflows", () => {
}),
).toBe(false);
});
it("merges the newest provider-finished run while checkpoint capture is pending", () => {
const projection = {
runs: [
{ id: "newest-queued", status: "queued", ordinal: 3 },
{ id: "older-completed", status: "completed", ordinal: 1 },
{ id: "newest-finished", status: "waiting", ordinal: 2 },
],
} as never;
expect(resolveLatestMergeBackRun(projection)?.id).toBe("newest-finished");
});
});
@@ -10,6 +10,7 @@ type Run = Projection["runs"][number];
type ProviderSession = Projection["providerSessions"][number];
const ACTIVE_RUN_STATUSES = new Set<Run["status"]>(["preparing", "starting", "running", "waiting"]);
const MERGE_BACK_RUN_STATUSES = new Set<Run["status"]>(["waiting", "completed"]);
export interface QueuedThreadRun {
readonly run: Run;
@@ -27,6 +28,21 @@ export function resolveActiveThreadRun(projection: Projection): Run | null {
return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
}
/**
* A successfully finished provider turn remains in `waiting` while its
* checkpoint is captured. Keep that newest turn available for merge-back
* instead of falling through to an older fully checkpointed run.
*/
export function resolveLatestMergeBackRun(projection: Projection): Run | null {
return projection.runs.reduce<Run | null>(
(latest, run) =>
MERGE_BACK_RUN_STATUSES.has(run.status) && (latest === null || run.ordinal > latest.ordinal)
? run
: latest,
null,
);
}
export function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
const activeRun = resolveActiveThreadRun(projection);
const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;