@devries-cameron20 / t3code-1 / commits / 3b7d39ef75
Fork 0

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

fix(mobile): new threads reuse the worktree that already holds a branch instead of failing checkout (#20825)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

shivam committed Oct 20, 2026 at 10:57 UTC 3b7d39ef75e11599ca652f85e3b43d7e0c630bdc
8 files changed +442 -26
apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
+2
@@ -268,6 +268,7 @@ export function NewTaskBranchPickerRouteScreen() {
268 AuthSourceControlWriteScope,
269 );
270 const navigation = useNavigation();
271 + const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
272 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
273 const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
274 const selectingBranchNameRef = useRef<string | null>(null);
@@ -314,6 +315,7 @@ export function NewTaskBranchPickerRouteScreen() {
315 branch,
316 project,
317 workspaceMode: flow.workspaceMode,
318 + readRefs,
319 switchRef,
320 });
321 if (mountedRef.current) setSwitchingBranchName(null);
apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
+15 -5
@@ -12,6 +12,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
12 import { useWorkspaceState } from "../../state/workspace";
13 import { vcsEnvironment } from "../../state/vcs";
14 import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
15 +import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";
16 import { NativeStackScreenOptions } from "../../native/StackHeader";
17
18 import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
@@ -37,6 +38,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
38 const projects = useProjects();
39 const { state: catalogState } = useWorkspaceState();
40 const navigation = useNavigation();
41 + const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
42 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
43
44 const initialProjectRef = useMemo(
@@ -87,8 +89,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
89 return;
90 }
91 const result = await checkoutNewTaskBranch({
90 - // A thread's branch is historical; only switchRef can establish that
91 - // the shared project checkout now matches it.
92 branch: {
93 name: branchName,
94 current: false,
@@ -97,6 +97,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
97 },
98 project: environmentId && workspaceRoot ? { environmentId, workspaceRoot } : null,
99 workspaceMode: "local",
100 + readRefs,
101 switchRef,
102 });
103 setPendingCheckouts((count) => count - 1);
@@ -110,6 +111,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
111 workspaceRoot,
112 initialProjectRef,
113 needsPreparation,
114 + readRefs,
115 switchRef,
116 waitingForProject,
117 ]);
@@ -136,10 +138,18 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
138
139 const preparedProjectRef = useMemo(
140 () =>
139 - result?._tag === "Success"
140 - ? { ...initialProjectRef, branch: result.value.name }
141 + result?._tag === "Success" && workspaceRoot
142 + ? {
143 + ...initialProjectRef,
144 + branch: result.value.name,
145 + worktreePath: resolveNewTaskBranchWorktreePath({
146 + workspaceMode: "local",
147 + projectCwd: workspaceRoot,
148 + branchWorktreePath: result.value.worktreePath,
149 + }),
150 + }
151 : initialProjectRef,
142 - [initialProjectRef, result],
152 + [initialProjectRef, result, workspaceRoot],
153 );
154 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
155
apps/mobile/src/features/threads/checkout-new-task-branch.test.ts
+287 -7
@@ -3,8 +3,9 @@ import * as NodeFSP from "node:fs/promises";
3 import * as NodeOS from "node:os";
4 import * as NodePath from "node:path";
5 import * as NodeUtil from "node:util";
6 -import { EnvironmentId } from "@t3tools/contracts";
6 +import { EnvironmentId, VcsListRefsInput } from "@t3tools/contracts";
7 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8 +import * as Schema from "effect/Schema";
9 import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
10
11 import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
@@ -17,7 +18,9 @@ const branch = { name: "feature/a", current: false, isDefault: false, worktreePa
18 const environmentId = EnvironmentId.make("branch-test-environment");
19
20 beforeEach(async () => {
20 - directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-branch-selection-"));
21 + directory = await NodeFSP.realpath(
22 + await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-branch-selection-")),
23 + );
24 cwd = NodePath.join(directory, "project");
25 await exec("git", ["init", "-b", "main", cwd]);
26 await git("config", "user.name", "Branch test");
@@ -35,30 +38,119 @@ afterEach(async () => {
38 await NodeFSP.rm(directory, { recursive: true, force: true });
39 });
40
38 -function selectBranch(switchRef: Parameters<typeof checkoutNewTaskBranch>[0]["switchRef"]) {
41 +type CheckoutInput = Parameters<typeof checkoutNewTaskBranch>[0];
42 +const decodeListRefsInput = Schema.decodeUnknownSync(VcsListRefsInput);
43 +const REF_PAGE_SIZE = 2;
44 +
45 +const readRefs: CheckoutInput["readRefs"] = (request) =>
46 + settlePromise(async () => {
47 + expect(request.environmentId).toBe(environmentId);
48 + const input = decodeListRefsInput(request.input);
49 + const { stdout: rootPath } = await exec("git", [
50 + "-C",
51 + input.cwd,
52 + "rev-parse",
53 + "--show-toplevel",
54 + ]);
55 + const { stdout: head } = await exec("git", [
56 + "-C",
57 + input.cwd,
58 + "rev-parse",
59 + "--symbolic-full-name",
60 + "HEAD",
61 + ]);
62 + const { stdout } = await exec("git", [
63 + "-C",
64 + input.cwd,
65 + "for-each-ref",
66 + "--sort=refname",
67 + "--format=%(refname:short)%09%(worktreepath)%09%(upstream)",
68 + "refs/heads",
69 + ]);
70 + const refs = stdout
71 + .trimEnd()
72 + .split("\n")
73 + .map((line) => {
74 + const [name = "", path, upstreamRef] = line.split("\t");
75 + return {
76 + name,
77 + current: head.trim() === `refs/heads/${name}`,
78 + isDefault: name === "main",
79 + isRemote: false,
80 + worktreePath: path || null,
81 + ...(upstreamRef ? { upstreamRef } : {}),
82 + };
83 + })
84 + .filter((ref) => ref.name.includes(input.query ?? ""));
85 + const cursor = input.cursor ?? 0;
86 + return {
87 + isAtRepositoryRoot: (await NodeFSP.realpath(input.cwd)) === rootPath.trim(),
88 + refs: refs.slice(cursor, cursor + REF_PAGE_SIZE),
89 + isRepo: true,
90 + hasPrimaryRemote: false,
91 + nextCursor: cursor + REF_PAGE_SIZE < refs.length ? cursor + REF_PAGE_SIZE : null,
92 + totalCount: refs.length,
93 + };
94 + });
95 +
96 +const refuseSwitch: CheckoutInput["switchRef"] = () => {
97 + throw new Error("An occupied branch must not trigger checkout");
98 +};
99 +
100 +function selectBranch(switchRef: CheckoutInput["switchRef"]) {
101 return checkoutNewTaskBranch({
102 branch,
103 project: { environmentId, workspaceRoot: cwd },
104 workspaceMode: "local",
105 + readRefs,
106 switchRef,
107 });
108 }
109
47 -const switchRef: Parameters<typeof checkoutNewTaskBranch>[0]["switchRef"] = (request) =>
110 +const switchRef: CheckoutInput["switchRef"] = (request) =>
111 settlePromise(async () => {
112 expect(request.environmentId).toBe(environmentId);
113 await exec("git", ["-C", request.input.cwd, "checkout", request.input.refName]);
114 const { stdout } = await exec("git", ["-C", request.input.cwd, "branch", "--show-current"]);
52 - return { refName: stdout.trim() };
115 + return { refName: stdout.trim() || null };
116 });
117
118 +async function addRemote(remoteName: string, sourceRef = branch.name) {
119 + const remotePath = NodePath.join(directory, `${remoteName.replaceAll("/", "-")}.git`);
120 + await exec("git", ["init", "--bare", remotePath]);
121 + await git("remote", "add", remoteName, remotePath);
122 + await git("push", remoteName, `${sourceRef}:refs/heads/${branch.name}`);
123 + const { stdout } = await git(
124 + "rev-parse",
125 + "--verify",
126 + "--symbolic-full-name",
127 + `refs/remotes/${remoteName}/${branch.name}`,
128 + );
129 + return {
130 + ...branch,
131 + name: stdout.trim().replace("refs/remotes/", ""),
132 + isRemote: true,
133 + remoteName,
134 + };
135 +}
136 +
137 describe("new-task branch checkout", () => {
56 - it("switches main to the older thread's feature branch before returning a selection", async () => {
57 - const result = await selectBranch(switchRef);
138 + it("switches to a free branch and clears its historical worktree path", async () => {
139 + const previousWorktree = NodePath.join(directory, "previous-worktree");
140 + await git("worktree", "add", previousWorktree, branch.name);
141 + await exec("git", ["-C", previousWorktree, "checkout", "-b", "other-branch"]);
142 + const result = await checkoutNewTaskBranch({
143 + branch: { ...branch, worktreePath: previousWorktree },
144 + project: { environmentId, workspaceRoot: cwd },
145 + workspaceMode: "local",
146 + readRefs,
147 + switchRef,
148 + });
149 expect(result._tag).toBe("Success");
150 if (result._tag !== "Success") throw new Error("Checkout failed");
151 expect(result.value.name).toBe("feature/a");
152 expect(result.value.current).toBe(true);
153 + expect(result.value.worktreePath).toBeNull();
154 expect((await git("branch", "--show-current")).stdout.trim()).toBe("feature/a");
155 expect(await NodeFSP.readFile(NodePath.join(cwd, "file.txt"), "utf8")).toBe("feature\n");
156 });
@@ -100,6 +192,7 @@ describe("new-task branch checkout", () => {
192 branch,
193 project: null,
194 workspaceMode: "local",
195 + readRefs,
196 switchRef: () => {
197 throw new Error("An unavailable project must not run checkout");
198 },
@@ -117,6 +210,7 @@ describe("new-task branch checkout", () => {
210 branch: { ...branch, worktreePath },
211 project: { environmentId, workspaceRoot: cwd },
212 workspaceMode: "local",
213 + readRefs,
214 switchRef: () => {
215 throw new Error("Existing worktrees must not switch the project checkout");
216 },
@@ -129,4 +223,190 @@ describe("new-task branch checkout", () => {
223 "feature\n",
224 );
225 });
226 +
227 + it("reuses an occupied picker worktree when the project root is a symlink", async () => {
228 + const worktreePath = NodePath.join(directory, "worktree");
229 + await git("worktree", "add", worktreePath, branch.name);
230 + const workspaceRoot = NodePath.join(directory, "project-alias");
231 + await NodeFSP.symlink(cwd, workspaceRoot, "junction");
232 +
233 + const result = await checkoutNewTaskBranch({
234 + branch: { ...branch, worktreePath },
235 + project: { environmentId, workspaceRoot },
236 + workspaceMode: "local",
237 + readRefs,
238 + switchRef: refuseSwitch,
239 + });
240 +
241 + expect((await git("branch", "--show-current")).stdout.trim()).toBe("main");
242 + expect(await NodeFSP.readFile(NodePath.join(workspaceRoot, "file.txt"), "utf8")).toBe("main\n");
243 + expect(
244 + (await exec("git", ["-C", worktreePath, "branch", "--show-current"])).stdout.trim(),
245 + ).toBe(branch.name);
246 + expect(await NodeFSP.readFile(NodePath.join(worktreePath, "file.txt"), "utf8")).toBe(
247 + "feature\n",
248 + );
249 + expect(
250 + result._tag,
251 + result._tag === "Failure" ? String(squashAtomCommandFailure(result)) : undefined,
252 + ).toBe("Success");
253 + if (result._tag !== "Success") throw new Error("Symlink-root worktree selection failed");
254 + expect(result.value.worktreePath).toBe(worktreePath);
255 + });
256 +
257 + it("resolves historical branch metadata to its worktree beyond a long query's first page", async () => {
258 + const name = `feature/${"a".repeat(120)}/${"b".repeat(150)}`;
259 + await git("branch", "-m", branch.name, name);
260 + await git("branch", `a-${name}`);
261 + await git("branch", `b-${name}`);
262 + await git("worktree", "add", NodePath.join(directory, "decoy"), `a-${name}`);
263 + const worktreePath = NodePath.join(directory, "worktree");
264 + await git("worktree", "add", worktreePath, name);
265 +
266 + const result = await checkoutNewTaskBranch({
267 + branch: { ...branch, name },
268 + project: { environmentId, workspaceRoot: cwd },
269 + workspaceMode: "local",
270 + readRefs,
271 + switchRef: refuseSwitch,
272 + });
273 +
274 + expect(result._tag).toBe("Success");
275 + if (result._tag !== "Success") throw new Error("Historical branch selection failed");
276 + expect(result.value).toMatchObject({
277 + name,
278 + worktreePath,
279 + });
280 + expect((await git("branch", "--show-current")).stdout.trim()).toBe("main");
281 + expect(await NodeFSP.readFile(NodePath.join(cwd, "file.txt"), "utf8")).toBe("main\n");
282 + });
283 +
284 + it("resolves a non-origin remote to the right worktree when the remote name contains slashes", async () => {
285 + const remoteBranch = await addRemote("team/upstream");
286 + await git("branch", "--set-upstream-to", remoteBranch.name, branch.name);
287 + await git("branch", "upstream/feature/a");
288 + await git("worktree", "add", NodePath.join(directory, "decoy"), "upstream/feature/a");
289 + const worktreePath = NodePath.join(directory, "worktree");
290 + await git("worktree", "add", worktreePath, branch.name);
291 +
292 + const result = await checkoutNewTaskBranch({
293 + branch: remoteBranch,
294 + project: { environmentId, workspaceRoot: cwd },
295 + workspaceMode: "local",
296 + readRefs,
297 + switchRef: refuseSwitch,
298 + });
299 +
300 + expect(result._tag).toBe("Success");
301 + if (result._tag !== "Success") throw new Error("Remote branch selection failed");
302 + expect(result.value).toMatchObject({
303 + name: branch.name,
304 + isRemote: false,
305 + worktreePath,
306 + });
307 + expect((await git("branch", "--show-current")).stdout.trim()).toBe("main");
308 + });
309 +
310 + it("switches to the selected remote instead of reusing a worktree tracking another remote", async () => {
311 + const originBranch = await addRemote("origin");
312 + await git("branch", "--set-upstream-to", originBranch.name, branch.name);
313 + const worktreePath = NodePath.join(directory, "worktree");
314 + await git("worktree", "add", worktreePath, branch.name);
315 + await git("checkout", "-b", "upstream-source");
316 + await NodeFSP.writeFile(NodePath.join(cwd, "file.txt"), "upstream feature\n");
317 + await git("commit", "-am", "divergent upstream feature");
318 + const remoteBranch = await addRemote("team/upstream", "HEAD");
319 + const selectedCommit = (await git("rev-parse", remoteBranch.name)).stdout.trim();
320 + expect((await git("rev-parse", originBranch.name)).stdout.trim()).not.toBe(selectedCommit);
321 + await git("checkout", "main");
322 +
323 + const result = await checkoutNewTaskBranch({
324 + branch: remoteBranch,
325 + project: { environmentId, workspaceRoot: cwd },
326 + workspaceMode: "local",
327 + readRefs,
328 + switchRef,
329 + });
330 +
331 + expect(result._tag).toBe("Success");
332 + if (result._tag !== "Success") throw new Error("Remote checkout failed");
333 + expect(result.value.worktreePath).toBeNull();
334 + expect((await git("rev-parse", "HEAD")).stdout.trim()).toBe(selectedCommit);
335 + expect(await NodeFSP.readFile(NodePath.join(cwd, "file.txt"), "utf8")).toBe(
336 + "upstream feature\n",
337 + );
338 + expect(await NodeFSP.readFile(NodePath.join(worktreePath, "file.txt"), "utf8")).toBe(
339 + "feature\n",
340 + );
341 + });
342 +
343 + it.each([
344 + { source: "historical", nested: true },
345 + { source: "picker", nested: true },
346 + { source: "historical", nested: false },
347 + { source: "picker", nested: false },
348 + ])(
349 + "rejects $source worktree reuse when project root is unsafe (nested: $nested)",
350 + async ({ source, nested }) => {
351 + const projectRoot = cwd;
352 + const worktreePath = NodePath.join(directory, "worktree");
353 + await git("worktree", "add", worktreePath, branch.name);
354 + if (nested) {
355 + cwd = NodePath.join(projectRoot, "packages", "app");
356 + await NodeFSP.mkdir(cwd, { recursive: true });
357 + }
358 + let checkoutAttempted = false;
359 +
360 + const result = await checkoutNewTaskBranch({
361 + branch: { ...branch, worktreePath: source === "picker" ? worktreePath : null },
362 + project: { environmentId, workspaceRoot: cwd },
363 + workspaceMode: "local",
364 + readRefs: async (request) => {
365 + const result = await readRefs(request);
366 + if (!nested && result._tag === "Success") {
367 + // Older servers cannot prove whether this project is at the repository root.
368 + const { isAtRepositoryRoot: _isAtRepositoryRoot, ...value } = result.value;
369 + return { ...result, value };
370 + }
371 + return result;
372 + },
373 + switchRef: (request) => {
374 + checkoutAttempted = true;
375 + return refuseSwitch(request);
376 + },
377 + });
378 +
379 + expect(checkoutAttempted).toBe(false);
380 + expect((await git("branch", "--show-current")).stdout.trim()).toBe("main");
381 + expect(await NodeFSP.readFile(NodePath.join(projectRoot, "file.txt"), "utf8")).toBe("main\n");
382 + expect(
383 + (await exec("git", ["-C", worktreePath, "branch", "--show-current"])).stdout.trim(),
384 + ).toBe(branch.name);
385 + expect(await NodeFSP.readFile(NodePath.join(worktreePath, "file.txt"), "utf8")).toBe(
386 + "feature\n",
387 + );
388 + expect(result._tag).toBe("Failure");
389 + if (result._tag !== "Failure") throw new Error("Expected unsafe worktree reuse to fail");
390 + if (nested) {
391 + expect(String(squashAtomCommandFailure(result))).toMatch(/subdirectory/i);
392 + }
393 + },
394 + );
395 +
396 + it("keeps a nested project's cwd when historical metadata names the already-current branch", async () => {
397 + await git("checkout", branch.name);
398 + cwd = NodePath.join(cwd, "packages", "app");
399 + await NodeFSP.mkdir(cwd, { recursive: true });
400 +
401 + const result = await selectBranch(refuseSwitch);
402 +
403 + expect(result._tag).toBe("Success");
404 + if (result._tag !== "Success") throw new Error("Current branch selection failed");
405 + expect(result.value).toMatchObject({
406 + name: branch.name,
407 + current: true,
408 + worktreePath: null,
409 + });
410 + expect((await git("branch", "--show-current")).stdout.trim()).toBe(branch.name);
411 + });
412 });
apps/mobile/src/features/threads/checkout-new-task-branch.ts
+72 -10
@@ -4,16 +4,26 @@ import {
4 type AtomCommandResult,
5 mapAtomCommandResult,
6 } from "@t3tools/client-runtime/state/runtime";
7 -import type { VcsSwitchRefInput, VcsSwitchRefResult } from "@t3tools/contracts";
7 +import type {
8 + VcsListRefsInput,
9 + VcsListRefsResult,
10 + VcsSwitchRefInput,
11 + VcsSwitchRefResult,
12 +} from "@t3tools/contracts";
13 +import { deriveLocalBranchNameFromRemoteRef } from "@t3tools/shared/git";
14 import * as Cause from "effect/Cause";
15 import { AsyncResult } from "effect/reactivity";
16
11 -import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
17 +const VCS_REF_QUERY_MAX_LENGTH = 256;
18
19 export async function checkoutNewTaskBranch<E>(input: {
20 readonly branch: VcsRef;
21 readonly project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot"> | null;
22 readonly workspaceMode: "local" | "worktree";
23 + readonly readRefs: (request: {
24 + readonly environmentId: EnvironmentProject["environmentId"];
25 + readonly input: VcsListRefsInput;
26 + }) => Promise<AtomCommandResult<VcsListRefsResult, E>>;
27 readonly switchRef: (request: {
28 readonly environmentId: EnvironmentProject["environmentId"];
29 readonly input: VcsSwitchRefInput;
@@ -24,14 +34,56 @@ export async function checkoutNewTaskBranch<E>(input: {
34 Cause.fail(new Error("The selected project is unavailable. Reconnect and try again.")),
35 );
36 }
27 - if (
28 - !shouldCheckoutNewTaskBranch({
29 - branchIsCurrent: input.branch.current,
30 - branchWorktreePath: input.branch.worktreePath,
31 - workspaceMode: input.workspaceMode,
32 - })
33 - ) {
34 - return AsyncResult.success(input.branch);
37 + if (input.workspaceMode === "worktree" || input.branch.current) {
38 + return AsyncResult.success(
39 + input.branch.current ? { ...input.branch, worktreePath: null } : input.branch,
40 + );
41 + }
42 +
43 + // Remote refs omit local worktrees, and historical thread metadata can be stale.
44 + const localName = localBranchName(input.branch);
45 + let cursor: number | undefined;
46 + for (;;) {
47 + const refs = await input.readRefs({
48 + environmentId: input.project.environmentId,
49 + input: {
50 + cwd: input.project.workspaceRoot,
51 + // Bound the substring query; compare the full name across every page.
52 + query: localName.slice(0, VCS_REF_QUERY_MAX_LENGTH),
53 + refKind: "local",
54 + ...(cursor === undefined ? { refresh: true } : { cursor }),
55 + },
56 + });
57 + if (refs._tag === "Failure") return AsyncResult.failure(refs.cause);
58 + const local = refs.value.refs.find((ref) => ref.name === localName);
59 + if (
60 + local &&
61 + (!input.branch.isRemote || local.upstreamRef === `refs/remotes/${input.branch.name}`) &&
62 + (local.current || local.worktreePath)
63 + ) {
64 + if (local.current) return AsyncResult.success({ ...local, worktreePath: null });
65 + if (refs.value.isAtRepositoryRoot === undefined) {
66 + return AsyncResult.failure(
67 + Cause.fail(
68 + new Error(
69 + "The server did not report whether this project is at the repository root, so this worktree cannot be reused safely. Update the server or choose another branch.",
70 + ),
71 + ),
72 + );
73 + }
74 + if (!refs.value.isAtRepositoryRoot) {
75 + return AsyncResult.failure(
76 + Cause.fail(
77 + new Error(
78 + "This project is a repository subdirectory. Choose another branch or add the repository root as a project to reuse this worktree.",
79 + ),
80 + ),
81 + );
82 + }
83 + return AsyncResult.success(local);
84 + }
85 + if (local || refs.value.nextCursor === null) break;
86 + cursor = refs.value.nextCursor;
87 }
88
89 const result = await input.switchRef({
@@ -43,5 +95,15 @@ export async function checkoutNewTaskBranch<E>(input: {
95 current: true,
96 isRemote: false,
97 name: value.refName ?? input.branch.name,
98 + worktreePath: null,
99 }));
100 }
101 +
102 +// A remote name can itself contain slashes; prefer the authoritative prefix.
103 +function localBranchName(branch: VcsRef): string {
104 + if (!branch.isRemote) return branch.name;
105 + const prefix = branch.remoteName ? `${branch.remoteName}/` : null;
106 + return prefix && branch.name.startsWith(prefix)
107 + ? branch.name.slice(prefix.length)
108 + : deriveLocalBranchNameFromRemoteRef(branch.name);
109 +}
apps/server/src/vcs/GitVcsDriverCore.test.ts
+41 -2
@@ -26,6 +26,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
26 import {
27 GitCommandError,
28 ReviewDiffPreviewInput,
29 + VcsRef,
30 + VcsListRefsResult,
31 type ReviewDiffFileContentsInput,
32 type ReviewDiffPreviewResult,
33 type WorktreeSubmodules,
@@ -44,6 +46,8 @@ import { gitConfigEnv } from "./VcsProcess.ts";
46 import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts";
47
48 const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError));
49 +const decodeVcsRef = Schema.decodeUnknownSync(VcsRef);
50 +const decodeVcsListRefsResult = Schema.decodeUnknownSync(VcsListRefsResult);
51
52 const layerServerConfig = ServerConfig.layerTest(process.cwd(), {
53 prefix: "t3-git-vcs-driver-test-",
@@ -3827,7 +3831,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3831 });
3832
3833 describe("refName operations", () => {
3830 - it.effect("optionally includes remote refs that match local branches", () =>
3834 + it.effect("lists root and upstream metadata and optionally includes matching remote refs", () =>
3835 Effect.gen(function* () {
3836 const cwd = yield* makeTmpDir();
3837 const remote = yield* makeTmpDir("git-vcs-driver-remote-");
@@ -3835,6 +3839,10 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3839 yield* git(remote, ["init", "--bare"]);
3840 yield* git(cwd, ["remote", "add", "origin", remote]);
3841 yield* git(cwd, ["push", "-u", "origin", initialBranch]);
3842 + yield* git(cwd, ["remote", "add", "team/upstream", remote]);
3843 + yield* git(cwd, ["push", "team/upstream", "HEAD:refs/heads/feature/a"]);
3844 + yield* git(cwd, ["branch", "--track", "feature/a", "team/upstream/feature/a"]);
3845 + yield* git(cwd, ["branch", "--no-track", "local-only"]);
3846 const driver = yield* GitVcsDriver.GitVcsDriver;
3847
3848 const deduplicated = yield* driver.listRefs({ cwd });
@@ -3843,7 +3851,19 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3851 false,
3852 );
3853
3846 - const complete = yield* driver.listRefs({ cwd, includeMatchingRemoteRefs: true });
3854 + const worktreePath = yield* makeTmpDir("git-vcs-driver-worktree-");
3855 + yield* git(cwd, ["worktree", "add", worktreePath, "feature/a"]);
3856 + yield* writeTextFile(worktreePath, "packages/app/file.txt", "nested project\n");
3857 + const pathService = yield* Path.Path;
3858 + const nestedCwd = pathService.join(worktreePath, "packages", "app");
3859 + const complete = yield* driver.listRefs({
3860 + cwd: nestedCwd,
3861 + includeMatchingRemoteRefs: true,
3862 + });
3863 + const untracked = complete.refs.find((ref) => ref.name === "local-only");
3864 + assert.ok(untracked);
3865 + assert.equal("upstreamRef" in untracked, false);
3866 + assert.deepEqual(decodeVcsRef(untracked), untracked);
3867 assert.equal(
3868 complete.refs.some((ref) => ref.name === initialBranch),
3869 true,
@@ -3862,6 +3882,25 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3882 assert.equal(remoteOnly.refs.length, 1);
3883 assert.equal(remoteOnly.refs[0]?.name, `origin/${initialBranch}`);
3884 assert.equal(remoteOnly.refs[0]?.isRemote, true);
3885 +
3886 + const tracked = complete.refs.find((ref) => ref.name === "feature/a");
3887 + assert.ok(tracked);
3888 + assert.deepEqual(decodeVcsRef(tracked), {
3889 + ...tracked,
3890 + upstreamRef: "refs/remotes/team/upstream/feature/a",
3891 + });
3892 + const aliasCwd = pathService.join(cwd, "worktree-alias");
3893 + NodeFS.symlinkSync(worktreePath, aliasCwd, "junction");
3894 + const aliased = yield* driver.listRefs({ cwd: aliasCwd });
3895 + const expected = [
3896 + { ...complete, isAtRepositoryRoot: false },
3897 + { ...aliased, isAtRepositoryRoot: true },
3898 + ];
3899 + assert.deepEqual([complete, aliased], expected);
3900 + assert.deepEqual(
3901 + [decodeVcsListRefsResult(complete), decodeVcsListRefsResult(aliased)],
3902 + expected,
3903 + );
3904 }),
3905 );
3906
apps/server/src/vcs/GitVcsDriverCore.ts
+16 -2
@@ -161,6 +161,7 @@ class GitRefsRefreshCacheKey extends Data.Class<{
161 interface GitRepositoryPaths {
162 readonly gitCommonDir: string;
163 readonly worktreeRoot: string | null;
164 + readonly isAtRepositoryRoot: boolean | undefined;
165 readonly currentBranch: string | null;
166 }
167
@@ -1408,6 +1409,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1409 : path.resolve(cwd, worktreeRootOutput),
1410 )
1411 : null;
1412 + // Git reports physical roots, so resolve project aliases before comparing.
1413 + const isAtRepositoryRoot =
1414 + worktreeRoot === null
1415 + ? undefined
1416 + : yield* fileSystem.realPath(cwd).pipe(
1417 + Effect.map((physicalCwd) => path.relative(worktreeRoot, physicalCwd) === ""),
1418 + Effect.orElseSucceed(() => undefined),
1419 + );
1420 const currentBranchOutput = currentBranchResult.stdout.trim();
1421 const currentBranch =
1422 currentBranchResult.exitCode === 0 && currentBranchOutput.length > 0
@@ -1417,6 +1426,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1426 return {
1427 gitCommonDir,
1428 worktreeRoot,
1429 + isAtRepositoryRoot,
1430 currentBranch,
1431 } satisfies GitRepositoryPaths;
1432 });
@@ -3381,7 +3391,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3391 [
3392 ...gitDirArgs,
3393 "for-each-ref",
3384 - "--format=%(refname)%09%(committerdate:unix)%09%(symref)",
3394 + "--format=%(refname)%09%(committerdate:unix)%09%(symref)%09%(upstream)",
3395 "refs/heads",
3396 "refs/remotes",
3397 ],
@@ -3450,7 +3460,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3460
3461 for (const line of refsResult.stdout.split("\n")) {
3462 if (line.length === 0) continue;
3453 - const [fullRefName, lastCommitRaw, symbolicTarget] = line.split("\t");
3463 + const [fullRefName, lastCommitRaw, symbolicTarget, upstreamRef] = line.split("\t");
3464 if (!fullRefName || symbolicTarget) continue;
3465 const parsedLastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
3466 const lastCommit = Number.isFinite(parsedLastCommit) ? parsedLastCommit : 0;
@@ -3464,6 +3474,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3474 isRemote: false,
3475 isDefault: name === defaultBranch,
3476 worktreePath: worktreeMap.get(name) ?? null,
3477 + ...(upstreamRef ? { upstreamRef } : {}),
3478 },
3479 lastCommit,
3480 });
@@ -3660,6 +3671,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3671 });
3672
3673 return {
3674 + ...(repositoryPaths.isAtRepositoryRoot === undefined
3675 + ? {}
3676 + : { isAtRepositoryRoot: repositoryPaths.isAtRepositoryRoot }),
3677 refs: [...refs.refs],
3678 isRepo: true,
3679 hasPrimaryRemote: snapshot.hasPrimaryRemote,
packages/client-runtime/src/state/vcs.ts
+6
@@ -277,6 +277,12 @@ export function createVcsEnvironmentAtoms<R, E>(
277
278 return {
279 listRefs,
280 + // An uncached read for decisions that must match the repository now, not
281 + // the persisted list a picker renders from.
282 + readRefs: createEnvironmentRpcCommand(runtime, {
283 + label: "environment-data:vcs:read-refs",
284 + tag: WS_METHODS.vcsListRefs,
285 + }),
286 status: createEnvironmentSubscriptionAtomFamily(runtime, {
287 label: "environment-data:vcs:status",
288 idleTtlMs: VCS_STATUS_IDLE_TTL_MS,
packages/contracts/src/git.ts
+3
@@ -84,6 +84,8 @@ export const VcsRef = Schema.Struct({
84 name: TrimmedNonEmptyStringSchema,
85 isRemote: Schema.optional(Schema.Boolean),
86 remoteName: Schema.optional(TrimmedNonEmptyStringSchema),
87 + // Full Git ref, for example refs/remotes/origin/feature.
88 + upstreamRef: Schema.optional(TrimmedNonEmptyStringSchema),
89 current: Schema.Boolean,
90 isDefault: Schema.Boolean,
91 worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
@@ -276,6 +278,7 @@ export const VcsStatusStreamEvent = Schema.Union([
278 export type VcsStatusStreamEvent = typeof VcsStatusStreamEvent.Type;
279
280 export const VcsListRefsResult = Schema.Struct({
281 + isAtRepositoryRoot: Schema.optional(Schema.Boolean),
282 refs: Schema.Array(VcsRef),
283 isRepo: Schema.Boolean,
284 hasPrimaryRemote: Schema.Boolean,