Skip to content

Commit 58e3294

Browse files
committed
fix(server): moving a thread mid-turn no longer fails the turn
t3_thread_select_project and t3_worktree_handoff change the thread's workspace from inside the agent's own turn. The orchestrator detached the provider session right away, which for Claude closed the event stream while the tool call was still running: the run failed with a provider error and the queued continuation stayed stuck behind the unfinished tool call. A workspace change while a run is active now leaves the session alone. The tool call returns, the turn ends normally, and the next turn start replaces a session whose working directory no longer matches the thread's workspace, resuming the native conversation there. Idle workspace changes still detach immediately. The scratch folder is no longer removed after a project selection: on Windows the live provider process holds it as its working directory, and an empty folder is harmless, like the ones deleted threads leave behind.
1 parent e80954c commit 58e3294

9 files changed

Lines changed: 285 additions & 233 deletions

File tree

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

Lines changed: 5 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import {
44
CommandId,
55
EnvironmentId,
66
type OrchestrationV2ThreadProjection,
7-
type OrchestrationV2ThreadShell,
87
type Project,
98
ProjectId,
109
ProviderInstanceId,
@@ -123,8 +122,6 @@ interface HarnessOptions {
123122
readonly removeWorktreeFails?: boolean;
124123
readonly deleteLocalBranchFails?: boolean;
125124
readonly createWorktreeGate?: Effect.Effect<void>;
126-
readonly scratchRoot?: string;
127-
readonly otherThreadWorktreePaths?: ReadonlyArray<string>;
128125
}
129126

130127
const makeHarness = (options: HarnessOptions = {}) => {
@@ -278,14 +275,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
278275
}),
279276
);
280277
const refreshStatus = vi.fn((_: string) => Effect.die("refreshStatus stub"));
281-
const listProjectThreads = vi.fn((_: unknown) =>
282-
Effect.succeed(
283-
(options.otherThreadWorktreePaths ?? []).map((worktreePath, index) => ({
284-
id: ThreadId.make(`thread-other-${index}`),
285-
worktreePath,
286-
})) as unknown as ReadonlyArray<OrchestrationV2ThreadShell>,
287-
),
288-
);
289278
const runForThread = vi.fn((input: { readonly worktreePath: string }) => {
290279
switch (options.setupScript ?? "started") {
291280
case "no-script":
@@ -319,10 +308,8 @@ const makeHarness = (options: HarnessOptions = {}) => {
319308
dispatch,
320309
getThreadRecords,
321310
sendToThread,
322-
listProjectThreads,
323311
} satisfies Partial<ThreadManagementService.ThreadManagementService["Service"]>),
324312
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
325-
scratchRoot: Effect.succeed(Option.fromNullishOr(options.scratchRoot)),
326313
isScratchProject: (id) => Effect.succeed(id === scratchProjectId),
327314
namedProjectsRoot: "/projects",
328315
} satisfies Partial<ManagedProjectFolders.ManagedProjectFolders["Service"]>),
@@ -358,7 +345,6 @@ const makeHarness = (options: HarnessOptions = {}) => {
358345
scope,
359346
dispatch,
360347
sendToThread,
361-
listProjectThreads,
362348
fetchWorktreeBaseCommit,
363349
createWorktree,
364350
removeWorktree,
@@ -742,15 +728,14 @@ const makeScratchFolder = Effect.gen(function* () {
742728
const scratchRoot = yield* fs.makeTempDirectoryScoped({ prefix: "select-project-scratch-" });
743729
const folder = path.join(scratchRoot, "2026-10-23-in-whatscord-fix-the-login-a1b2c3d4");
744730
yield* fs.makeDirectory(folder);
745-
return { fs, path, scratchRoot, folder };
731+
return { fs, path, folder };
746732
});
747733

748734
describe("t3_thread_select_project", () => {
749735
it.effect("moves an untouched scratch thread to the project root and resumes it there", () =>
750736
Effect.gen(function* () {
751-
const { fs, scratchRoot, folder } = yield* makeScratchFolder;
737+
const { folder } = yield* makeScratchFolder;
752738
const harness = makeHarness({
753-
scratchRoot,
754739
thread: { projectId: scratchProjectId, worktreePath: folder },
755740
});
756741

@@ -779,34 +764,29 @@ describe("t3_thread_select_project", () => {
779764
workspaceRoot,
780765
continuation: { status: "scheduled", delivery: "queued" },
781766
});
782-
expect(yield* fs.exists(folder)).toBe(false);
783767
}).pipe(Effect.provide(NodeServices.layer)),
784768
);
785769

786-
it.effect("queues the agent's own continuation and keeps a folder a fork still uses", () =>
770+
it.effect("queues the agent's own continuation prompt", () =>
787771
Effect.gen(function* () {
788-
const { fs, scratchRoot, folder } = yield* makeScratchFolder;
772+
const { folder } = yield* makeScratchFolder;
789773
const harness = makeHarness({
790-
scratchRoot,
791774
thread: { projectId: scratchProjectId, worktreePath: folder },
792-
otherThreadWorktreePaths: [folder],
793775
});
794776

795777
yield* runSelectProject(harness, { projectId, continuationPrompt: "Fix the login bug." });
796778

797779
expect(harness.sendToThread).toHaveBeenCalledWith(
798780
expect.objectContaining({ text: "Fix the login bug." }),
799781
);
800-
expect(yield* fs.exists(folder)).toBe(true);
801782
}).pipe(Effect.provide(NodeServices.layer)),
802783
);
803784

804785
it.effect("refuses once the agent has written files to the scratch folder", () =>
805786
Effect.gen(function* () {
806-
const { fs, path, scratchRoot, folder } = yield* makeScratchFolder;
787+
const { fs, path, folder } = yield* makeScratchFolder;
807788
yield* fs.writeFileString(path.join(folder, "notes.md"), "started");
808789
const harness = makeHarness({
809-
scratchRoot,
810790
thread: { projectId: scratchProjectId, worktreePath: folder },
811791
});
812792

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

Lines changed: 7 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,13 @@ import * as Effect from "effect/Effect";
1818
import * as FileSystem from "effect/FileSystem";
1919
import * as Layer from "effect/Layer";
2020
import * as Option from "effect/Option";
21-
import * as Path from "effect/Path";
2221

2322
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
2423
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
2524
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
2625
import * as ProjectService from "../project/ProjectService.ts";
2726
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
2827
import * as ServerSettings from "../serverSettings.ts";
29-
import { removeEmptyDirectory } from "../vcs/removeEmptyDirectory.ts";
3028
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
3129
import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
3230

@@ -75,7 +73,6 @@ const make = Effect.gen(function* () {
7573
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
7674
const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
7775
const fileSystem = yield* FileSystem.FileSystem;
78-
const path = yield* Path.Path;
7976

8077
// Serializes workspace changes per thread: two concurrent handoffs could
8178
// otherwise both pass the worktreePath === null check and each create a
@@ -405,8 +402,8 @@ const make = Effect.gen(function* () {
405402
continuation,
406403
note:
407404
continuation.status === "scheduled"
408-
? "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the queued continuation prompt then starts the next turn inside the worktree with the conversation preserved. The worktree is not removed automatically when the thread is deleted."
409-
: "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.",
405+
? "Handoff recorded. This turn still runs in the previous workspace, so end it now; the queued continuation prompt then starts the next turn inside the worktree with the conversation preserved. The worktree is not removed automatically when the thread is deleted."
406+
: "Handoff recorded. This turn still runs in the previous workspace, so end it now; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.",
410407
};
411408
return result;
412409
}),
@@ -459,32 +456,6 @@ const make = Effect.gen(function* () {
459456
asOperationFailed(`Unable to read the thread's folder '${folder}'`),
460457
);
461458

462-
// Removes the thread's own scratch folder once it has moved out. A fork can
463-
// share the folder, and rmdir keeps anything written there meanwhile.
464-
const removeScratchFolder = Effect.fn("WorktreeMcpService.removeScratchFolder")(function* (
465-
thread: { readonly id: string; readonly projectId: ProjectId },
466-
folder: string,
467-
) {
468-
const scratchRoot = yield* managedFolders.scratchRoot;
469-
if (
470-
!Option.exists(
471-
scratchRoot,
472-
(root) => path.dirname(path.resolve(folder)) === path.resolve(root),
473-
)
474-
) {
475-
return;
476-
}
477-
const shared = yield* threadManagement
478-
.listProjectThreads({ projectId: thread.projectId, includeSubagents: true })
479-
.pipe(
480-
Effect.map((threads) =>
481-
threads.some((other) => other.id !== thread.id && other.worktreePath === folder),
482-
),
483-
);
484-
if (shared) return;
485-
yield* removeEmptyDirectory(folder);
486-
});
487-
488459
const performSelectProject = Effect.fn("WorktreeMcpService.performSelectProject")(function* (
489460
scope: McpThreadInvocationScope,
490461
input: ThreadSelectProjectMcpInput,
@@ -524,9 +495,9 @@ const make = Effect.gen(function* () {
524495
input.continuationPrompt ??
525496
`This thread now works in the ${target.title} project at ${target.workspaceRoot}. Continue the user's request there.`;
526497

527-
// uninterruptibleMask: once the move commits, the scheduled session detach
528-
// can sever this request's connection and interrupt the fiber, and the
529-
// queued continuation is what restarts the thread in the project.
498+
// uninterruptibleMask: once the move commits, the queued continuation is
499+
// what starts the thread in the project, so a cancelled request must not
500+
// skip it.
530501
return yield* Effect.uninterruptibleMask((restore) =>
531502
Effect.gen(function* () {
532503
yield* restore(
@@ -577,20 +548,14 @@ const make = Effect.gen(function* () {
577548
}),
578549
);
579550

580-
if (thread.worktreePath !== null) {
581-
yield* removeScratchFolder(thread, thread.worktreePath).pipe(
582-
Effect.ignoreCause({ log: true }),
583-
);
584-
}
585-
586551
const result: ThreadSelectProjectMcpResult = {
587552
projectId: target.id,
588553
workspaceRoot: target.workspaceRoot,
589554
continuation,
590555
note:
591556
continuation.status === "scheduled"
592-
? "Thread moved to the project's root. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the queued continuation then starts the next turn in the project with the conversation preserved. Use t3_worktree_handoff there if the work needs its own worktree."
593-
: "Thread moved to the project's root. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues in the project when the thread receives its next message.",
557+
? "Thread moved to the project's root. This turn still runs in the scratch folder, so end it now without touching files; the queued continuation then starts the next turn in the project with the conversation preserved. Use t3_worktree_handoff there if the work needs its own worktree."
558+
: "Thread moved to the project's root. This turn still runs in the scratch folder, so end it now without touching files; the conversation continues in the project when the thread receives its next message.",
594559
};
595560
return result;
596561
}),
@@ -640,5 +605,4 @@ export const layer: Layer.Layer<
640605
| VcsStatusBroadcaster.VcsStatusBroadcaster
641606
| ManagedProjectFolders.ManagedProjectFolders
642607
| FileSystem.FileSystem
643-
| Path.Path
644608
> = Layer.effect(WorktreeMcpService, make);

‎apps/server/src/mcp/toolkits/worktree/tools.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ const WorktreeToolFailure = Schema.Union([WorktreeMcpFailure, OrchestratorMcpFai
2929

3030
const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", {
3131
description:
32-
"Needs an agent running inside a T3 thread. Move this agent thread into a new git worktree. To launch a separate agent already bound to a new or existing worktree, use t3_thread_launch with workspaceStrategy instead. Creates the worktree branch (optionally from the base branch's remote), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.",
32+
"Needs an agent running inside a T3 thread. Move this agent thread into a new git worktree. To launch a separate agent already bound to a new or existing worktree, use t3_thread_launch with workspaceStrategy instead. Creates the worktree branch (optionally from the base branch's remote), re-points the thread at the worktree, and by default runs the project's setup script there. The current turn keeps the previous workspace, so call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.",
3333
parameters: WorktreeMcpHandoffInput,
3434
success: WorktreeMcpHandoffResult,
3535
failure: WorktreeToolFailure,
@@ -62,7 +62,7 @@ const WorktreeStatusTool = Tool.make("t3_worktree_status", {
6262

6363
const ThreadSelectProjectTool = Tool.make("t3_thread_select_project", {
6464
description:
65-
"Needs an agent running inside a T3 thread without a project (its working directory is a T3 Code scratch folder). When the user names one of their projects, find it with t3_project_list and call this as your FIRST action, before reading or editing any files: it moves this thread into the project so its work gets the project's branch, diffs, and checkpoints. The thread lands in the project's root; call t3_worktree_handoff afterwards if the work needs its own worktree. Changing the workspace detaches the live provider session, so the current turn ends shortly after this call; end your turn after it. A continuation is queued as the thread's next message and resumes the conversation in the project; pass continuationPrompt to word it yourself. Fails once the thread's scratch folder has files in it: then start a thread in the project with t3_thread_launch instead.",
65+
"Needs an agent running inside a T3 thread without a project (its working directory is a T3 Code scratch folder). When the user names one of their projects, find it with t3_project_list and call this as your FIRST action, before reading or editing any files: it moves this thread into the project so its work gets the project's branch, diffs, and checkpoints. The thread lands in the project's root; call t3_worktree_handoff afterwards if the work needs its own worktree. The current turn keeps the scratch folder as its working directory, so end your turn right after this call. A continuation is queued as the thread's next message and resumes the conversation in the project; pass continuationPrompt to word it yourself. Fails once the thread's scratch folder has files in it: then start a thread in the project with t3_thread_launch instead.",
6666
parameters: ThreadSelectProjectMcpInput,
6767
success: ThreadSelectProjectMcpResult,
6868
failure: WorktreeToolFailure,

0 commit comments

Comments
 (0)