Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BranchToolbar.logic.test.ts

500 lines15.8 KB

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