Open History to see the last commit
1// @vitest-environment jsdom
2import { act } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { EnvironmentId, ProjectId } from "@t3tools/contracts";
5import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6
7const mocks = vi.hoisted(() => ({
8 importThreads: vi.fn(),
9 createProject: vi.fn(),
10 complete: vi.fn(),
11 refresh: vi.fn(),
12 toast: vi.fn(),
13 projects: [] as Array<{ id: string; environmentId: string; workspaceRoot: string }>,
14}));
15vi.mock("../../state/session", () => ({
16 useEnvironmentScope: () => true,
17 useEnvironmentsWithScope: (environments: Array<{ environmentId: string }>) =>
18 new Set(environments.map((entry) => entry.environmentId)),
19 readEnvironmentScope: () => true,
20}));
21vi.mock("../../state/agentSessions", () => ({ agentSessionImport: "import" }));
22vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "create" } }));
23vi.mock("../../state/use-atom-command", () => ({
24 useAtomCommand: (command: string) =>
25 command === "import"
26 ? mocks.importThreads
27 : command === "create"
28 ? mocks.createProject
29 : mocks.refresh,
30}));
31vi.mock("../../onboarding/firstRun", () => ({ useCompleteOnboarding: () => mocks.complete }));
32vi.mock("../../state/entities", () => ({
33 useProjects: () => mocks.projects,
34 readProjects: () => mocks.projects,
35}));
36vi.mock("../../state/environments", () => {
37 const environment = {
38 environmentId: "test-env",
39 label: "Computer",
40 connection: { phase: "connected" },
41 };
42 return {
43 useEnvironments: () => ({ environments: [environment] }),
44 usePrimaryEnvironment: () => environment,
45 };
46});
47vi.mock("../../state/server", () => ({
48 serverEnvironment: {
49 providersValueAtom: () => [],
50 configValueAtom: () => null,
51 refreshProviders: "refresh",
52 },
53}));
54vi.mock("@effect/atom-react", () => ({ useAtomValue: (value: unknown) => value }));
55vi.mock("../../onboarding/useProjectScans", () => ({
56 useProjectScans: () => [
57 {
58 environmentId: "test-env",
59 isPending: false,
60 error: null,
61 refresh: mocks.refresh,
62 data: {
63 truncated: false,
64 candidates: [
65 {
66 path: "/project",
67 title: "project",
68 projectId: "test-project",
69 threadCount: 29,
70 lastActiveAt: new Date().toISOString(),
71 sources: ["codex"],
72 },
73 ],
74 },
75 },
76 ],
77}));
78vi.mock("../../connection/onboarding", () => ({ connectPairing: vi.fn() }));
79vi.mock("../../state/terminal", () => ({ terminalEnvironment: {} }));
80vi.mock("../clerk/useT3ConnectAuthPrompt", () => ({ useT3ConnectAuthPrompt: vi.fn() }));
81vi.mock("../../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
82vi.mock("../ThreadTerminalDrawer", () => ({ TerminalViewport: () => null }));
83vi.mock("../settings/ChatGptWelcomeCoordinator", () => ({ ChatGptWelcomeCoordinator: () => null }));
84vi.mock("../settings/CodexSetupSection", () => ({
85 CodexSetupSection: () => null,
86 AddManagedCodexAccountDialog: () => null,
87}));
88vi.mock("../cloud/CloudEnvironmentConnectList", () => ({
89 CloudEnvironmentConnectRows: () => null,
90}));
91vi.mock("../ui/toast", () => ({
92 toastManager: { add: mocks.toast, close: vi.fn(), update: vi.fn() },
93}));
94
95import { WelcomeWizard } from "./WelcomeWizard";
96
97let root: Root;
98let container: HTMLDivElement;
99
100beforeEach(() => {
101 vi.clearAllMocks();
102 vi.stubGlobal(
103 "ResizeObserver",
104 class {
105 observe() {}
106 unobserve() {}
107 disconnect() {}
108 },
109 );
110 Object.defineProperty(Element.prototype, "getAnimations", {
111 configurable: true,
112 value: () => [],
113 });
114 mocks.projects = [{ id: "test-project", environmentId: "test-env", workspaceRoot: "/project" }];
115 mocks.complete.mockResolvedValue(undefined);
116 mocks.refresh.mockResolvedValue(undefined);
117 mocks.importThreads.mockResolvedValue({
118 _tag: "Success",
119 value: { importedCount: 28, skippedCount: 1 },
120 });
121 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
122 container = document.createElement("div");
123 document.body.append(container);
124 root = createRoot(container);
125});
126afterEach(async () => {
127 await act(async () => root.unmount());
128 container.remove();
129});
130
131async function click(label: string) {
132 const button = [...document.querySelectorAll("button")].find(
133 (element) => element.textContent?.trim() === label,
134 );
135 expect(button, `button ${label}`).toBeDefined();
136 await act(async () => button!.click());
137}
138
139it("enters the workspace after a partial import and warns after navigation finishes", async () => {
140 let finishNavigation = () => {};
141 const navigation = new Promise<void>((resolve) => {
142 finishNavigation = resolve;
143 });
144 const onDone = vi.fn(() => navigation);
145 await act(async () => root.render(<WelcomeWizard localAvailable onDone={onDone} />));
146 await click("Continue");
147 await click("Continue");
148 await click("Import 1 project");
149 expect(onDone).toHaveBeenCalledWith({
150 environmentId: EnvironmentId.make("test-env"),
151 projectId: ProjectId.make("test-project"),
152 });
153 expect(mocks.toast).not.toHaveBeenCalled();
154 await act(async () => finishNavigation());
155 expect(mocks.toast).toHaveBeenCalledWith(
156 expect.objectContaining({
157 type: "warning",
158 description: "Imported 28 threads. 1 thread could not be imported.",
159 }),
160 );
161 expect(mocks.toast.mock.invocationCallOrder[0]).toBeGreaterThan(
162 onDone.mock.invocationCallOrder[0]!,
163 );
164});
165
166it.each([
167 [0, 0, null],
168 [29, 0, null],
169 [1, 0, null],
170 [0, 1, "1 thread could not be imported."],
171 [0, 2, "2 threads could not be imported."],
172] as const)(
173 "finishes setup with %i imported and %i skipped threads",
174 async (importedCount, skippedCount, warning) => {
175 mocks.importThreads.mockResolvedValue({
176 _tag: "Success",
177 value: { importedCount, skippedCount },
178 });
179 const onDone = vi.fn();
180 await act(async () => root.render(<WelcomeWizard localAvailable onDone={onDone} />));
181 await click("Continue");
182 await click("Continue");
183 await click("Import 1 project");
184 expect(onDone).toHaveBeenCalledOnce();
185 if (warning === null && importedCount > 0) {
186 expect(mocks.toast).toHaveBeenCalledWith({
187 type: "success",
188 title: `Imported ${importedCount} ${importedCount === 1 ? "thread" : "threads"}`,
189 });
190 } else if (warning === null) {
191 expect(mocks.toast).not.toHaveBeenCalled();
192 } else {
193 expect(mocks.toast).toHaveBeenCalledWith(
194 expect.objectContaining({ type: "warning", description: warning }),
195 );
196 }
197 },
198);
199
200it("keeps setup open when saving completion fails and preserves the import warning on retry", async () => {
201 mocks.complete.mockRejectedValueOnce(new Error("settings unavailable"));
202 const onDone = vi.fn();
203 await act(async () => root.render(<WelcomeWizard localAvailable onDone={onDone} />));
204 await click("Continue");
205 await click("Continue");
206 await click("Import 1 project");
207 expect(onDone).not.toHaveBeenCalled();
208 expect(mocks.toast).toHaveBeenCalledWith(
209 expect.objectContaining({ type: "error", title: "Could not finish setup" }),
210 );
211 await click("Do not import projects");
212 expect(onDone).toHaveBeenCalledOnce();
213 expect(mocks.importThreads).toHaveBeenCalledOnce();
214 expect(mocks.toast).toHaveBeenLastCalledWith(
215 expect.objectContaining({
216 type: "warning",
217 description: "Imported 28 threads. 1 thread could not be imported.",
218 }),
219 );
220});