Open History to see the last commit
1import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
2import { act, type ComponentProps } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
5import { page, userEvent } from "vite-plus/test/browser";
6
7import "~/index.css";
8
9const state = vi.hoisted(() => ({
10 worktreePath: "/tmp/worktree" as string | null,
11 showContextMenu: vi.fn(),
12 writeTextToClipboard: vi.fn(),
13}));
14
15vi.mock(import("../localApi"), async (original) => ({
16 ...(await original()),
17 readLocalApi: (() => ({ contextMenu: { show: state.showContextMenu } })) as never,
18}));
19vi.mock(import("../hooks/useCopyToClipboard"), async (original) => ({
20 ...(await original()),
21 writeTextToClipboard: state.writeTextToClipboard,
22 useCopyToClipboard: ((options: { target: string }) => ({
23 copyToClipboard: (command: string) => state.writeTextToClipboard(command, options.target),
24 isCopied: false,
25 })) as never,
26}));
27vi.mock(import("./BranchToolbarBranchSelector"), async (original) => ({
28 ...(await original()),
29 BranchToolbarBranchSelector: (() => null) as never,
30}));
31vi.mock(import("../state/entities"), async (original) => ({
32 ...(await original()),
33 useQuietThreadShell: (() => ({
34 environmentId: "local",
35 projectId: "project",
36 worktreePath: state.worktreePath,
37 })) as never,
38 useProject: (() => ({ workspaceRoot: "/tmp/project" })) as never,
39 useThreadShellsForProjectRefs: () => [],
40}));
41
42import { BranchToolbar } from "./BranchToolbar";
43import { ComposerSurface } from "./chat/ComposerSurface";
44import type { ServerUpdateTarget } from "./ServerUpdateAction";
45
46let root: Root;
47let container: HTMLDivElement;
48
49beforeEach(() => {
50 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
51 state.worktreePath = "/tmp/worktree";
52 state.showContextMenu.mockReset().mockResolvedValue("copy-path");
53 state.writeTextToClipboard.mockReset().mockResolvedValue(true);
54 container = document.createElement("div");
55 document.body.append(container);
56 root = createRoot(container);
57});
58
59afterEach(async () => {
60 await act(async () => root.unmount());
61 container.remove();
62 vi.unstubAllGlobals();
63});
64
65function render(props: Partial<ComponentProps<typeof BranchToolbar>>) {
66 return act(async () =>
67 root.render(
68 <ComposerSurface.Shell>
69 <BranchToolbar
70 layout="panel"
71 panelSection="workspace"
72 environmentId={EnvironmentId.make("local")}
73 threadId={ThreadId.make("thread")}
74 showGitControls
75 envMode="local"
76 envLocked={false}
77 startFromOrigin={false}
78 onStartFromOriginChange={vi.fn()}
79 onEnvModeChange={vi.fn()}
80 {...props}
81 />
82 </ComposerSurface.Shell>,
83 ),
84 );
85}
86
87it("keeps machine choices usable when the combined row's workspace is locked", async () => {
88 const onEnvironmentChange = vi.fn();
89 await render({
90 onEnvironmentChange,
91 availableEnvironments: ["local", "remote"].map((id) => ({
92 environmentId: EnvironmentId.make(id),
93 projectId: ProjectId.make("project"),
94 label: id,
95 isPrimary: id === "local",
96 machine: "server",
97 })),
98 });
99 const trigger = container.querySelector("button")!;
100 expect(trigger.textContent).toBe("local");
101 expect(container.querySelectorAll("button")).toHaveLength(1);
102
103 // A ctrl-click is a macOS secondary click; it must not open the menu.
104 await act(async () => {
105 trigger.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, ctrlKey: true }));
106 });
107 expect(document.querySelector('[role="menu"]')).toBeNull();
108
109 await userEvent.click(trigger);
110 await expect
111 .element(page.getByRole("menuitemradio", { name: "New worktree" }))
112 .toHaveAttribute("aria-disabled", "true");
113 await userEvent.click(page.getByRole("menuitemradio", { name: "remote" }));
114 expect(onEnvironmentChange).toHaveBeenCalledWith("remote");
115});
116
117it("shows a started thread's primary machine as a static label in the composer", async () => {
118 await render({
119 layout: "composer",
120 showGitControls: false,
121 availableEnvironments: ["local", "remote"].map((id) => ({
122 environmentId: EnvironmentId.make(id),
123 projectId: ProjectId.make("project"),
124 label: id,
125 isPrimary: id === "local",
126 machine: "server",
127 })),
128 });
129 expect(container.textContent).toBe("local");
130 expect(container.querySelector("button")).toBeNull();
131});
132
133it.each([
134 ["local", null, "/tmp/project"],
135 ["worktree", null, null],
136 ["worktree", "/tmp/worktree", "/tmp/worktree"],
137] as const)(
138 "copies only an existing workspace path with mode %s and worktree %s",
139 async (envMode, worktreePath, copiedPath) => {
140 state.worktreePath = worktreePath;
141 await render({ envMode });
142 const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
143 await act(async () => {
144 container.querySelector('[aria-label="Run context"]')!.dispatchEvent(event);
145 });
146 expect(event.defaultPrevented).toBe(copiedPath !== null);
147 if (copiedPath === null) {
148 expect(state.showContextMenu).not.toHaveBeenCalled();
149 expect(state.writeTextToClipboard).not.toHaveBeenCalled();
150 } else {
151 await vi.waitFor(() =>
152 expect(state.writeTextToClipboard).toHaveBeenCalledWith(copiedPath, "workspace path"),
153 );
154 }
155 },
156);
157
158it.each([
159 { layout: "wide Git", width: 900, showGitControls: true },
160 { layout: "narrow Git", width: 360, showGitControls: true },
161 { layout: "sole primary non-Git", width: 360, showGitControls: false },
162])(
163 "copies the pending update from the $layout composer chip",
164 async ({ width, showGitControls }) => {
165 await page.viewport(1000, 700);
166 container.style.width = `${width}px`;
167 container.style.setProperty("--chat-content-max-width", `${width}px`);
168 const serverUpdate = {
169 environmentId: EnvironmentId.make("local"),
170 serverLabel: "Build box",
171 serverVersion: "0.0.30",
172 targetVersion: "0.0.31",
173 selfUpdate: null,
174 installation: { kind: "npm-global", prefix: "/opt/node" },
175 } satisfies ServerUpdateTarget & { serverVersion: string };
176 await render({
177 layout: "composer",
178 envLocked: showGitControls,
179 showGitControls,
180 availableEnvironments: [
181 {
182 environmentId: serverUpdate.environmentId,
183 projectId: ProjectId.make("project"),
184 label: serverUpdate.serverLabel,
185 isPrimary: true,
186 machine: "server",
187 },
188 ],
189 serverUpdate,
190 });
191
192 expect(
193 container.querySelector('[data-slot="composer-shell"]')!.getBoundingClientRect().width,
194 ).toBe(width);
195 const chip = page.getByRole("button", { name: /Build box|Copy update command/ });
196 await expect.element(chip).toBeVisible();
197 await userEvent.hover(chip);
198 await expect.element(page.getByRole("tooltip")).toMatchTextContent("0.0.30");
199 await expect.element(page.getByRole("tooltip")).toMatchTextContent("0.0.31");
200 await userEvent.click(chip);
201 await vi.waitFor(() =>
202 expect(state.writeTextToClipboard).toHaveBeenCalledWith(
203 "npm install --global --prefix '/opt/node' t3@0.0.31",
204 "update command",
205 ),
206 );
207 },
208);