Skip to content

Commit af9b4e4

Browse files
fix(server): a worktree handoff on Claude or Pi completes its run and starts the continuation (#36360)
Co-authored-by: Jake Leventhal <[email protected]>
1 parent 9a455f0 commit af9b4e4

12 files changed

Lines changed: 334 additions & 204 deletions

‎apps/server/src/mcp/WorktreeMcpService.test.ts‎

Lines changed: 12 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ interface HarnessOptions {
106106
readonly threadAttachedOnRecheck?: boolean;
107107
readonly threadArchivedOnRecheck?: boolean;
108108
readonly threadReadFailsOnRecheck?: boolean;
109-
readonly continuation?: "queued" | "fails" | "dies";
110109
readonly projectMissing?: boolean;
111110
readonly projectReadFails?: boolean;
112111
readonly existingBranchWorktreePath?: string | null;
@@ -179,22 +178,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
179178
? Effect.succeed(makeProjection(thread))
180179
: Effect.fail(new OrchestratorProjectionError({ threadId: id }));
181180
});
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-
});
198181
const getById = vi.fn((id: ProjectId) =>
199182
options.projectReadFails
200183
? (Effect.fail("simulated project read failure") as never)
@@ -298,7 +281,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
298281
Layer.mock(ThreadManagementService.ThreadManagementService)({
299282
dispatch,
300283
getThreadRecords,
301-
sendToThread,
302284
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
303285
Layer.mock(ProjectService.ProjectService)({
304286
getById,
@@ -355,7 +337,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
355337
scope,
356338
listRefs,
357339
dispatch,
358-
sendToThread,
359340
fetchWorktreeBaseCommit,
360341
createWorktree,
361342
removeWorktree,
@@ -398,30 +379,23 @@ const runStatus = (harness: ReturnType<typeof makeHarness>) =>
398379
const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput);
399380

400381
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();
403385
return Effect.gen(function* () {
404386
const result = yield* runHandoff(harness, {
405-
branch: "feature/continue-fails",
387+
branch: "feature/continue",
406388
continuationPrompt: "Keep going.",
407389
});
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." }),
421397
}),
422398
);
423-
expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
424-
expect(harness.sendToThread).not.toHaveBeenCalled();
425399
});
426400
});
427401

@@ -618,7 +592,7 @@ describe("t3_worktree_handoff", () => {
618592
});
619593
});
620594

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", () =>
622596
Effect.gen(function* () {
623597
const gate = yield* Deferred.make<void>();
624598
const harness = makeHarness({ dispatchGate: Deferred.await(gate) });
@@ -637,7 +611,6 @@ describe("t3_worktree_handoff", () => {
637611
yield* Fiber.join(interruption);
638612

639613
expect(harness.dispatch).toHaveBeenCalledTimes(1);
640-
expect(harness.sendToThread).toHaveBeenCalledTimes(1);
641614
expect(harness.runForThread).toHaveBeenCalledTimes(1);
642615
}),
643616
);

‎apps/server/src/mcp/WorktreeMcpService.ts‎

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,6 @@ const make = Effect.gen(function* () {
147147
);
148148
return {
149149
commandId: CommandId.make(part("command", "worktree-handoff")),
150-
continuationCommandId: CommandId.make(part("command", "worktree-continuation")),
151150
continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
152151
};
153152
}),
@@ -293,14 +292,23 @@ const make = Effect.gen(function* () {
293292
`Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
294293
);
295294
}
296-
yield* threadManagement
295+
return yield* threadManagement
297296
.dispatch({
298297
type: "thread.metadata.update",
299298
commandId: ids.commandId,
300299
threadId: scope.thread.threadId,
301300
branch: worktree.worktree.refName,
302301
worktreePath,
303302
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+
}),
304312
})
305313
.pipe(
306314
Effect.catchCause((cause) =>
@@ -321,33 +329,18 @@ const make = Effect.gen(function* () {
321329
),
322330
);
323331

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+
};
351344

352345
yield* vcsStatusBroadcaster
353346
.refreshStatus(worktreePath)

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 57 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,26 @@ function cancelledAppOwnedTask(
758758
};
759759
}
760760

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+
761781
// Provider wakes can start follow-up work; monitor updates only report progress.
762782
// Dispatch takes the parent's lock for follow-ups because intake writes the parent.
763783
function mayStartSubagentFollowup(
@@ -6532,6 +6552,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
65326552
]);
65336553
});
65346554

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+
65356575
const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* (
65366576
command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
65376577
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -14710,7 +14750,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1471014750
case "thread.active.reorder":
1471114751
case "thread.tag.set":
1471214752
case "thread.mark-unread":
14713-
case "thread.metadata.update":
1471414753
case "thread.pull-request.link":
1471514754
case "thread.pull-request.unlink":
1471614755
case "thread.pull-request-link.sync":
@@ -14723,6 +14762,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1472314762
case "provider.switch":
1472414763
yield* dispatchThreadMutation(command, events, effects);
1472514764
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+
}
1472614775
case "thread.pull-request-watch.checks-reopen":
1472714776
yield* dispatchThreadMutation(command, events, effects);
1472814777
break;
@@ -14743,20 +14792,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1474314792
yield* dispatchThreadProjectAdoptFolder(command, events);
1474414793
break;
1474514794
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);
1476014796
const guestSend =
1476114797
command.guestMessageId === undefined
1476214798
? undefined
@@ -15339,11 +15375,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1533915375
);
1534015376
// Taken before the lineage read, so a message whose read yields keeps its
1534115377
// 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")
1534315381
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)
1534715385
: dispatch,
1534815386
);
1534915387
// Answering a message-mode question can also start a follow-up.

‎apps/server/src/orchestration-v2/ProviderSessionManager.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3410,10 +3410,19 @@ it.effect.each(["detach", "stream failure", "provider stop", "early close"] as c
34103410
);
34113411
yield* interrupts(1);
34123412
yield* Deferred.succeed(resume, undefined);
3413+
const consumed = yield* Fiber.join(consumer);
34133414
assert.equal(
3414-
Exit.isFailure(yield* Fiber.join(consumer)),
3415+
Exit.isFailure(consumed),
34153416
release !== "provider stop" && release !== "early close",
34163417
);
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+
);
34173426
yield* interrupts(2);
34183427

34193428
assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));

‎apps/server/src/orchestration-v2/ProviderSessionManager.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -655,10 +655,12 @@ export const layerWithOptions = (
655655
detail: string,
656656
afterDrain: Effect.Effect<void>,
657657
cause?: Cause.Cause<ProviderAdapter.ProviderAdapterV2Error>,
658+
detachedThreadId?: ThreadId,
658659
) {
659660
const error = new ProviderAdapter.ProviderAdapterEventStreamError({
660661
driver: entry.runtime.driver,
661662
providerSessionId: entry.runtime.providerSessionId,
663+
...(detachedThreadId === undefined ? {} : { detachedThreadId }),
662664
cause: detail,
663665
});
664666
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
@@ -1280,6 +1282,7 @@ export const layerWithOptions = (
12801282
input.detail ?? `Provider session released: ${input.reason}.`,
12811283
afterDrain,
12821284
input.eventStreamCause,
1285+
input.detachedThreadId,
12831286
);
12841287
}
12851288
const closeExit = yield* closeScopeWithin(entry.scope, {

0 commit comments

Comments
 (0)