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

WelcomeWizard.browser.test.tsx

223 lines7.4 KB

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