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