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