The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 17:15 UTC
fix(server): a worktree handoff on Claude or Pi completes its run and starts the continuation (#36360)
Co-authored-by: Jake Leventhal <15133828+jakeleventhal@users.noreply.github.com>
Julius Marminge committed
Nov 13, 2026 at 12:55 UTC
af9b4e41dee813626a0b4f03998778a18f077c3a
12 files changed
+334
-204
apps/server/src/mcp/WorktreeMcpService.test.ts
+12
-39
@@ -106,7 +106,6 @@ interface HarnessOptions {
106
readonly threadAttachedOnRecheck?: boolean;
107
readonly threadArchivedOnRecheck?: boolean;
108
readonly threadReadFailsOnRecheck?: boolean;
109
- readonly continuation?: "queued" | "fails" | "dies";
109
readonly projectMissing?: boolean;
110
readonly projectReadFails?: boolean;
111
readonly existingBranchWorktreePath?: string | null;
@@ -179,22 +178,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
178
? Effect.succeed(makeProjection(thread))
179
: Effect.fail(new OrchestratorProjectionError({ threadId: id }));
180
});
182
- const sendToThread = vi.fn((_: unknown) => {
183
- switch (options.continuation ?? "queued") {
184
- case "fails":
185
- return Effect.fail(
186
- new ThreadManagementService.ThreadManagementThreadArchivedError({
187
- threadId,
188
- }),
189
- );
190
- case "dies":
191
- return Effect.die(new Error("send defect"));
192
- default:
193
- return Effect.succeed({
194
- delivery: "queued",
195
- } as ThreadManagementService.ThreadManagementSendResult);
196
- }
197
- });
181
const getById = vi.fn((id: ProjectId) =>
182
options.projectReadFails
183
? (Effect.fail("simulated project read failure") as never)
@@ -298,7 +281,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
281
Layer.mock(ThreadManagementService.ThreadManagementService)({
282
dispatch,
283
getThreadRecords,
301
- sendToThread,
284
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
285
Layer.mock(ProjectService.ProjectService)({
286
getById,
@@ -355,7 +337,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
337
scope,
338
listRefs,
339
dispatch,
358
- sendToThread,
340
fetchWorktreeBaseCommit,
341
createWorktree,
342
removeWorktree,
@@ -398,30 +379,23 @@ const runStatus = (harness: ReturnType<typeof makeHarness>) =>
379
const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
380
381
describe("t3_worktree_handoff", () => {
401
- it.effect("reports a continuation failure without failing the handoff", () => {
402
- const harness = makeHarness({ continuation: "fails" });
382
+ // regression: #22971 a separate send let the detach settle the run before its follow-up existed
383
+ it.effect("commits the continuation with the thread binding", () => {
384
+ const harness = makeHarness();
385
return Effect.gen(function* () {
386
const result = yield* runHandoff(harness, {
405
- branch: "feature/continue-fails",
387
+ branch: "feature/continue",
388
continuationPrompt: "Keep going.",
389
});
408
- expect(result.continuation).toMatchObject({ status: "failed" });
409
- expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails");
410
- expect(harness.dispatch).toHaveBeenCalled();
411
- });
412
- });
413
-
414
- it.effect("does not queue a continuation when the thread update fails", () => {
415
- const harness = makeHarness({ dispatchFails: true });
416
- return Effect.gen(function* () {
417
- const exit = yield* Effect.exit(
418
- runHandoff(harness, {
419
- branch: "feature/dispatch-fails-continue",
420
- continuationPrompt: "Keep going.",
390
+ expect(result.continuation).toEqual({ status: "scheduled", delivery: "queued" });
391
+ expect(harness.dispatch).toHaveBeenCalledTimes(1);
392
+ expect(harness.dispatch).toHaveBeenCalledWith(
393
+ expect.objectContaining({
394
+ type: "thread.metadata.update",
395
+ worktreePath: "/worktrees/project/feature/continue",
396
+ continuation: expect.objectContaining({ text: "Keep going." }),
397
}),
398
);
423
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
424
- expect(harness.sendToThread).not.toHaveBeenCalled();
399
});
400
});
401
@@ -618,7 +592,7 @@ describe("t3_worktree_handoff", () => {
592
});
593
});
594
621
- it.effect("queues the continuation even when interrupted during the binding dispatch", () =>
595
+ it.effect("runs the setup script even when interrupted during the binding dispatch", () =>
596
Effect.gen(function* () {
597
const gate = yield* Deferred.make<void>();
598
const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
@@ -637,7 +611,6 @@ describe("t3_worktree_handoff", () => {
611
yield* Fiber.join(interruption);
612
613
expect(harness.dispatch).toHaveBeenCalledTimes(1);
640
- expect(harness.sendToThread).toHaveBeenCalledTimes(1);
614
expect(harness.runForThread).toHaveBeenCalledTimes(1);
615
}),
616
);
apps/server/src/mcp/WorktreeMcpService.ts
+22
-29
@@ -147,7 +147,6 @@ const make = Effect.gen(function* () {
147
);
148
return {
149
commandId: CommandId.make(part("command", "worktree-handoff")),
150
- continuationCommandId: CommandId.make(part("command", "worktree-continuation")),
150
continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
151
};
152
}),
@@ -293,7 +292,7 @@ const make = Effect.gen(function* () {
292
`Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
293
);
294
}
296
- yield* threadManagement
295
+ return yield* threadManagement
296
.dispatch({
297
type: "thread.metadata.update",
298
commandId: ids.commandId,
@@ -301,6 +300,15 @@ const make = Effect.gen(function* () {
300
branch: worktree.worktree.refName,
301
worktreePath,
302
expectedWorktreePath: null,
303
+ // Binding detaches the session and ends the caller; a later send could lose the race.
304
+ ...(input.continuationPrompt === undefined
305
+ ? {}
306
+ : {
307
+ continuation: {
308
+ messageId: ids.continuationMessageId,
309
+ text: input.continuationPrompt,
310
+ },
311
+ }),
312
})
313
.pipe(
314
Effect.catchCause((cause) =>
@@ -321,33 +329,18 @@ const make = Effect.gen(function* () {
329
),
330
);
331
324
- // Queue continuation immediately after binding; detachment terminates the caller, so relaunch needs a durable message.
325
- const queueContinuation: Effect.Effect<WorktreeMcpContinuationStatus, WorktreeMcpFailure> =
326
- Effect.suspend(() =>
327
- input.continuationPrompt === undefined
328
- ? Effect.succeed<WorktreeMcpContinuationStatus>({ status: "skipped" })
329
- : threadManagement
330
- .sendToThread({
331
- projectId: projection.thread.projectId,
332
- commandId: ids.continuationCommandId,
333
- threadId: scope.thread.threadId,
334
- messageId: ids.continuationMessageId,
335
- text: input.continuationPrompt,
336
- attachments: [],
337
- mode: "queue",
338
- createdBy: "agent",
339
- creationSource: "mcp",
340
- })
341
- .pipe(
342
- Effect.map((sendResult): WorktreeMcpContinuationStatus => ({
343
- status: "scheduled",
344
- delivery: sendResult.delivery,
345
- })),
346
- reportFailed("worktree handoff continuation failed to queue"),
347
- ),
348
- );
349
-
350
- const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
332
+ const bound = yield* recheckAndBind;
333
+ const continuation: WorktreeMcpContinuationStatus =
334
+ input.continuationPrompt === undefined
335
+ ? { status: "skipped" }
336
+ : {
337
+ status: "scheduled",
338
+ delivery: bound.storedEvents.some(
339
+ ({ event }) => event.type === "run.created" && event.payload.status !== "queued",
340
+ )
341
+ ? "started"
342
+ : "queued",
343
+ };
344
345
yield* vcsStatusBroadcaster
346
.refreshStatus(worktreePath)
apps/server/src/orchestration-v2/Orchestrator.ts
+57
-19
@@ -758,6 +758,26 @@ function cancelledAppOwnedTask(
758
};
759
}
760
761
+// A workspace change detaches the session, which can settle the calling run at once. Queuing its
762
+// follow-up in a later command would let a delegated task report its result before that exists.
763
+function metadataUpdateContinuation(
764
+ command: Extract<OrchestrationV2Command, { readonly type: "thread.metadata.update" }>,
765
+): Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }> | undefined {
766
+ return command.continuation === undefined
767
+ ? undefined
768
+ : {
769
+ type: "message.dispatch",
770
+ commandId: command.commandId,
771
+ threadId: command.threadId,
772
+ messageId: command.continuation.messageId,
773
+ text: command.continuation.text,
774
+ attachments: [],
775
+ dispatchMode: { type: "queue_after_active" },
776
+ createdBy: "agent",
777
+ creationSource: "mcp",
778
+ };
779
+}
780
+
781
// Provider wakes can start follow-up work; monitor updates only report progress.
782
// Dispatch takes the parent's lock for follow-ups because intake writes the parent.
783
function mayStartSubagentFollowup(
@@ -6532,6 +6552,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6552
]);
6553
});
6554
6555
+ // Providers own native subagent conversations; messages cannot target them, and adapters ask questions on the parent.
6556
+ const refuseNativeSubagentMessage = Effect.fnUntraced(function* (
6557
+ command: Pick<OrchestrationV2Command, "commandId"> & { readonly threadId: ThreadId },
6558
+ ) {
6559
+ const thread = yield* projectionStore
6560
+ .getThread(command.threadId)
6561
+ .pipe(
6562
+ Effect.mapError(
6563
+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
6564
+ ),
6565
+ );
6566
+ if (isProviderNativeSubagentThread(thread)) {
6567
+ return yield* new OrchestratorSubagentThreadReadOnlyError({
6568
+ commandId: command.commandId,
6569
+ threadId: command.threadId,
6570
+ });
6571
+ }
6572
+ return thread;
6573
+ });
6574
+
6575
const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* (
6576
command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
6577
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -14710,7 +14750,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14750
case "thread.active.reorder":
14751
case "thread.tag.set":
14752
case "thread.mark-unread":
14713
- case "thread.metadata.update":
14753
case "thread.pull-request.link":
14754
case "thread.pull-request.unlink":
14755
case "thread.pull-request-link.sync":
@@ -14723,6 +14762,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14762
case "provider.switch":
14763
yield* dispatchThreadMutation(command, events, effects);
14764
break;
14765
+ case "thread.metadata.update": {
14766
+ const continuation = metadataUpdateContinuation(command);
14767
+ if (continuation !== undefined) yield* refuseNativeSubagentMessage(command);
14768
+ yield* dispatchThreadMutation(command, events, effects);
14769
+ if (continuation !== undefined) {
14770
+ cancelUnsettledEffects = yield* dispatchMessage(continuation, events, effects);
14771
+ yield* recordSubagentFollowup(continuation, events).pipe(mapDispatchError(command));
14772
+ }
14773
+ break;
14774
+ }
14775
case "thread.pull-request-watch.checks-reopen":
14776
yield* dispatchThreadMutation(command, events, effects);
14777
break;
@@ -14743,20 +14792,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14792
yield* dispatchThreadProjectAdoptFolder(command, events);
14793
break;
14794
case "message.dispatch": {
14746
- // Providers own native subagent conversations; messages cannot target them, and adapters ask questions on the parent.
14747
- const thread = yield* projectionStore
14748
- .getThread(command.threadId)
14749
- .pipe(
14750
- Effect.mapError(
14751
- (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
14752
- ),
14753
- );
14754
- if (isProviderNativeSubagentThread(thread)) {
14755
- return yield* new OrchestratorSubagentThreadReadOnlyError({
14756
- commandId: command.commandId,
14757
- threadId: command.threadId,
14758
- });
14759
- }
14795
+ const thread = yield* refuseNativeSubagentMessage(command);
14796
const guestSend =
14797
command.guestMessageId === undefined
14798
? undefined
@@ -15339,11 +15375,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15375
);
15376
// Taken before the lineage read, so a message whose read yields keeps its
15377
// place ahead of later messages to the same thread.
15342
- if (command.type === "message.dispatch")
15378
+ const message =
15379
+ command.type === "thread.metadata.update" ? metadataUpdateContinuation(command) : command;
15380
+ if (message?.type === "message.dispatch")
15381
return yield* messageIntake.withLock(
15344
- command.threadId,
15345
- mayStartSubagentFollowup(command)
15346
- ? withSubagentParentLock(command.threadId, dispatch)
15382
+ message.threadId,
15383
+ mayStartSubagentFollowup(message)
15384
+ ? withSubagentParentLock(message.threadId, dispatch)
15385
: dispatch,
15386
);
15387
// Answering a message-mode question can also start a follow-up.
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+10
-1
@@ -3410,10 +3410,19 @@ it.effect.each(["detach", "stream failure", "provider stop", "early close"] as c
3410
);
3411
yield* interrupts(1);
3412
yield* Deferred.succeed(resume, undefined);
3413
+ const consumed = yield* Fiber.join(consumer);
3414
assert.equal(
3414
- Exit.isFailure(yield* Fiber.join(consumer)),
3415
+ Exit.isFailure(consumed),
3416
release !== "provider stop" && release !== "early close",
3417
);
3418
+ // regression: #22971 only a detach names its thread, so a handoff run can settle on it.
3419
+ assert.equal(
3420
+ Exit.isFailure(consumed)
3421
+ ? (Cause.squash(consumed.cause) as ProviderAdapter.ProviderAdapterEventStreamError)
3422
+ .detachedThreadId
3423
+ : undefined,
3424
+ release === "detach" ? threadId : undefined,
3425
+ );
3426
yield* interrupts(2);
3427
3428
assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+3
@@ -655,10 +655,12 @@ export const layerWithOptions = (
655
detail: string,
656
afterDrain: Effect.Effect<void>,
657
cause?: Cause.Cause<ProviderAdapter.ProviderAdapterV2Error>,
658
+ detachedThreadId?: ThreadId,
659
) {
660
const error = new ProviderAdapter.ProviderAdapterEventStreamError({
661
driver: entry.runtime.driver,
662
providerSessionId: entry.runtime.providerSessionId,
663
+ ...(detachedThreadId === undefined ? {} : { detachedThreadId }),
664
cause: detail,
665
});
666
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
@@ -1280,6 +1282,7 @@ export const layerWithOptions = (
1282
input.detail ?? `Provider session released: ${input.reason}.`,
1283
afterDrain,
1284
input.eventStreamCause,
1285
+ input.detachedThreadId,
1286
);
1287
}
1288
const closeExit = yield* closeScopeWithin(entry.scope, {
apps/server/src/orchestration-v2/RunExecutionService.ts
+57
-14
@@ -546,6 +546,8 @@ export class RunExecutionStartError extends Schema.TaggedError<RunExecutionStart
546
}
547
}
548
549
+const isProviderEventStreamError = Schema.is(ProviderAdapter.ProviderAdapterEventStreamError);
550
+
551
export class RunExecutionIngestError extends Schema.TaggedError<RunExecutionIngestError>()(
552
"RunExecutionIngestError",
553
{
@@ -557,6 +559,7 @@ export class RunExecutionIngestError extends Schema.TaggedError<RunExecutionInge
559
return `Failed while ingesting orchestration V2 run execution ${this.runId}.`;
560
}
561
}
562
+const isRunExecutionIngestError = Schema.is(RunExecutionIngestError);
563
564
export const RunExecutionServiceV2Error = Schema.Union([
565
RunExecutionStartError,
@@ -935,6 +938,12 @@ export const layer: Layer.Layer<
938
),
939
),
940
);
941
+ const failedProviderTurnId =
942
+ input.attempt.providerTurnId ??
943
+ idAllocator.derive.providerTurn({
944
+ driver: input.providerThread.driver,
945
+ nativeTurnId: `failed:${input.attempt.id}`,
946
+ });
947
const makeFailedTerminalEvent = (
948
failure: OrchestrationV2ProviderFailure,
949
failureItemOrdinal: number,
@@ -942,12 +951,7 @@ export const layer: Layer.Layer<
951
type: "turn.terminal",
952
driver: input.providerThread.driver,
953
providerThreadId: input.providerThread.id,
945
- providerTurnId:
946
- input.attempt.providerTurnId ??
947
- idAllocator.derive.providerTurn({
948
- driver: input.providerThread.driver,
949
- nativeTurnId: `failed:${input.attempt.id}`,
950
- }),
954
+ providerTurnId: failedProviderTurnId,
955
runOrdinal: input.run.ordinal,
956
failureItemOrdinal,
957
status: "failed",
@@ -1112,8 +1116,14 @@ export const layer: Layer.Layer<
1116
// Set when ingestion ends or finalization settles the run's open items, which a later
1117
// streaming snapshot must not reopen.
1118
let idleFlushClosed = false;
1119
+ const workspaceHandedOff = Effect.suspend(() =>
1120
+ input.shouldFinalizeRun === undefined || input.hasWorkspaceMoved === undefined
1121
+ ? Effect.succeed(false)
1122
+ : input.hasWorkspaceMoved(),
1123
+ );
1124
const finalizeRootRun = Effect.fn("RunExecutionService.finalizeRootRun")(function* (
1125
terminal: ProviderTerminalEvent,
1126
+ abandonedProviderTurn?: OrchestrationV2ProviderTurn,
1127
) {
1128
if (yield* Ref.get(rootRunFinalized)) {
1129
return;
@@ -1149,6 +1159,7 @@ export const layer: Layer.Layer<
1159
: { loadRunInterruptReason: input.loadRunInterruptReason }),
1160
openRunOwnedSubagents: openSubagents,
1161
openRunOwnedSubagentsTerminal: terminal,
1162
+ ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }),
1163
terminal: settledTerminal,
1164
failureItemPersisted: settledTerminal.status === "failed",
1165
refreshAfterTurn,
@@ -1161,11 +1172,7 @@ export const layer: Layer.Layer<
1172
// for it: the run completes, while its native subagents still settle
1173
// as interrupted. The completed write refuses in the same transaction
1174
// as a stored Stop request, so a racing Stop stays authoritative.
1164
- const handedOff =
1165
- terminal.status === "interrupted" &&
1166
- input.shouldFinalizeRun !== undefined &&
1167
- input.hasWorkspaceMoved !== undefined &&
1168
- (yield* input.hasWorkspaceMoved());
1175
+ const handedOff = terminal.status === "interrupted" && (yield* workspaceHandedOff);
1176
if (!handedOff || !(yield* writeTerminal({ ...terminal, status: "completed" }))) {
1177
yield* writeTerminal(terminal);
1178
}
@@ -1722,14 +1729,51 @@ export const layer: Layer.Layer<
1729
(cause) =>
1730
Effect.gen(function* () {
1731
const completedAt = yield* DateTime.now;
1732
+ const routing = yield* Ref.get(eventRouting);
1733
+ const rootProviderTurn = yield* Ref.get(latestRootProviderTurn);
1734
+ const squashed = Cause.squash(cause);
1735
+ // An exclusive session closes when its thread detaches, and no terminal
1736
+ // follows. The process is gone, so a handoff settles here with no interrupt.
1737
+ if (
1738
+ isRunExecutionIngestError(squashed) &&
1739
+ isProviderEventStreamError(squashed.cause) &&
1740
+ squashed.cause.detachedThreadId === input.run.threadId &&
1741
+ (yield* workspaceHandedOff)
1742
+ ) {
1743
+ const handedOff = yield* finalizeRootRun(
1744
+ {
1745
+ type: "turn.terminal",
1746
+ driver: input.providerThread.driver,
1747
+ providerThreadId: input.providerThread.id,
1748
+ providerTurnId: routing.rootProviderTurnId ?? failedProviderTurnId,
1749
+ runOrdinal: input.run.ordinal,
1750
+ status: "interrupted",
1751
+ failure: null,
1752
+ threadDisposition: "reusable",
1753
+ },
1754
+ rootProviderTurn === null ||
1755
+ isTerminalProviderTurnStatus(rootProviderTurn.status)
1756
+ ? undefined
1757
+ : { ...rootProviderTurn, status: "interrupted", completedAt },
1758
+ ).pipe(
1759
+ Effect.as(true),
1760
+ Effect.catchCauseIf(
1761
+ (settleCause) => !Cause.hasInterruptsOnly(settleCause),
1762
+ (settleCause) =>
1763
+ Effect.logWarning(
1764
+ "orchestration V2 failed to settle a run after its workspace handoff",
1765
+ { runId: input.run.id, cause: settleCause },
1766
+ ).pipe(Effect.as(false)),
1767
+ ),
1768
+ );
1769
+ if (handedOff) return;
1770
+ }
1771
yield* Effect.logWarning("orchestration V2 provider event ingestion failed", {
1772
runId: input.run.id,
1773
cause,
1774
});
1775
if (yield* Ref.get(rootRunFinalized)) return;
1776
const providerThread = yield* Ref.get(latestProviderThread);
1731
- const routing = yield* Ref.get(eventRouting);
1732
- const rootProviderTurn = yield* Ref.get(latestRootProviderTurn);
1777
// Stop background work too; the failed consumer cannot persist terminal events.
1778
const abandonedProviderTurn =
1779
routing.rootProviderTurnId !== null && !routing.rootTurnEnded
@@ -1767,7 +1811,6 @@ export const layer: Layer.Layer<
1811
: null;
1812
const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal);
1813
const openSubagents = yield* Ref.get(openRunOwnedSubagents);
1770
- const squashed = Cause.squash(cause);
1814
let nextRetryWarningAt = completedAt;
1815
yield* writeFinalRunEvents({
1816
run: input.run,
apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
+138
-99
@@ -443,114 +443,153 @@ it.live("retries a failed selection restart session open before completing", ()
443
}),
444
);
445
446
-it.live("a workspace handoff during a run does not leave the run interrupted", () =>
447
- Effect.gen(function* () {
448
- const cwd = yield* checkpointWorkspace("workspace-handoff-lifecycle");
449
- const handoffCwd = yield* checkpointWorkspace("workspace-handoff-lifecycle-target");
450
- const threadId = ThreadId.make("thread:workspace-handoff-lifecycle");
451
- const state = yield* Ref.make<RestartAdapterState>({
452
- activeTurn: null,
453
- opened: [],
454
- started: [],
455
- closedSessionCount: 0,
456
- failedReplacementOpen: false,
457
- });
458
- const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state));
446
+// regression: #22971 an exclusive session closes on detach; that failed the run and held the queue
447
+it.live.each(["pooled", "exclusive"] as const)(
448
+ "a workspace handoff on a %s session completes its run and starts the queued continuation",
449
+ (mode) =>
450
+ Effect.gen(function* () {
451
+ const cwd = yield* checkpointWorkspace(`workspace-handoff-${mode}`);
452
+ const handoffCwd = yield* checkpointWorkspace(`workspace-handoff-${mode}-target`);
453
+ const threadId = ThreadId.make(`thread:workspace-handoff:${mode}`);
454
+ const state = yield* Ref.make<RestartAdapterState>({
455
+ activeTurn: null,
456
+ opened: [],
457
+ started: [],
458
+ closedSessionCount: 0,
459
+ failedReplacementOpen: false,
460
+ });
461
+ const base = makeRestartAdapter(
462
+ state,
463
+ mode === "pooled" ? pooledCapabilities : exclusiveCapabilities,
464
+ );
465
+ // A session that closes on detach is never asked to interrupt: Claude's cannot answer.
466
+ const adapter: ProviderAdapter.ProviderAdapterV2["Service"] =
467
+ mode === "pooled"
468
+ ? base
469
+ : {
470
+ ...base,
471
+ openSession: (input) =>
472
+ base.openSession(input).pipe(
473
+ Effect.map((session) => ({
474
+ ...session,
475
+ interruptTurn: () => Effect.die("an exclusive handoff must not interrupt"),
476
+ })),
477
+ ),
478
+ };
479
+ const layerRegistry = ProviderAdapterRegistry.layerSingle(adapter);
480
460
- const projection = yield* Effect.gen(function* () {
461
- const orchestrator = yield* Orchestrator.OrchestratorV2;
462
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
463
- const eventSink = yield* EventSink.EventSinkV2;
481
+ const projection = yield* Effect.gen(function* () {
482
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
483
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
484
+ const eventSink = yield* EventSink.EventSinkV2;
485
465
- yield* orchestrator.dispatch({
466
- type: "thread.create",
467
- createdBy: "user",
468
- creationSource: "web",
469
- commandId: CommandId.make("command:workspace-handoff:create"),
470
- threadId,
471
- projectId: ProjectId.make("project:workspace-handoff"),
472
- title: "Workspace handoff",
473
- modelSelection: initialSelection,
474
- runtimeMode: "full-access",
475
- interactionMode: "default",
476
- branch: null,
477
- worktreePath: cwd,
478
- });
479
- const running = yield* eventSink
480
- .stream({
486
+ yield* orchestrator.dispatch({
487
+ type: "thread.create",
488
+ createdBy: "user",
489
+ creationSource: "web",
490
+ commandId: CommandId.make("command:workspace-handoff:create"),
491
threadId,
482
- afterSequence: yield* eventSink.latestSequence({ threadId }),
483
- })
484
- .pipe(
485
- Stream.map((stored) => stored.event),
486
- Stream.filter(
487
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
488
- ),
489
- Stream.take(1),
490
- Stream.runDrain,
491
- Effect.forkScoped,
492
- );
493
- yield* orchestrator.dispatch({
494
- type: "message.dispatch",
495
- createdBy: "user",
496
- creationSource: "web",
497
- commandId: CommandId.make("command:workspace-handoff:first"),
498
- threadId,
499
- messageId: MessageId.make("message:workspace-handoff:first"),
500
- text: "move to a worktree",
501
- attachments: [],
502
- modelSelection: initialSelection,
503
- dispatchMode: { type: "start_immediately" },
504
- });
505
- yield* Fiber.join(running);
506
- yield* worker.drain();
492
+ projectId: ProjectId.make("project:workspace-handoff"),
493
+ title: "Workspace handoff",
494
+ modelSelection: initialSelection,
495
+ runtimeMode: "full-access",
496
+ interactionMode: "default",
497
+ branch: null,
498
+ worktreePath: cwd,
499
+ });
500
+ const running = yield* eventSink
501
+ .stream({
502
+ threadId,
503
+ afterSequence: yield* eventSink.latestSequence({ threadId }),
504
+ })
505
+ .pipe(
506
+ Stream.map((stored) => stored.event),
507
+ Stream.filter(
508
+ (event) =>
509
+ event.type === "provider-turn.updated" && event.payload.status === "running",
510
+ ),
511
+ Stream.take(1),
512
+ Stream.runDrain,
513
+ Effect.forkScoped,
514
+ );
515
+ yield* orchestrator.dispatch({
516
+ type: "message.dispatch",
517
+ createdBy: "user",
518
+ creationSource: "web",
519
+ commandId: CommandId.make("command:workspace-handoff:first"),
520
+ threadId,
521
+ messageId: MessageId.make("message:workspace-handoff:first"),
522
+ text: "move to a worktree",
523
+ attachments: [],
524
+ modelSelection: initialSelection,
525
+ dispatchMode: { type: "start_immediately" },
526
+ });
527
+ yield* Fiber.join(running);
528
+ yield* worker.drain();
529
508
- const settled = yield* eventSink
509
- .stream({
530
+ const settled = yield* eventSink
531
+ .stream({
532
+ threadId,
533
+ afterSequence: yield* eventSink.latestSequence({ threadId }),
534
+ })
535
+ .pipe(
536
+ Stream.map((stored) => stored.event),
537
+ Stream.filter(
538
+ (event) =>
539
+ event.type === "run.updated" &&
540
+ event.payload.status !== "running" &&
541
+ event.payload.status !== "queued" &&
542
+ event.payload.status !== "starting",
543
+ ),
544
+ Stream.take(1),
545
+ Stream.runDrain,
546
+ Effect.forkScoped,
547
+ );
548
+ // What t3_worktree_handoff dispatches while the calling turn is still running.
549
+ const bound = yield* orchestrator.dispatch({
550
+ type: "thread.metadata.update",
551
+ commandId: CommandId.make("command:workspace-handoff:rebind"),
552
threadId,
511
- afterSequence: yield* eventSink.latestSequence({ threadId }),
512
- })
513
- .pipe(
514
- Stream.map((stored) => stored.event),
515
- Stream.filter(
516
- (event) =>
517
- event.type === "run.updated" &&
518
- event.payload.status !== "running" &&
519
- event.payload.status !== "queued" &&
520
- event.payload.status !== "starting",
553
+ branch: "repro-handoff",
554
+ worktreePath: handoffCwd,
555
+ continuation: {
556
+ messageId: MessageId.make("message:workspace-handoff:continuation"),
557
+ text: "continue in the worktree",
558
+ },
559
+ });
560
+ // The detach can settle the run at once, so its follow-up must exist in the same commit.
561
+ assert.deepEqual(
562
+ bound.storedEvents.flatMap(({ event }) =>
563
+ event.type === "run.created" ? [event.payload.status] : [],
564
),
522
- Stream.take(1),
523
- Stream.runDrain,
524
- Effect.forkScoped,
565
+ ["queued"],
566
);
526
- // What t3_worktree_handoff dispatches while the calling turn is still running.
527
- yield* orchestrator.dispatch({
528
- type: "thread.metadata.update",
529
- commandId: CommandId.make("command:workspace-handoff:rebind"),
530
- threadId,
531
- branch: "repro-handoff",
532
- worktreePath: handoffCwd,
533
- });
534
- yield* Fiber.join(settled);
535
- yield* worker.drain();
536
- return yield* orchestrator.getThreadProjection(threadId);
537
- }).pipe(
538
- Effect.provide(
539
- ProviderReplayHarness.layerWithRegistry(
540
- { name: "workspace-handoff-lifecycle" },
541
- layerRegistry,
567
+ yield* Fiber.join(settled);
568
+ yield* worker.drain();
569
+ return yield* orchestrator.getThreadProjection(threadId);
570
+ }).pipe(
571
+ Effect.provide(
572
+ ProviderReplayHarness.layerWithRegistry(
573
+ { name: `workspace-handoff-${mode}` },
574
+ layerRegistry,
575
+ ),
576
),
543
- ),
544
- );
577
+ );
578
546
- assert.equal(projection.thread.worktreePath, handoffCwd);
547
- assert.equal(projection.runs[0]?.status, "completed");
548
- assert.isNotNull(projection.runs[0]?.checkpointId ?? null);
549
- assert.isFalse(
550
- projection.turnItems.some((item) => item.type === "run_interrupt_result"),
551
- "an intentional workspace handoff must not project an interrupt result",
552
- );
553
- }),
579
+ assert.equal(projection.thread.worktreePath, handoffCwd);
580
+ assert.equal(projection.runs[0]?.status, "completed");
581
+ assert.isNotNull(projection.runs[0]?.checkpointId ?? null);
582
+ assert.isFalse(
583
+ projection.turnItems.some(
584
+ (item) => item.type === "run_interrupt_result" || item.type === "error",
585
+ ),
586
+ "an intentional workspace handoff must not project an interrupt result or a failure",
587
+ );
588
+ assert.deepEqual(
589
+ (yield* Ref.get(state)).started.map((turn) => turn.cwd),
590
+ [cwd, handoffCwd],
591
+ );
592
+ }),
593
);
594
595
it.live("Stop during a restart interrupts the turn the restart could not stop", () =>
apps/server/src/orchestration-v2/ThreadManagementService.ts
+12
@@ -749,6 +749,18 @@ const make = Effect.gen(function* () {
749
750
const assertDispatchTargetEnabled = (command: OrchestrationV2ServerCommand) => {
751
switch (command.type) {
752
+ case "thread.metadata.update":
753
+ return command.continuation === undefined
754
+ ? Effect.void
755
+ : orchestrator.getThreadRecords(command.threadId, []).pipe(
756
+ Effect.flatMap((projection) =>
757
+ assertProviderInstanceEnabled({
758
+ projectId: projection.thread.projectId,
759
+ commandId: command.commandId,
760
+ instanceId: projection.thread.modelSelection.instanceId,
761
+ }),
762
+ ),
763
+ );
764
case "message.dispatch":
765
return orchestrator.getThreadRecords(command.threadId, []).pipe(
766
Effect.flatMap((projection) =>
apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts
+13
@@ -95,6 +95,19 @@ describe("Claude Agent SDK replay fixtures", () => {
95
userFacingDispatchErrorMessage(refused),
96
"This subagent is run by its provider and cannot take messages. Message the parent thread instead.",
97
);
98
+ const refusedContinuation = yield* orchestrator
99
+ .dispatch({
100
+ type: "thread.metadata.update",
101
+ commandId: CommandId.make("command:subagent:continue-native-child"),
102
+ threadId: child.thread.id,
103
+ title: "Renamed",
104
+ continuation: {
105
+ messageId: MessageId.make("message:subagent:continue-native-child"),
106
+ text: "Also check the tests.",
107
+ },
108
+ })
109
+ .pipe(Effect.flip);
110
+ assert.equal(refusedContinuation._tag, "OrchestratorSubagentThreadReadOnlyError");
111
assert.equal(yield* orchestrator.getThreadEventSequence(child.thread.id), before);
112
const after = yield* orchestrator.getThreadProjection(child.thread.id);
113
assert.lengthOf(after.runs, 0);
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+6
-3
@@ -2004,8 +2004,9 @@ describe("orchestration v2 provider switching", () => {
2004
yield* Deferred.await(started);
2005
yield* Fiber.join(toolCallRunning);
2006
2007
- const runFailed = yield* awaitEvent(
2008
- (event) => event.type === "run.updated" && event.payload.status === "failed",
2007
+ // The handoff itself is not a failure: the run completes once the session closes.
2008
+ const runSettled = yield* awaitEvent(
2009
+ (event) => event.type === "run.updated" && event.payload.status === "waiting",
2010
);
2011
yield* orchestrator.dispatch({
2012
type: "thread.metadata.update",
@@ -2016,9 +2017,11 @@ describe("orchestration v2 provider switching", () => {
2017
expectedWorktreePath: null,
2018
});
2019
yield* worker.drain();
2019
- yield* Fiber.join(runFailed);
2020
+ yield* Fiber.join(runSettled);
2021
+ yield* worker.drain();
2022
2023
const projection = yield* orchestrator.getThreadProjection(scenarioThreadId);
2024
+ assert.equal(projection.runs.at(-1)?.status, "completed");
2025
const toolCall = projection.turnItems.find((item) => item.id === toolCallId);
2026
assert.equal(toolCall?.status, "interrupted");
2027
assert.isNotNull(toolCall?.completedAt);
packages/contracts/src/orchestrationV2.ts
+2
@@ -3210,6 +3210,8 @@ export const OrchestrationV2Command = Schema.Union([
3210
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
3211
expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
3212
expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
3213
+ /** A message queued in the same commit, so a workspace change cannot settle the thread first. */
3214
+ continuation: Schema.optional(Schema.Struct({ messageId: MessageId, text: Schema.String })),
3215
/** Reject unless no message or run has landed on this thread. */
3216
expectedEmpty: Schema.optional(Schema.Boolean),
3217
limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecoveryUpdate)),
packages/provider-core/src/server/ProviderAdapter.ts
+2
@@ -439,6 +439,8 @@ export class ProviderAdapterEventStreamError extends Schema.TaggedError<Provider
439
{
440
driver: ProviderDriverKind,
441
providerSessionId: ProviderSessionId,
442
+ /** Set when T3 closed the session because this thread detached from it, not the provider. */
443
+ detachedThreadId: Schema.optional(ThreadId),
444
cause: Schema.optional(Schema.Defect()),
445
},
446
) {