Open History to see the last commit
1import {
2 EnvironmentId,
3 GitCommandError,
4 ProviderInstanceId,
5 RunId,
6 type VcsRef,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "vite-plus/test";
9import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
10import {
11 deriveLocalBranchNameFromRemoteRef,
12 isWorktreeChangeBlocked,
13 resolveBranchSelectionTarget,
14 resolveDraftEnvModeAfterBranchChange,
15 resolveEffectiveEnvMode,
16 resolveBranchToolbarPrBranch,
17 resolveConfirmedSelectedRef,
18 resolveDefaultWorktreeBaseBranch,
19 resolveLocalCheckoutBranchMismatch,
20 resolveLockedWorkspaceLabel,
21 sanitizeNewRefName,
22 shouldIncludeBranchPickerItem,
23 isBranchHoldCurrent,
24 offersWorkspaceModes,
25 toBranchActionErrorMessage,
26} from "./BranchToolbar.logic";
27
28describe("toBranchActionErrorMessage", () => {
29 it("shows a Git failure's detail without the operation and cwd", () => {
30 const error = new GitCommandError({
31 operation: "GitVcsDriver.switchRef.checkout",
32 command: "git",
33 cwd: "/tmp/repo",
34 detail: "Commit, stash, or discard them, then switch again.",
35 });
36
37 expect(toBranchActionErrorMessage(error)).toBe(
38 "Commit, stash, or discard them, then switch again.",
39 );
40 expect(toBranchActionErrorMessage(new Error("boom"))).toBe("boom");
41 });
42});
43
44describe("resolveDraftEnvModeAfterBranchChange", () => {
45 it("switches to local mode when returning from an existing worktree to the main worktree", () => {
46 expect(
47 resolveDraftEnvModeAfterBranchChange({
48 nextWorktreePath: null,
49 currentWorktreePath: "/repo/.t3/worktrees/feature-a",
50 effectiveEnvMode: "worktree",
51 }),
52 ).toBe("local");
53 });
54
55 it("uses worktree mode when selecting a ref already attached to a worktree", () => {
56 expect(
57 resolveDraftEnvModeAfterBranchChange({
58 nextWorktreePath: "/repo/.t3/worktrees/feature-a",
59 currentWorktreePath: null,
60 effectiveEnvMode: "local",
61 }),
62 ).toBe("worktree");
63 });
64});
65
66describe("resolveBranchToolbarPrBranch", () => {
67 it("hides PR state while an optimistic branch switch is in flight", () => {
68 expect(
69 resolveBranchToolbarPrBranch({
70 activeThreadBranch: "feature/current",
71 resolvedActiveBranch: "feature/next",
72 }),
73 ).toBeNull();
74 });
75});
76
77describe("resolveDefaultWorktreeBaseBranch", () => {
78 it("offers nothing while a clone has no refs, then the default branch once they are listed", () => {
79 expect(resolveDefaultWorktreeBaseBranch([])).toBeNull();
80 expect(
81 resolveDefaultWorktreeBaseBranch([
82 { name: "feature", isDefault: false, current: true },
83 { name: "staging", isDefault: true, current: false },
84 ]),
85 ).toBe("staging");
86 expect(
87 resolveDefaultWorktreeBaseBranch([
88 { name: "other", isDefault: false, current: false },
89 { name: "feature", isDefault: false, current: true },
90 ]),
91 ).toBe("feature");
92 });
93});
94
95describe("resolveLocalCheckoutBranchMismatch", () => {
96 it("detects when a local thread is associated with a different branch than the checkout", () => {
97 expect(
98 resolveLocalCheckoutBranchMismatch({
99 effectiveEnvMode: "local",
100 activeWorktreePath: null,
101 activeThreadBranch: "feature/thread",
102 currentGitBranch: "feature/current",
103 }),
104 ).toEqual({
105 threadBranch: "feature/thread",
106 currentBranch: "feature/current",
107 });
108 });
109
110 it("ignores dedicated worktrees because their checkout is already thread-scoped", () => {
111 expect(
112 resolveLocalCheckoutBranchMismatch({
113 effectiveEnvMode: "worktree",
114 activeWorktreePath: "/repo/.t3/worktrees/feature-thread",
115 activeThreadBranch: "feature/thread",
116 currentGitBranch: "feature/current",
117 }),
118 ).toBeNull();
119 });
120});
121
122describe("resolveEffectiveEnvMode", () => {
123 it("keeps a server thread in worktree mode while its worktree is still being created", () => {
124 expect(
125 resolveEffectiveEnvMode({
126 activeWorktreePath: null,
127 hasServerThread: true,
128 draftThreadEnvMode: undefined,
129 preparingWorktree: true,
130 }),
131 ).toBe("worktree");
132 expect(
133 resolveEffectiveEnvMode({
134 activeWorktreePath: null,
135 hasServerThread: true,
136 draftThreadEnvMode: undefined,
137 }),
138 ).toBe("local");
139 });
140});
141
142describe("offersWorkspaceModes", () => {
143 it("offers worktrees from a repository or tracked repositories, never in No project", () => {
144 const folder = { isScratchProject: false, isGitRepo: false, tracksGitRepositories: false };
145 expect(offersWorkspaceModes(folder)).toBe(false);
146 expect(offersWorkspaceModes({ ...folder, isGitRepo: true })).toBe(true);
147 expect(offersWorkspaceModes({ ...folder, tracksGitRepositories: true })).toBe(true);
148 // Git status assumes a repository until it loads.
149 expect(offersWorkspaceModes({ ...folder, isScratchProject: true, isGitRepo: true })).toBe(
150 false,
151 );
152 });
153});
154
155describe("resolveLockedWorkspaceLabel", () => {
156 it.each([
157 ["/home/me/.t3/worktrees/app/t3-ff466c42", "t3-ff466c42"],
158 ["/home/me/.t3/worktrees/app/t3-ff466c42/", "t3-ff466c42"],
159 ["C:\\Users\\me\\worktrees\\feature-x", "feature-x"],
160 ])("names the worktree at %s", (path, label) => {
161 expect(resolveLockedWorkspaceLabel(path, "worktree")).toBe(label);
162 });
163});
164
165describe("deriveLocalBranchNameFromRemoteRef", () => {
166 it("supports remote names that contain slashes", () => {
167 expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
168 "upstream/feature/demo",
169 );
170 });
171
172 it("strips the whole remote name when it is known", () => {
173 expect(deriveLocalBranchNameFromRemoteRef("team/origin/feature", "team/origin")).toBe(
174 "feature",
175 );
176 });
177});
178
179describe("dedupeRemoteBranchesWithLocalMatches", () => {
180 it.each([
181 ["feature/demo", "origin/feature/demo", true],
182 ["feature/demo", "feature/demo", false],
183 ["demo", "demo", true],
184 ["origin/", "origin/", true],
185 ["/demo", "/demo", true],
186 ["", "", false],
187 ])("filters origin ref %s / %s (hidden: %s)", (localName, remoteName, hidden) => {
188 const input: VcsRef[] = [
189 {
190 name: localName,
191 current: false,
192 isDefault: false,
193 worktreePath: null,
194 },
195 {
196 name: remoteName,
197 isRemote: true,
198 remoteName: "origin",
199 current: false,
200 isDefault: false,
201 worktreePath: null,
202 },
203 {
204 name: "origin/feature/remote-only",
205 isRemote: true,
206 remoteName: "origin",
207 current: false,
208 isDefault: false,
209 worktreePath: null,
210 },
211 ];
212
213 const result = dedupeRemoteBranchesWithLocalMatches(input);
214 const expected = hidden ? [input[0], input[2]] : input;
215 expect(result).toEqual(expected);
216 for (const [index, ref] of result.entries()) {
217 expect(ref).toBe(expected[index]);
218 }
219 });
220
221 it("keeps non-origin remote refs visible when git tracks with first-slash local naming", () => {
222 const input: VcsRef[] = [
223 {
224 name: "upstream/feature",
225 current: false,
226 isDefault: false,
227 worktreePath: null,
228 },
229 {
230 name: "my-org/upstream/feature",
231 isRemote: true,
232 remoteName: "my-org/upstream",
233 current: false,
234 isDefault: false,
235 worktreePath: null,
236 },
237 ];
238
239 expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
240 "upstream/feature",
241 "my-org/upstream/feature",
242 ]);
243 });
244});
245
246describe("resolveBranchSelectionTarget", () => {
247 it("reuses an existing secondary worktree for the selected ref", () => {
248 expect(
249 resolveBranchSelectionTarget({
250 activeProjectCwd: "/repo/nested-checkout/packages/app",
251 activeProjectCheckoutRoot: "/repo/nested-checkout",
252 activeWorktreePath: null,
253 refName: { isDefault: true, worktreePath: "/repo" },
254 }),
255 ).toEqual({
256 checkoutCwd: "/repo",
257 nextWorktreePath: "/repo",
258 reuseExistingWorktree: true,
259 staysInActiveCheckout: false,
260 });
261 expect(
262 resolveBranchSelectionTarget({
263 activeProjectCwd: "/repo",
264 activeWorktreePath: "/repo/.t3/worktrees/feature-a",
265 refName: {
266 isDefault: false,
267 worktreePath: "/repo/.t3/worktrees/feature-b",
268 },
269 }),
270 ).toEqual({
271 checkoutCwd: "/repo/.t3/worktrees/feature-b",
272 nextWorktreePath: "/repo/.t3/worktrees/feature-b",
273 reuseExistingWorktree: true,
274 staysInActiveCheckout: false,
275 });
276 });
277
278 it("switches back to the main repo when the ref already lives there", () => {
279 // A subdirectory project's own checkout is reported at the repository root.
280 // The checkout root is undefined until the project's status loads.
281 for (const [activeProjectCwd, activeWorktreePath, activeProjectCheckoutRoot] of [
282 ["/repo", "/repo/.t3/worktrees/feature-a", "/repo"],
283 ["/repo/packages/app", "/repo/.t3/worktrees/feature-a", "/repo"],
284 ["/repo/packages/app", null, "/repo"],
285 ["/repo/packages/app", "/repo/.t3/worktrees/feature-a", undefined],
286 ["/repo/packages/app", null, undefined],
287 ] as const) {
288 expect(
289 resolveBranchSelectionTarget({
290 activeProjectCwd,
291 activeProjectCheckoutRoot,
292 activeWorktreePath,
293 refName: {
294 isDefault: true,
295 worktreePath: "/repo",
296 },
297 }),
298 ).toEqual({
299 checkoutCwd: "/repo",
300 nextWorktreePath: null,
301 reuseExistingWorktree: true,
302 // A ref listed in the thread's own checkout may be stale, so it is checked out, not assumed.
303 staysInActiveCheckout: activeWorktreePath === null,
304 });
305 }
306 });
307
308 it("keeps checkout in the current worktree for non-default refs", () => {
309 expect(
310 resolveBranchSelectionTarget({
311 activeProjectCwd: "/repo",
312 activeWorktreePath: "/repo/.t3/worktrees/feature-a",
313 refName: {
314 isDefault: false,
315 worktreePath: null,
316 },
317 }),
318 ).toEqual({
319 checkoutCwd: "/repo/.t3/worktrees/feature-a",
320 nextWorktreePath: "/repo/.t3/worktrees/feature-a",
321 reuseExistingWorktree: false,
322 staysInActiveCheckout: true,
323 });
324 });
325});
326
327describe("isWorktreeChangeBlocked", () => {
328 const runtime = (status: "preparing" | "running" | "completed") => ({
329 status,
330 activeRunId: status === "completed" ? null : RunId.make("run"),
331 providerInstanceId: ProviderInstanceId.make("codex"),
332 providerName: null,
333 lastError: null,
334 });
335
336 it.each([
337 ["preparing", "/repo/wt-a", null, true],
338 ["running", "/repo/wt-a", "/repo/wt-b", true],
339 ["running", null, "/repo/wt-b", true],
340 ["running", "/repo/wt-a", "/repo/wt-a", false],
341 ["completed", "/repo/wt-a", null, false],
342 ] as const)(
343 "a %s turn moving %s -> %s is blocked: %s",
344 (status, currentWorktreePath, nextWorktreePath, blocked) => {
345 expect(
346 isWorktreeChangeBlocked({
347 runtime: runtime(status),
348 currentWorktreePath,
349 nextWorktreePath,
350 }),
351 ).toBe(blocked);
352 },
353 );
354});
355
356describe("shouldIncludeBranchPickerItem", () => {
357 it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => {
358 expect(
359 shouldIncludeBranchPickerItem({
360 itemValue: "__checkout_pull_request__:1359",
361 normalizedQuery: "gh pr checkout 1359",
362 createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
363 checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
364 }),
365 ).toBe(true);
366 });
367
368 it("surfaces an existing ref matching the sanitized query", () => {
369 expect(
370 shouldIncludeBranchPickerItem({
371 itemValue: "new-branch",
372 normalizedQuery: "new branch",
373 createBranchItemValue: null,
374 checkoutPullRequestItemValue: null,
375 }),
376 ).toBe(true);
377 });
378});
379
380describe("isBranchHoldCurrent", () => {
381 const environmentId = EnvironmentId.make("env-a");
382 const hold = {
383 branch: "feature",
384 environmentId,
385 checkouts: [{ cwd: "/repo", replaces: "main" }],
386 };
387 const current = { canonicalBranch: "main", environmentId, cwd: "/repo" };
388
389 it("keeps showing the checked-out branch while status still reports the old one", () => {
390 expect(isBranchHoldCurrent(hold, current)).toBe(true);
391 });
392
393 it("lets go once status moves, even to a different branch than the checkout", () => {
394 for (const canonicalBranch of ["feature", "other", null]) {
395 expect(isBranchHoldCurrent(hold, { ...current, canonicalBranch })).toBe(false);
396 }
397 });
398
399 it("does not apply to another checkout that happens to be on the old branch", () => {
400 expect(isBranchHoldCurrent(hold, { ...current, cwd: "/other" })).toBe(false);
401 });
402
403 it("follows a thread moving from its worktree to the project root", () => {
404 const moveHold = {
405 branch: "main",
406 environmentId,
407 checkouts: [
408 { cwd: "/repo-feature", replaces: "feature" },
409 { cwd: "/repo", replaces: "dev" },
410 ],
411 };
412 expect(
413 isBranchHoldCurrent(moveHold, {
414 environmentId,
415 cwd: "/repo-feature",
416 canonicalBranch: "feature",
417 }),
418 ).toBe(true);
419 expect(
420 isBranchHoldCurrent(moveHold, { environmentId, cwd: "/repo", canonicalBranch: "dev" }),
421 ).toBe(true);
422 expect(
423 isBranchHoldCurrent(moveHold, { environmentId, cwd: "/repo", canonicalBranch: "main" }),
424 ).toBe(false);
425 });
426
427 it("does not apply to the same path on another environment", () => {
428 expect(
429 isBranchHoldCurrent(hold, { ...current, environmentId: EnvironmentId.make("env-b") }),
430 ).toBe(false);
431 });
432});
433
434describe("sanitizeNewRefName", () => {
435 it("collapses a run of whitespace into a single dash", () => {
436 expect(sanitizeNewRefName("new branch")).toBe("new-branch");
437 });
438
439 it("replaces tabs, which git rejects just like spaces", () => {
440 expect(sanitizeNewRefName("new\tbranch")).toBe("new-branch");
441 });
442
443 it("preserves whitespace that git accepts", () => {
444 expect(sanitizeNewRefName("new\u00a0branch")).toBe("new\u00a0branch");
445 expect(sanitizeNewRefName("new\u2009branch")).toBe("new\u2009branch");
446 });
447
448 it("does not collapse dashes the user typed", () => {
449 expect(sanitizeNewRefName("new - branch")).toBe("new---branch");
450 expect(sanitizeNewRefName("foo--bar")).toBe("foo--bar");
451 });
452});
453
454describe("resolveConfirmedSelectedRef", () => {
455 const listed: VcsRef = {
456 name: "previous",
457 isRemote: false,
458 current: false,
459 isDefault: false,
460 worktreePath: "/worktree-b",
461 };
462
463 it.each([
464 [
465 "the claimed worktree still has it checked out",
466 [{ ...listed, current: true }],
467 "/worktree-b",
468 ],
469 ["the claimed worktree has moved to another branch", [], null],
470 ["the claimed worktree lists it but not as current", [listed], null],
471 ["the read failed", null, null],
472 ] as const)("%s", (_label, refs, expected) => {
473 expect(resolveConfirmedSelectedRef(listed, refs === null ? null : { refs }).worktreePath).toBe(
474 expected,
475 );
476 });
477});