@devries-cameron20 / t3code-1 / commits / 52c1491c8a
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): successful worktree handoffs complete normally (#24545)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 12:00 UTC 52c1491c8a301e79a25568bbbfdeb59317222fa0
6 files changed +491 -37
apps/server/src/orchestration-v2/EventSink.ts
+24
@@ -3,6 +3,7 @@ import {
3 type OrchestrationV2Run,
4 OrchestrationV2DomainEvent,
5 type OrchestrationV2ProviderThread,
6 + type OrchestrationV2TurnItem,
7 OrchestrationV2StoredEvent,
8 ProviderThreadId,
9 RunAttemptId,
@@ -127,6 +128,11 @@ export interface EventSinkV2Shape {
128 readonly runId: RunId;
129 readonly activeAttemptId: RunAttemptId;
130 readonly expectedStatus: OrchestrationV2Run["status"];
131 + /** Also refuse while this run interrupt request is stored without its result. */
132 + readonly unlessInterruptRequested?: {
133 + readonly requestId: OrchestrationV2TurnItem["id"];
134 + readonly resultId: OrchestrationV2TurnItem["id"];
135 + };
136 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
137 readonly effects?: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
138 }) => Effect.Effect<
@@ -525,6 +531,24 @@ const layerBase: Layer.Layer<
531 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
532 };
533 }
534 + if (input.unlessInterruptRequested !== undefined) {
535 + const { requestId, resultId } = input.unlessInterruptRequested;
536 + const pending = yield* sql<{ readonly pending: number }>`
537 + SELECT EXISTS (
538 + SELECT 1 FROM orchestration_v2_projection_turn_items
539 + WHERE thread_id = ${input.threadId} AND turn_item_id = ${requestId}
540 + ) AND NOT EXISTS (
541 + SELECT 1 FROM orchestration_v2_projection_turn_items
542 + WHERE thread_id = ${input.threadId} AND turn_item_id = ${resultId}
543 + ) AS pending
544 + `;
545 + if (pending[0]?.pending === 1) {
546 + return {
547 + committed: false as const,
548 + storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
549 + };
550 + }
551 + }
552
553 const normalized = yield* normalizeEvents(
554 input.guardPendingUserInputCancellations === true
apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+101
@@ -1984,6 +1984,107 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
1984 }).pipe(Effect.provide(Layer.fresh(layerTest))),
1985 );
1986
1987 + it.effect("refuses a run-current write once an unpaired interrupt request is stored", () =>
1988 + Effect.gen(function* () {
1989 + const eventSink = yield* EventSink.EventSinkV2;
1990 + const now = yield* DateTime.now;
1991 + const threadId = ThreadId.make("thread:foundation-interrupt-guard");
1992 + const runId = RunId.make("run:foundation-interrupt-guard");
1993 + const attemptId = RunAttemptId.make("run-attempt:foundation-interrupt-guard");
1994 + const requestId = TurnItemId.make("turn-item:foundation-interrupt-guard:request");
1995 + const resultId = TurnItemId.make("turn-item:foundation-interrupt-guard:result");
1996 + const run: OrchestrationV2Run = {
1997 + id: runId,
1998 + threadId,
1999 + ordinal: 1,
2000 + providerInstanceId,
2001 + modelSelection,
2002 + providerThreadId: null,
2003 + userMessageId: MessageId.make("message:foundation-interrupt-guard"),
2004 + rootNodeId: null,
2005 + activeAttemptId: attemptId,
2006 + status: "running",
2007 + queuePosition: null,
2008 + requestedAt: now,
2009 + startedAt: now,
2010 + completedAt: null,
2011 + checkpointId: null,
2012 + contextHandoffId: null,
2013 + };
2014 + yield* eventSink.write({
2015 + events: [
2016 + threadCreatedEvent({
2017 + id: "event:foundation-interrupt-guard:thread",
2018 + thread: makeThread(threadId, now),
2019 + now,
2020 + }),
2021 + {
2022 + id: EventId.make("event:foundation-interrupt-guard:run"),
2023 + type: "run.created",
2024 + threadId,
2025 + runId,
2026 + providerInstanceId,
2027 + occurredAt: now,
2028 + payload: run,
2029 + },
2030 + ],
2031 + });
2032 + const signalItem = (id: TurnItemId, type: "run_interrupt_request" | "run_interrupt_result") =>
2033 + ({
2034 + id: EventId.make(`event:${id}`),
2035 + type: "turn-item.updated",
2036 + threadId,
2037 + runId,
2038 + occurredAt: now,
2039 + payload: {
2040 + id,
2041 + threadId,
2042 + runId,
2043 + nodeId: null,
2044 + providerThreadId: null,
2045 + providerTurnId: null,
2046 + nativeItemRef: null,
2047 + parentItemId: null,
2048 + ordinal: 1,
2049 + status: "completed",
2050 + title: "Interrupt",
2051 + startedAt: now,
2052 + completedAt: now,
2053 + updatedAt: now,
2054 + type,
2055 + message: "Stopped",
2056 + },
2057 + }) as OrchestrationV2DomainEvent;
2058 + const completeRun = (suffix: string) =>
2059 + eventSink.writeIfRunCurrent({
2060 + threadId,
2061 + runId,
2062 + activeAttemptId: attemptId,
2063 + expectedStatus: "running",
2064 + unlessInterruptRequested: { requestId, resultId },
2065 + events: [
2066 + {
2067 + id: EventId.make(`event:foundation-interrupt-guard:waiting:${suffix}`),
2068 + type: "run.updated",
2069 + threadId,
2070 + runId,
2071 + providerInstanceId,
2072 + occurredAt: now,
2073 + payload: { ...run, status: "waiting" },
2074 + },
2075 + ],
2076 + });
2077 +
2078 + yield* eventSink.write({ events: [signalItem(requestId, "run_interrupt_request")] });
2079 + const refused = yield* completeRun("refused");
2080 + assert.isFalse(refused.committed);
2081 + assert.deepEqual(refused.storedEvents, []);
2082 +
2083 + yield* eventSink.write({ events: [signalItem(resultId, "run_interrupt_result")] });
2084 + assert.isTrue((yield* completeRun("paired")).committed);
2085 + }).pipe(Effect.provide(Layer.fresh(layerTest))),
2086 + );
2087 +
2088 it.effect("guards post-terminal provider-thread writes by attempt and run ordinal", () =>
2089 Effect.gen(function* () {
2090 const eventSink = yield* EventSink.EventSinkV2;
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+8
@@ -236,6 +236,7 @@ export const layer: Layer.Layer<
236 readonly attemptId: OrchestrationV2RunAttempt["id"];
237 readonly providerThreadId: OrchestrationV2ProviderThread["id"];
238 readonly runOrdinal: number;
239 + readonly worktreePath: string | null;
240 readonly inheritedBackgroundTurnItems: ReturnType<
241 typeof RunExecutionService.selectInheritedBackgroundTurnItems
242 >;
@@ -281,6 +282,11 @@ export const layer: Layer.Layer<
282 }),
283 )
284 .pipe(Effect.catchCause(() => Effect.succeed(false))),
285 + hasWorkspaceMoved: () =>
286 + projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe(
287 + Effect.map((current) => current.thread.worktreePath !== input.worktreePath),
288 + Effect.catchCause(() => Effect.succeed(false)),
289 + ),
290 loadRunInterruptReason: () =>
291 projectionStore
292 .getThreadRecords(input.threadId, ["turnItems"], {
@@ -692,6 +698,7 @@ export const layer: Layer.Layer<
698 attemptId: attempt.id,
699 providerThreadId: providerThread.id,
700 runOrdinal: run.ordinal,
701 + worktreePath: projection.thread.worktreePath,
702 inheritedBackgroundTurnItems,
703 });
704 const { isCurrentAttemptInStatus } = runControls;
@@ -1766,6 +1773,7 @@ export const layer: Layer.Layer<
1773 shouldFinalizeRun: runControls.shouldFinalizeRun,
1774 hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest,
1775 loadRunInterruptReason: runControls.loadRunInterruptReason,
1776 + hasWorkspaceMoved: runControls.hasWorkspaceMoved,
1777 message: {
1778 messageId: message.id,
1779 text: userText,
apps/server/src/orchestration-v2/RunExecutionService.test.ts
+172
@@ -2580,6 +2580,143 @@ it.effect(
2580 }),
2581 );
2582
2583 +it.effect("settles native subagents when a workspace handoff completes the root run", () =>
2584 + Effect.gen(function* () {
2585 + const ids = backgroundScenarioIds("subagent-workspace-handoff");
2586 + const providerInstanceId = ProviderInstanceId.make("codex");
2587 + const written = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);
2588 + const ingestionDone = yield* Deferred.make<void>();
2589 + const layerTest = RunExecutionService.layer.pipe(
2590 + Layer.provide(
2591 + Layer.mergeAll(
2592 + McpAppModelContext.layerEmpty,
2593 + PreviewAgentActivity.layer,
2594 + Layer.mock(CheckpointService.CheckpointServiceV2)({
2595 + captureBaseline: () => Effect.void,
2596 + }),
2597 + layerTurnItemPositionsTest,
2598 + mockEventSink({
2599 + write: () => Effect.succeed([]),
2600 + writeWithEffects: (input) =>
2601 + Ref.update(written, (current) => [...current, ...input.events]).pipe(Effect.as([])),
2602 + writeIfRunCurrent: (input) =>
2603 + Ref.update(written, (current) => [...current, ...input.events]).pipe(
2604 + Effect.as({ committed: true, storedEvents: [] }),
2605 + ),
2606 + }),
2607 + IdAllocator.layer,
2608 + Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({
2609 + ingestNormalized: () => Effect.succeed([]),
2610 + }),
2611 + ServerSettings.layerTest(),
2612 + ),
2613 + ),
2614 + );
2615 + const fixture = {
2616 + ids,
2617 + providerInstanceId,
2618 + childThreadId: ids.childThreadId,
2619 + driver,
2620 + status: "running",
2621 + } as const;
2622 + const runningSubagent = makeRunOwnedSubagentFixture(fixture);
2623 + const runningTurnItem = makeRunOwnedSubagentTurnItemFixture(fixture);
2624 + const runningNode = makeRunOwnedSubagentNodeFixture({ ids, status: "running" });
2625 + const runningChildNode = makeRunOwnedSubagentChildNodeFixture({ ids, status: "running" });
2626 +
2627 + yield* Effect.gen(function* () {
2628 + const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
2629 + yield* runExecution.startRootRun({
2630 + commandId: CommandId.make("command:subagent-workspace-handoff"),
2631 + appThread: rootAppThread(ids.threadId),
2632 + providerSessionId: ProviderSessionId.make("session:subagent-workspace-handoff"),
2633 + session: {
2634 + events: Stream.empty,
2635 + subscribeEvents: Effect.succeed({
2636 + // The provider event stream stays open: only settled children may end ingestion.
2637 + events: Stream.concat(
2638 + Stream.fromIterable([
2639 + childThreadCreatedEvent(ids),
2640 + { type: "subagent.updated", driver, subagent: runningSubagent },
2641 + { type: "node.updated", driver, node: runningNode },
2642 + { type: "node.updated", driver, node: runningChildNode },
2643 + { type: "turn_item.updated", driver, turnItem: runningTurnItem },
2644 + rootTerminalEvent(ids, "interrupted"),
2645 + ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>),
2646 + Stream.never,
2647 + ),
2648 + close: Deferred.succeed(ingestionDone, undefined),
2649 + }),
2650 + startTurn: () => Effect.void,
2651 + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime,
2652 + run: {
2653 + id: ids.runId,
2654 + threadId: ids.threadId,
2655 + ordinal: 1,
2656 + providerInstanceId,
2657 + } as OrchestrationV2Run,
2658 + rootNode: { id: ids.rootNodeId } as OrchestrationV2ExecutionNode,
2659 + checkpointScope: {
2660 + id: CheckpointScopeId.make("checkpoint-scope:subagent-workspace-handoff"),
2661 + } as OrchestrationV2CheckpointScope,
2662 + providerThread: { id: ids.providerThreadId, driver } as OrchestrationV2ProviderThread,
2663 + attempt: {
2664 + id: ids.attemptId,
2665 + providerTurnId: ids.rootProviderTurnId,
2666 + } as OrchestrationV2RunAttempt,
2667 + attemptId: ids.attemptId,
2668 + providerTurnOrdinal: 1,
2669 + shouldFinalizeRun: () => Effect.succeed(true),
2670 + hasWorkspaceMoved: () => Effect.succeed(true),
2671 + message: {
2672 + messageId: MessageId.make("message:subagent-workspace-handoff:user"),
2673 + text: "Spawn a subagent then move to a worktree.",
2674 + attachments: [],
2675 + createdBy: "user",
2676 + creationSource: "web",
2677 + },
2678 + modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
2679 + runtimePolicy: {
2680 + runtimeMode: "full-access",
2681 + interactionMode: "default",
2682 + cwd: process.cwd(),
2683 + approvalPolicy: "never",
2684 + sandboxPolicy: {
2685 + type: "readOnly",
2686 + access: { type: "fullAccess" },
2687 + networkAccess: false,
2688 + },
2689 + },
2690 + });
2691 + }).pipe(Effect.provide(layerTest));
2692 +
2693 + const closed = yield* Deferred.await(ingestionDone).pipe(Effect.timeoutOption("2 seconds"));
2694 + assert.isTrue(Option.isSome(closed), "settled children must end event ingestion");
2695 +
2696 + const events = yield* Ref.get(written);
2697 + const statusOf = (type: OrchestrationV2DomainEvent["type"], id: string) =>
2698 + events.flatMap((event) => {
2699 + if (event.type !== type) return [];
2700 + const payload = (
2701 + event as { readonly payload: { readonly id: string; readonly status: string } }
2702 + ).payload;
2703 + return payload.id === id ? [payload.status] : [];
2704 + });
2705 + assert.deepEqual(statusOf("subagent.updated", runningSubagent.id), ["interrupted"]);
2706 + assert.deepEqual(statusOf("turn-item.updated", runningTurnItem.id), ["interrupted"]);
2707 + assert.deepEqual(statusOf("node.updated", runningNode.id), ["interrupted"]);
2708 + assert.deepEqual(statusOf("node.updated", runningChildNode.id), ["interrupted"]);
2709 + assert.deepEqual(statusOf("run.updated", ids.runId), ["waiting"]);
2710 + assert.deepEqual(statusOf("run-attempt.updated", ids.attemptId), ["completed"]);
2711 + assert.isFalse(
2712 + events.some(
2713 + (event) =>
2714 + event.type === "turn-item.updated" && event.payload.type === "run_interrupt_result",
2715 + ),
2716 + );
2717 + }),
2718 +);
2719 +
2720 it.effect("omits interrupt results and subagent cascade for a superseded attempt", () =>
2721 Effect.gen(function* () {
2722 const { written, observed } = yield* captureRootRunTermination({
@@ -2619,6 +2756,37 @@ it.effect("emits run_interrupt_result when superseded attempt still has a hard-s
2756 }),
2757 );
2758
2759 +it.effect("keeps a Stop that commits while a workspace handoff completes the run", () =>
2760 + Effect.gen(function* () {
2761 + const stopCommitted = yield* Ref.make(false);
2762 + const { written, finalEvents, committedEffects } = yield* captureRootRunTermination({
2763 + key: "stop-races-workspace-handoff",
2764 + shouldFinalizeRun: () => Effect.succeed(true),
2765 + // Stop commits after the handoff is detected and before the terminal write.
2766 + hasWorkspaceMoved: () => Ref.set(stopCommitted, true).pipe(Effect.as(true)),
2767 + // The sink refuses a guarded write once the Stop request is stored.
2768 + beforeTerminalWrite: (request) =>
2769 + Ref.get(stopCommitted).pipe(
2770 + Effect.map((stopped) => !(stopped && request.unlessInterruptRequested !== undefined)),
2771 + ),
2772 + });
2773 + const statuses = (type: OrchestrationV2DomainEvent["type"]) =>
2774 + finalEvents.flatMap((event) =>
2775 + event.type === type ? [(event.payload as { readonly status: string }).status] : [],
2776 + );
2777 + assert.deepEqual(statuses("run.updated"), ["interrupted"]);
2778 + assert.deepEqual(statuses("run-attempt.updated"), ["interrupted"]);
2779 + assert.deepEqual(
2780 + written.map((item) => item.type),
2781 + ["run_interrupt_result"],
2782 + );
2783 + assert.deepEqual(
2784 + committedEffects.map((effect) => effect.request.type),
2785 + ["checkpoint.capture"],
2786 + );
2787 + }),
2788 +);
2789 +
2790 it.effect("does not overwrite Stop when ownership changes after the finalization read", () =>
2791 Effect.gen(function* () {
2792 const { written, observed, submittedEffects, committedEffects } =
@@ -3180,6 +3348,7 @@ function captureRootRunTermination(input: {
3348 readonly shouldFinalizeRun: () => Effect.Effect<boolean, ProjectionStore.ProjectionStoreV2Error>;
3349 readonly rejectTerminalWrite?: boolean;
3350 readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
3351 + readonly hasWorkspaceMoved?: () => Effect.Effect<boolean, never>;
3352 readonly loadRunInterruptReason?: () => Effect.Effect<string | undefined, never>;
3353 readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"];
3354 readonly seedOpenSubagent?: boolean;
@@ -3376,6 +3545,9 @@ function captureRootRunTermination(input: {
3545 : {
3546 hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
3547 }),
3548 + ...(input.hasWorkspaceMoved === undefined
3549 + ? {}
3550 + : { hasWorkspaceMoved: input.hasWorkspaceMoved }),
3551 message: {
3552 messageId: MessageId.make(`message:${input.key}`),
3553 text: "interrupt projection",
apps/server/src/orchestration-v2/RunExecutionService.ts
+73 -37
@@ -586,6 +586,7 @@ export interface RunExecutionServiceV2StartRootRunInput {
586 readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
587 readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
588 readonly loadRunInterruptReason?: () => Effect.Effect<string | undefined, never>;
589 + readonly hasWorkspaceMoved?: () => Effect.Effect<boolean, never>;
590 readonly message: ProviderAdapter.ProviderAdapterV2TurnMessage;
591 readonly modelSelection: ModelSelection;
592 readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
@@ -639,6 +640,7 @@ export const layer: Layer.Layer<
640 readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
641 readonly loadRunInterruptReason?: () => Effect.Effect<string | undefined, never>;
642 readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
643 + readonly openRunOwnedSubagentsTerminal?: ProviderTerminalEvent;
644 // Root turn snapshot written with the run when T3 ends the run itself.
645 readonly abandonedProviderTurn?: OrchestrationV2ProviderTurn;
646 readonly terminal: ProviderTerminalEvent;
@@ -648,6 +650,7 @@ export const layer: Layer.Layer<
650 readonly writeIfRunCurrent?: {
651 readonly activeAttemptId: RunAttemptId;
652 readonly expectedStatus: OrchestrationV2Run["status"];
653 + readonly unlessInterruptRequested?: boolean;
654 };
655 }) {
656 const completedAt = input.completedAt ?? (yield* DateTime.now);
@@ -694,7 +697,7 @@ export const layer: Layer.Layer<
697 yield* input.refreshAfterTurn;
698 }
699 }
697 - return;
700 + return false;
701 }
702 const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId });
703 const reason =
@@ -709,14 +712,15 @@ export const layer: Layer.Layer<
712 open.turnItems.size > 0 ||
713 open.childTurnItems.size > 0 ||
714 open.nodes.size > 0;
715 + const subagentTerminal = input.openRunOwnedSubagentsTerminal ?? input.terminal;
716 const cascadedSubagentEvents =
713 - isRunOwnedSubagentTerminalStatus(input.terminal.status) &&
714 - !childTurnsContinue(input.terminal) &&
717 + isRunOwnedSubagentTerminalStatus(subagentTerminal.status) &&
718 + !childTurnsContinue(subagentTerminal) &&
719 hasOpenSubagentProjection
720 ? yield* cascadeTerminalizeRunOwnedSubagents({
721 run: input.run,
722 open,
719 - status: input.terminal.status,
723 + status: subagentTerminal.status,
724 completedAt,
725 allocateEventId,
726 })
@@ -874,11 +878,25 @@ export const layer: Layer.Layer<
878 runId: input.run.id,
879 activeAttemptId: input.writeIfRunCurrent.activeAttemptId,
880 expectedStatus: input.writeIfRunCurrent.expectedStatus,
881 + ...(input.writeIfRunCurrent.unlessInterruptRequested === true
882 + ? {
883 + unlessInterruptRequested: {
884 + requestId: idAllocator.derive.runSignalTurnItem({
885 + runId: input.run.id,
886 + signal: "interrupt-request",
887 + }),
888 + resultId: idAllocator.derive.runSignalTurnItem({
889 + runId: input.run.id,
890 + signal: "interrupt-result",
891 + }),
892 + },
893 + }
894 + : {}),
895 events: finalization.events,
896 effects: finalization.effects,
897 });
898 if (!result.committed) {
881 - return;
899 + return false;
900 }
901 } else {
902 yield* eventSink.writeWithEffects(finalization);
@@ -890,6 +908,7 @@ export const layer: Layer.Layer<
908 childrenRunning: hasOpenSubagentProjection && cascadedSubagentEvents.length === 0,
909 });
910 yield* input.refreshAfterTurn;
911 + return true;
912 },
913 );
914
@@ -1097,38 +1116,55 @@ export const layer: Layer.Layer<
1116 }
1117 const providerThread = yield* Ref.get(latestProviderThread);
1118 const openSubagents = yield* Ref.get(openRunOwnedSubagents);
1100 - yield* writeFinalRunEvents({
1101 - run: input.run,
1102 - rootNode: input.rootNode,
1103 - checkpointScope: input.checkpointScope,
1104 - providerThread,
1105 - attempt: input.attempt,
1106 - ...(input.shouldFinalizeRun === undefined
1107 - ? {}
1108 - : {
1109 - shouldFinalizeRun: input.shouldFinalizeRun,
1110 - // Stop may commit between the ownership read and this
1111 - // terminal write. Gate the events and checkpoint together.
1112 - writeIfRunCurrent: {
1113 - activeAttemptId: input.attempt.id,
1114 - expectedStatus: "running" as const,
1115 - },
1116 - }),
1117 - ...(input.hasUnpairedRunInterruptRequest === undefined
1118 - ? {}
1119 - : {
1120 - hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
1121 - }),
1122 - ...(input.loadRunInterruptReason === undefined
1123 - ? {}
1124 - : { loadRunInterruptReason: input.loadRunInterruptReason }),
1125 - openRunOwnedSubagents: openSubagents,
1126 - terminal,
1127 - failureItemPersisted: terminal.status === "failed",
1128 - refreshAfterTurn,
1129 - }).pipe(
1130 - Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
1131 - );
1119 + const writeTerminal = (settledTerminal: ProviderTerminalEvent) =>
1120 + writeFinalRunEvents({
1121 + run: input.run,
1122 + rootNode: input.rootNode,
1123 + checkpointScope: input.checkpointScope,
1124 + providerThread,
1125 + attempt: input.attempt,
1126 + ...(input.shouldFinalizeRun === undefined
1127 + ? {}
1128 + : {
1129 + shouldFinalizeRun: input.shouldFinalizeRun,
1130 + // Stop may commit between the ownership read and this
1131 + // terminal write. Gate the events and checkpoint together.
1132 + writeIfRunCurrent: {
1133 + activeAttemptId: input.attempt.id,
1134 + expectedStatus: "running" as const,
1135 + unlessInterruptRequested: settledTerminal !== terminal,
1136 + },
1137 + }),
1138 + ...(input.hasUnpairedRunInterruptRequest === undefined
1139 + ? {}
1140 + : {
1141 + hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
1142 + }),
1143 + ...(input.loadRunInterruptReason === undefined
1144 + ? {}
1145 + : { loadRunInterruptReason: input.loadRunInterruptReason }),
1146 + openRunOwnedSubagents: openSubagents,
1147 + openRunOwnedSubagentsTerminal: terminal,
1148 + terminal: settledTerminal,
1149 + failureItemPersisted: settledTerminal.status === "failed",
1150 + refreshAfterTurn,
1151 + }).pipe(
1152 + Effect.mapError(
1153 + (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
1154 + ),
1155 + );
1156 + // A workspace handoff detaches the session and stops the turn that asked
1157 + // for it: the run completes, while its native subagents still settle
1158 + // as interrupted. The completed write refuses in the same transaction
1159 + // as a stored Stop request, so a racing Stop stays authoritative.
1160 + const handedOff =
1161 + terminal.status === "interrupted" &&
1162 + input.shouldFinalizeRun !== undefined &&
1163 + input.hasWorkspaceMoved !== undefined &&
1164 + (yield* input.hasWorkspaceMoved());
1165 + if (!handedOff || !(yield* writeTerminal({ ...terminal, status: "completed" }))) {
1166 + yield* writeTerminal(terminal);
1167 + }
1168 if (isRunOwnedSubagentTerminalStatus(terminal.status) && !childTurnsContinue(terminal)) {
1169 yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
1170 idleFlushClosed = true;
apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
+113
@@ -446,6 +446,119 @@ it.live("retries a failed selection restart session open before completing", ()
446 ),
447 );
448
449 +it.live("a workspace handoff during a run does not leave the run interrupted", () =>
450 + Effect.scoped(
451 + Effect.gen(function* () {
452 + const cwd = yield* checkpointWorkspace("workspace-handoff-lifecycle");
453 + const handoffCwd = yield* checkpointWorkspace("workspace-handoff-lifecycle-target");
454 + const threadId = ThreadId.make("thread:workspace-handoff-lifecycle");
455 + const state = yield* Ref.make<RestartAdapterState>({
456 + activeTurn: null,
457 + opened: [],
458 + started: [],
459 + closedSessionCount: 0,
460 + failedReplacementOpen: false,
461 + });
462 + const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state));
463 +
464 + const projection = yield* Effect.gen(function* () {
465 + const orchestrator = yield* Orchestrator.OrchestratorV2;
466 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
467 + const eventSink = yield* EventSink.EventSinkV2;
468 +
469 + yield* orchestrator.dispatch({
470 + type: "thread.create",
471 + createdBy: "user",
472 + creationSource: "web",
473 + commandId: CommandId.make("command:workspace-handoff:create"),
474 + threadId,
475 + projectId: ProjectId.make("project:workspace-handoff"),
476 + title: "Workspace handoff",
477 + modelSelection: initialSelection,
478 + runtimeMode: "full-access",
479 + interactionMode: "default",
480 + branch: null,
481 + worktreePath: cwd,
482 + });
483 + const running = yield* eventSink
484 + .stream({
485 + threadId,
486 + afterSequence: yield* eventSink.latestSequence({ threadId }),
487 + })
488 + .pipe(
489 + Stream.map((stored) => stored.event),
490 + Stream.filter(
491 + (event) =>
492 + event.type === "provider-turn.updated" && event.payload.status === "running",
493 + ),
494 + Stream.take(1),
495 + Stream.runDrain,
496 + Effect.forkScoped,
497 + );
498 + yield* orchestrator.dispatch({
499 + type: "message.dispatch",
500 + createdBy: "user",
501 + creationSource: "web",
502 + commandId: CommandId.make("command:workspace-handoff:first"),
503 + threadId,
504 + messageId: MessageId.make("message:workspace-handoff:first"),
505 + text: "move to a worktree",
506 + attachments: [],
507 + modelSelection: initialSelection,
508 + dispatchMode: { type: "start_immediately" },
509 + });
510 + yield* Fiber.join(running);
511 + yield* worker.drain();
512 +
513 + const settled = yield* eventSink
514 + .stream({
515 + threadId,
516 + afterSequence: yield* eventSink.latestSequence({ threadId }),
517 + })
518 + .pipe(
519 + Stream.map((stored) => stored.event),
520 + Stream.filter(
521 + (event) =>
522 + event.type === "run.updated" &&
523 + event.payload.status !== "running" &&
524 + event.payload.status !== "queued" &&
525 + event.payload.status !== "starting",
526 + ),
527 + Stream.take(1),
528 + Stream.runDrain,
529 + Effect.forkScoped,
530 + );
531 + // What t3_worktree_handoff dispatches while the calling turn is still running.
532 + yield* orchestrator.dispatch({
533 + type: "thread.metadata.update",
534 + commandId: CommandId.make("command:workspace-handoff:rebind"),
535 + threadId,
536 + branch: "repro-handoff",
537 + worktreePath: handoffCwd,
538 + });
539 + yield* Fiber.join(settled);
540 + yield* worker.drain();
541 + return yield* orchestrator.getThreadProjection(threadId);
542 + }).pipe(
543 + Effect.provide(
544 + ProviderReplayHarness.layerWithRegistry(
545 + { name: "workspace-handoff-lifecycle" },
546 + layerRegistry,
547 + ),
548 + ),
549 + );
550 +
551 + assert.equal(projection.thread.worktreePath, handoffCwd);
552 + assert.equal(projection.runs[0]?.status, "completed");
553 + assert.isNotNull(projection.runs[0]?.checkpointId ?? null);
554 + assert.isFalse(
555 + projection.turnItems.some((item) => item.type === "run_interrupt_result"),
556 + "an intentional workspace handoff must not project an interrupt result",
557 + );
558 + }),
559 + ),
560 +);
561 +
562 it.live("Stop during a restart interrupts the turn the restart could not stop", () =>
563 Effect.scoped(
564 Effect.gen(function* () {