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

AddProjectToMachineDialog.browser.test.tsx

311 lines11.3 KB

1import { EnvironmentId, ProjectId, type ProjectCloneSnapshot } from "@t3tools/contracts";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import { describe, expect, it, vi } from "vite-plus/test";
4import { page, userEvent } from "vite-plus/test/browser";
5​
6import { act, render } from "../../test/render";
7​
8const clone = vi.hoisted(() => vi.fn());
9const snapshots = vi.hoisted(() => vi.fn<() => ReadonlyArray<ProjectCloneSnapshot>>());
10​
11vi.mock(import("../lib/addProjectToMachine"), async (original) => ({
12 ...(await original()),
13 addProjectToMachine: clone,
14}));
15vi.mock(import("../state/projectClones"), async (original) => ({
16 ...(await original()),
17 // Clones land on the target machine only.
18 useEnvironmentProjectClones: (environmentId) =>
19 environmentId === "environment-2" ? snapshots() : [],
20}));
21​
22const project = vi.hoisted(() => {
23 let value: unknown = null;
24 const listeners = new Set<() => void>();
25 return {
26 // Each test starts from no project and no listeners left by an earlier test.
27 setup: (initial: unknown) => {
28 value = initial;
29 listeners.clear();
30 },
31 get: () => value,
32 set: (next: unknown) => {
33 value = next;
34 for (const listener of listeners) listener();
35 },
36 subscribe: (listener: () => void) => {
37 listeners.add(listener);
38 return () => listeners.delete(listener);
39 },
40 };
41});
42​
43vi.mock(import("../state/entities"), async (original) => {
44 const { useSyncExternalStore } = await import("react");
45 return {
46 ...(await original()),
47 readProject: (() => project.get()) as never,
48 subscribeProject: ((_ref: unknown, listener: (value: unknown) => void) =>
49 project.subscribe(() => listener(project.get()))) as never,
50 useProject: (() => useSyncExternalStore(project.subscribe, project.get)) as never,
51 };
52});
53vi.mock(import("../state/environments"), async (original) => ({
54 ...(await original()),
55 useEnvironments: (() => ({
56 environments: [
57 { environmentId: EnvironmentId.make("environment-2") },
58 {
59 environmentId: EnvironmentId.make("environment-3"),
60 serverConfig: {
61 environment: {
62 platform: { machine: "linux" },
63 capabilities: { ignoredFileListing: true, ignoredFileSearch: true },
64 },
65 },
66 },
67 ],
68 })) as never,
69}));
70vi.mock(import("../state/projects"), async (original) => {
71 const { AsyncResult, Atom } = await import("effect/reactivity");
72 const actual = await original();
73 const listing = Atom.make(
74 AsyncResult.success({ files: [{ path: ".env", byteLength: 12 }], truncated: true }),
75 );
76 return {
77 ...actual,
78 projectEnvironment: { ...actual.projectEnvironment, listIgnoredFiles: () => listing },
79 };
80});
81vi.mock(import("../state/filesystem"), async (original) => {
82 const { AsyncResult, Atom } = await import("effect/reactivity");
83 const actual = await original();
84 const home = Atom.make(
85 AsyncResult.success({
86 parentPath: "/remote/home",
87 entries: [{ name: "Work", fullPath: "/remote/home/Work" }],
88 }),
89 );
90 const work = Atom.make(AsyncResult.success({ parentPath: "/remote/home/Work", entries: [] }));
91 return {
92 ...actual,
93 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
94 filesystemEnvironment: {
95 ...actual.filesystemEnvironment,
96 browse: ({ environmentId, input }) => {
97 if (environmentId !== "environment-2") throw new Error("Expected the target environment");
98 return input.partialPath === "~/" ? home : work;
99 },
100 },
101 };
102});
103vi.mock(import("../hooks/useHandleNewThread"), async (original) => ({
104 ...(await original()),
105 useNewThreadHandler: (() => () => undefined) as never,
106}));
107vi.mock(import("../hooks/useAddProjectTargets"), async (original) => ({
108 ...(await original()),
109 useAddProjectTargets: () => [
110 {
111 environmentId: EnvironmentId.make("environment-2"),
112 label: "Remote machine",
113 machine: "linux",
114 },
115 ],
116}));
117vi.mock(import("../hooks/useLogicalProjectEnvironments"), async (original) => ({
118 ...(await original()),
119 useLogicalProjectEnvironments: (() => []) as never,
120}));
121​
122import {
123 AddProjectToMachineDialogHost,
124 openAddProjectToMachine,
125} from "./AddProjectToMachineDialog";
126import { ProjectCloneToastCoordinator } from "./ProjectCloneToastCoordinator";
127import { ToastProvider } from "./ui/toast";
128​
129const environmentId = EnvironmentId.make("environment-1");
130const projectRef = scopeProjectRef(environmentId, ProjectId.make("project-1"));
131const nextProjectRef = scopeProjectRef(environmentId, ProjectId.make("project-2"));
132// Only environment-3 can list ignored files.
133const searchableProjectRef = scopeProjectRef(
134 EnvironmentId.make("environment-3"),
135 ProjectId.make("project-3"),
136);
137const PROJECT = {
138 environmentId,
139 id: projectRef.projectId,
140 title: "Repo",
141 workspaceRoot: "/repo",
142 repositoryIdentity: null,
143};
144​
145function CloneDialogWithToasts() {
146 return (
147 <ToastProvider>
148 <ProjectCloneToastCoordinator />
149 <AddProjectToMachineDialogHost />
150 </ToastProvider>
151 );
153​
154describe("AddProjectToMachineDialog", () => {
155 it("chooses a destination from the other machine and keeps it editable", async () => {
156 project.setup({
157 ...PROJECT,
158 repositoryIdentity: {
159 rootPath: "/repo",
160 locator: { remoteUrl: "https://example.com/owner/repo.git" },
161 },
162 });
163 await using screen = await render(<AddProjectToMachineDialogHost />);
164 await act(() => openAddProjectToMachine({ projectRef, targetEnvironmentId: null }));
165​
166 const browse = screen.getByRole("button", { name: "Browse" });
167 const folder = screen.getByRole("textbox", { name: /^Folder on/ });
168 const picker = screen.getByRole("region", { name: "Choose clone location" });
169 await browse.click();
170 await picker.getByRole("button", { name: "Work" }).click();
171 await userEvent.keyboard("{Escape}");
172 await expect.element(picker).not.toBeInTheDocument();
173 await expect.element(folder).toHaveValue("~/repo");
174​
175 await browse.click();
176 await picker.getByRole("button", { name: "Work" }).click();
177 await picker.getByRole("button", { name: "Set clone location" }).click();
178 await expect.element(folder).toHaveValue("/remote/home/Work/repo");
179 await folder.fill("/remote/home/Work/renamed");
180 await expect.element(folder).toHaveValue("/remote/home/Work/renamed");
181 });
182​
183 it("keeps the replacement open after the dismissed clone finishes starting", async () => {
184 project.setup(PROJECT);
185 const reply = Promise.withResolvers<ProjectId>();
186 const requested = Promise.withResolvers<ProjectId>();
187 clone.mockImplementationOnce(({ projectId }: { projectId: ProjectId }) => {
188 requested.resolve(projectId);
189 return reply.promise;
190 });
191 snapshots.mockReturnValue([]);
192 await using screen = await render(<CloneDialogWithToasts />);
193​
194 await act(() => openAddProjectToMachine({ projectRef, targetEnvironmentId: null }));
195 const folder = screen.getByRole("textbox", { name: /^Folder on/ });
196 await folder.fill("/checkout");
197 await userEvent.keyboard("{Enter}");
198 await expect.element(screen.getByRole("button", { name: "Starting…" })).toBeDisabled();
199 const projectId = await requested.promise;
200 snapshots.mockReturnValue([
201 {
202 projectId,
203 remoteUrl: "https://example.com/repo.git",
204 destinationPath: "/checkout",
205 repository: null,
206 phase: "running",
207 stage: "connecting",
208 percent: null,
209 detail: null,
210 error: null,
211 startedAt: "2026-01-01T00:00:00.000Z",
212 endedAt: null,
213 sequence: 1,
214 },
215 ]);
216 await screen.rerender(<CloneDialogWithToasts />);
217 await userEvent.keyboard("{Escape}");
218​
219 await act(() => {
220 project.set({ ...PROJECT, id: nextProjectRef.projectId, title: "Next repo" });
221 openAddProjectToMachine({ projectRef: nextProjectRef, targetEnvironmentId: null });
222 });
223 await expect.element(screen.getByText(/Clone Next repo/)).toBeVisible();
224 const progress = page.getByText("Cloning checkout", { exact: true });
225 await expect.element(progress).not.toBeInTheDocument();
226 reply.resolve(projectId);
227 await expect.element(progress).toBeVisible();
228 await expect.element(screen.getByText(/Clone Next repo/)).toBeVisible();
229 });
230​
231 it("closes when its project goes away", async () => {
232 project.setup(PROJECT);
233 await using screen = await render(<AddProjectToMachineDialogHost />);
234​
235 await act(() => openAddProjectToMachine({ projectRef, targetEnvironmentId: null }));
236 await expect.element(screen.getByText("Add to another machine")).toBeInTheDocument();
237​
238 await act(() => project.set(null));
239 await act(() => project.set(PROJECT));
240 await expect.element(screen.getByText("Add to another machine")).not.toBeInTheDocument();
241 });
242​
243 it("does not reopen for a project that vanished before the dialog showed", async () => {
244 project.setup(PROJECT);
245 await using screen = await render(<AddProjectToMachineDialogHost />);
246​
247 await act(() => {
248 openAddProjectToMachine({ projectRef, targetEnvironmentId: null });
249 project.set(null);
250 });
251 await act(() => project.set(PROJECT));
252​
253 await expect.element(screen.getByText("Add to another machine")).not.toBeInTheDocument();
254 });
255​
256 it("clears the ignored file search on Escape before closing", async () => {
257 project.setup({
258 ...PROJECT,
259 environmentId: searchableProjectRef.environmentId,
260 id: searchableProjectRef.projectId,
261 });
262 await using screen = await render(<AddProjectToMachineDialogHost />);
263​
264 await act(() =>
265 openAddProjectToMachine({ projectRef: searchableProjectRef, targetEnvironmentId: null }),
266 );
267 const file = screen.getByRole("checkbox", { name: /\.env/ });
268 await file.click();
269 await expect.element(file).not.toBeChecked();
270 const dialog = screen.getByRole("dialog", { name: "Add to another machine" });
271 const search = screen.getByRole("searchbox", { name: "Search ignored files" });
272 await search.fill("env");
273 for (const composition of [
274 { key: "Escape", isComposing: true, keyCode: 27 },
275 { key: "Escape", isComposing: false, keyCode: 229 },
276 ]) {
277 // Safari ends the composition just before the Escape keydown.
278 await act(() => {
279 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
280 search
281 .element()
282 .dispatchEvent(
283 new KeyboardEvent("keydown", { ...composition, bubbles: true, cancelable: true }),
284 );
285 });
286 await expect.element(search).toHaveValue("env");
287 await expect.element(dialog).toHaveAttribute("data-open");
288 }
289​
290 await userEvent.keyboard("{Escape}");
291 await expect.element(search).toHaveValue("");
292 await expect.element(search).toHaveFocus();
293 await expect.element(search).toHaveAttribute("type", "text");
294 await expect.element(file).not.toBeChecked();
295 // Holding Escape repeats the keydown, which must not also close the dialog.
296 await act(() => {
297 search.element().dispatchEvent(
298 new KeyboardEvent("keydown", {
299 key: "Escape",
300 repeat: true,
301 bubbles: true,
302 cancelable: true,
303 }),
304 );
305 });
306 await expect.element(dialog).toHaveAttribute("data-open");
307​
308 await userEvent.keyboard("{Escape}");
309 await expect.element(dialog).not.toBeInTheDocument();
310 });
311});