The best way to control Claude Code, Codex and more from any computer or phone
fix(cli): t3 thread finds the project from inside its git worktrees (#30802)
Julius Marminge committed
Nov 11, 2026 at 16:09 UTC
d21daa78e043c14cf70b6a8e93e21104b1a2470c
3 files changed
+145
-18
apps/server/src/cli/thread.test.ts
+68
@@ -10,6 +10,7 @@ import * as Effect from "effect/Effect";
10
import * as FileSystem from "effect/FileSystem";
11
import * as Layer from "effect/Layer";
12
import * as Path from "effect/Path";
13
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
14
import * as TestConsole from "effect/testing/TestConsole";
15
import { Command } from "effect/cli";
16
import { vi } from "vite-plus/test";
@@ -21,6 +22,7 @@ import {
22
} from "../serverRuntimeState.ts";
23
import {
24
readLatestMessages,
25
+ resolveProject,
26
threadCommand,
27
type ThreadTools,
28
titleFromMessage,
@@ -292,3 +294,69 @@ it("titles from a long first line without splitting an emoji", () => {
294
const title = titleFromMessage(`${"a".repeat(78)}😀 and the rest of a long first line`);
295
assert.strictEqual(title, `${"a".repeat(78)}…`);
296
});
297
+
298
+const git = Effect.fn("test.git")(function* (cwd: string, args: ReadonlyArray<string>) {
299
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
300
+ const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }));
301
+ assert.strictEqual(Number(exitCode), 0, `git ${args.join(" ")}`);
302
+});
303
+
304
+const commitAll = (cwd: string) =>
305
+ Effect.andThen(
306
+ git(cwd, ["add", "."]),
307
+ git(cwd, [
308
+ "-c",
309
+ "user.name=Test",
310
+ "-c",
311
+ "user.email=test@example.test",
312
+ "commit",
313
+ "--quiet",
314
+ "-m",
315
+ "initial",
316
+ ]),
317
+ );
318
+
319
+it.live("resolves a path inside a git worktree of the project's repository to that project", () =>
320
+ Effect.gen(function* () {
321
+ const fileSystem = yield* FileSystem.FileSystem;
322
+ const path = yield* Path.Path;
323
+ const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-thread-worktree-" });
324
+ const repo = path.join(root, "sample");
325
+ const worktree = path.join(root, "worktrees", "sample", "t3-8ff64c24");
326
+ const feature = path.join(root, "wt", "feature");
327
+ const featureWorktree = path.join(root, "worktrees", "feature", "t3-1a2b3c4d");
328
+ yield* fileSystem.makeDirectory(path.join(repo, "pkg"), { recursive: true });
329
+ yield* fileSystem.writeFileString(path.join(repo, "pkg", "index.ts"), "export {};\n");
330
+ yield* git(repo, ["init", "--quiet", "-b", "main"]);
331
+ yield* commitAll(repo);
332
+ yield* git(repo, ["worktree", "add", "--quiet", "-b", "t3/8ff64c24", worktree]);
333
+ yield* git(repo, ["worktree", "add", "--quiet", "-b", "feature", feature]);
334
+ yield* git(feature, ["worktree", "add", "--quiet", "-b", "t3/1a2b3c4d", featureWorktree]);
335
+
336
+ const project = (id: string, workspaceRoot: string) => ({
337
+ id: ProjectId.make(id),
338
+ title: path.basename(workspaceRoot),
339
+ workspaceRoot,
340
+ });
341
+ const sample = project("project-sample", repo);
342
+ const featureProject = project("project-feature", feature);
343
+ const resolveFrom = (
344
+ projects: ReadonlyArray<ReturnType<typeof project>>,
345
+ workingDirectory: string,
346
+ identifier = ".",
347
+ ) =>
348
+ resolveProject(
349
+ scriptedTools({ t3_project_list: [{ projects, nextCursor: null }] }).tools,
350
+ identifier,
351
+ ).pipe(Effect.provideService(HostProcess.WorkingDirectory, workingDirectory));
352
+
353
+ assert.deepStrictEqual(yield* resolveFrom([sample], worktree), sample);
354
+ assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample);
355
+ assert.deepStrictEqual(yield* resolveFrom([sample], worktree, "pkg/index.ts"), sample);
356
+ assert.deepStrictEqual(yield* resolveFrom([featureProject], featureWorktree), featureProject);
357
+ const ambiguous = yield* Effect.flip(resolveFrom([sample, featureProject], featureWorktree));
358
+ assert.strictEqual(ambiguous._tag, "ThreadUsageError");
359
+ assert.include(ambiguous.message, "sample (project-sample)");
360
+ assert.include(ambiguous.message, "feature (project-feature)");
361
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
362
+);
apps/server/src/cli/thread.ts
+72
-13
@@ -30,6 +30,7 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
30
import * as ServerConfig from "../config.ts";
31
import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
32
import { expandHomePath } from "../os-jank.ts";
33
+import * as ProcessRunner from "../processRunner.ts";
34
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
35
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
36
@@ -273,8 +274,34 @@ const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools
274
return projects;
275
});
276
276
-/** A project id, or a path inside a project's folder (deepest project wins). */
277
-const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
277
+/** The checkouts of the git repository at `directory`, or none outside a repository. */
278
+const listGitCheckouts = Effect.fn("cli.thread.listGitCheckouts")(function* (directory: string) {
279
+ const processRunner = yield* ProcessRunner.ProcessRunner;
280
+ const list = (args: ReadonlyArray<string>) =>
281
+ processRunner
282
+ .run({ command: "git", args: ["worktree", "list", "--porcelain", ...args], cwd: directory })
283
+ .pipe(
284
+ Effect.option,
285
+ Effect.map((result) =>
286
+ Option.isSome(result) && result.value.code === 0 ? result.value.stdout : undefined,
287
+ ),
288
+ );
289
+ // Pre-2.36 Git rejects worktree list -z; normalize its line output to NUL records.
290
+ const stdout = (yield* list(["-z"])) ?? (yield* list([]))?.replaceAll("\n", "\0") ?? "";
291
+ return stdout.split("\0\0").flatMap((record) => {
292
+ const [first = "", ...attributes] = record.split("\0");
293
+ return first.startsWith("worktree ") && !attributes.includes("bare")
294
+ ? [first.slice("worktree ".length)]
295
+ : [];
296
+ });
297
+});
298
+
299
+/**
300
+ * A project id, or a path inside a project's folder (deepest project wins).
301
+ * A path inside a git worktree resolves as the same path in the repository's
302
+ * other checkouts.
303
+ */
304
+export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
305
tools: ThreadTools,
306
identifier: string,
307
) {
@@ -294,19 +321,51 @@ const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
321
const roots = yield* Effect.forEach(projects, (project) =>
322
Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })),
323
);
297
- const containing = roots
298
- .filter(({ root }) => {
299
- const relative = path.relative(root, target);
300
- return (
301
- relative === "" ||
302
- (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
303
- );
304
- })
305
- .toSorted((left, right) => right.root.length - left.root.length)[0];
306
- if (containing === undefined) {
324
+ const contains = (root: string, candidate: string) => {
325
+ const relative = path.relative(root, candidate);
326
+ return (
327
+ relative === "" ||
328
+ (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
329
+ );
330
+ };
331
+ const deepestContaining = (candidate: string) =>
332
+ roots
333
+ .filter(({ root }) => contains(root, candidate))
334
+ .toSorted((left, right) => right.root.length - left.root.length)[0]?.project;
335
+
336
+ const containing = deepestContaining(target);
337
+ if (containing !== undefined) return containing;
338
+ const targetInfo = yield* fileSystem.stat(target).pipe(Effect.option);
339
+ const gitDirectory =
340
+ Option.isSome(targetInfo) && targetInfo.value.type === "File" ? path.dirname(target) : target;
341
+ const listed = yield* listGitCheckouts(gitDirectory).pipe(
342
+ Effect.flatMap((paths) => Effect.forEach(paths, realPath)),
343
+ Effect.provide(ProcessRunner.layer),
344
+ );
345
+ const ownCheckout = listed
346
+ .filter((checkout) => contains(checkout, target))
347
+ .toSorted((left, right) => right.length - left.length)[0];
348
+ if (ownCheckout === undefined) {
349
+ return yield* new ThreadProjectNotFoundError({ identifier });
350
+ }
351
+ const relative = path.relative(ownCheckout, target);
352
+ const matches = new Map<ProjectId, (typeof projects)[number]>();
353
+ for (const checkout of listed) {
354
+ if (checkout === ownCheckout) continue;
355
+ const project = deepestContaining(path.join(checkout, relative));
356
+ if (project !== undefined) matches.set(project.id, project);
357
+ }
358
+ const [match, ...others] = matches.values();
359
+ if (match === undefined) {
360
return yield* new ThreadProjectNotFoundError({ identifier });
361
}
309
- return containing.project;
362
+ if (others.length > 0) {
363
+ const names = [match, ...others].map((project) => `${project.title} (${project.id})`);
364
+ return yield* new ThreadUsageError({
365
+ detail: `'${identifier}' is in a git worktree shared by several projects: ${names.join(", ")}. Pass a project id instead.`,
366
+ });
367
+ }
368
+ return match;
369
});
370
371
/** Every item on a timeline view, oldest first. */
docs/user/outside-agents.md
+5
-5
@@ -147,11 +147,11 @@ t3 thread show "$id"
147
t3 thread list
148
```
149
150
-`.` means the project that contains the current folder; a project id also
151
-works. A new thread uses the project's default model and permission mode, and
152
-runs in the project folder unless you pass `--worktree <base-branch>`. `send`
153
-never interrupts: a busy thread gets the message as its next turn. Pass `-` as
154
-the message to read it from stdin.
150
+`.` means the project that contains the current folder, or a git worktree of
151
+its repository; a project id also works. A new thread uses the project's
152
+default model and permission mode, and runs in the project folder unless you
153
+pass `--worktree <base-branch>`. `send` never interrupts: a busy thread gets
154
+the message as its next turn. Pass `-` as the message to read it from stdin.
155
156
`--wait` prints the agent's reply. It exits 1 when the run fails or stops, and
157
2 when the agent waits for an answer you give in the app. Add `--json` for a