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

WelcomeWizard.import.browser.test.tsx

388 lines13.4 KB

1import { RegistryContext } from "@effect/atom-react";
2import {
3 AuthOrchestrationOperateScope,
4 AuthOrchestrationReadScope,
5 EnvironmentId,
6 ProjectId,
7 type AgentSessionProjectCandidate,
8 type AuthEnvironmentScope,
9 type AuthSessionState,
10} from "@t3tools/contracts";
11import { AsyncResult, Atom } from "effect/reactivity";
12import { expect, it, vi } from "vite-plus/test";
13​
14import "~/index.css";
15import { act, render } from "../../../test/render";
16​
17type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
18type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
19type CreateProjectInput = {
20 environmentId: EnvironmentId;
21 input: { projectId: ProjectId; workspaceRoot: string };
22};
23const state = vi.hoisted(() => ({
24 selectedEnvironment: "primary",
25 addedEnvironments: [] as string[],
26 sessions: new Map<string, unknown>(),
27 projects: null as unknown,
28 providers: null as unknown,
29 config: null as unknown,
30 candidates: [] as AgentSessionProjectCandidate[],
31 createProject: vi.fn(),
32 importThreads: vi.fn(),
33 refreshProviders: vi.fn(),
34 connectPairing: vi.fn(),
35 completeOnboarding: vi.fn(),
36 onDone: vi.fn(),
37 scan: vi.fn(),
38 refreshScan: vi.fn(),
39 waitForProject: vi.fn(),
40}));
41​
42vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
43 const actual = await original();
44 return {
45 ...actual,
46 createEnvironmentSessionAtoms: ((runtime: never) => ({
47 ...actual.createEnvironmentSessionAtoms(runtime),
48 sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id),
49 })) as never,
50 };
51});
52vi.mock(import("../../cloud/publicConfig"), async (original) => ({
53 ...(await original()),
54 hasCloudPublicConfig: () => false,
55}));
56vi.mock(import("../../onboarding/firstRun"), async (original) => ({
57 ...(await original()),
58 completeOnboarding: state.completeOnboarding,
59}));
60vi.mock(import("../../state/environments"), async (original) => {
61 const environment = (environmentId: string) => ({
62 environmentId,
63 label: environmentId,
64 connection: { phase: "connected" },
65 entry: { enabled: true, target: { _tag: "DirectConnectionTarget" } },
66 });
67 const primary = environment("primary");
68 return {
69 ...(await original()),
70 usePrimaryEnvironment: (() => primary) as never,
71 useEnvironments: (() => ({
72 environments: [state.selectedEnvironment, ...state.addedEnvironments].map(environment),
73 })) as never,
74 };
75});
76vi.mock(import("../../state/server"), async (original) => {
77 const actual = await original();
78 return {
79 ...actual,
80 serverEnvironment: {
81 ...actual.serverEnvironment,
82 providersValueAtom: (() => state.providers) as never,
83 configValueAtom: (() => state.config) as never,
84 refreshProviders: "refreshProviders" as never,
85 },
86 };
87});
88vi.mock(import("../../state/entities"), async (original) => {
89 const { useAtomValue } = await import("@effect/atom-react");
90 return {
91 ...(await original()),
92 useProjects: (() => useAtomValue(state.projects as Atom.Atom<Project[]>)) as never,
93 readProjects: (() => appAtomRegistry.get(state.projects as Atom.Atom<Project[]>)) as never,
94 waitForProject: ((ref: unknown) => state.waitForProject(ref)) as never,
95 };
96});
97vi.mock(import("../../state/projects"), async (original) => ({
98 ...(await original()),
99 projectEnvironment: { create: "createProject" } as never,
100}));
101vi.mock(import("../../state/agentSessions"), async (original) => ({
102 ...(await original()),
103 agentSessionImport: "importThreads" as never,
104}));
105vi.mock(import("../../onboarding/useProjectScans"), async (original) => ({
106 ...(await original()),
107 useProjectScans: (ids: readonly EnvironmentId[]) =>
108 ids.map((environmentId) => {
109 state.scan({ environmentId });
110 return {
111 environmentId,
112 data: { candidates: state.candidates, truncated: false } as never,
113 isPending: false,
114 error: null,
115 refresh: state.refreshScan,
116 };
117 }),
118}));
119vi.mock(import("../../connection/onboarding"), async (original) => ({
120 ...(await original()),
121 connectPairing: "connectPairing" as never,
122}));
123vi.mock(import("../../state/use-atom-command"), async (original) => ({
124 ...(await original()),
125 useAtomCommand: ((
126 command: "createProject" | "importThreads" | "refreshProviders" | "connectPairing",
127 ) => state[command]) as never,
128}));
129vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
130 ...(await original()),
131 ChatGptWelcomeCoordinator: () => <></>,
132}));
133​
134import { appAtomRegistry } from "../../rpc/atomRegistry";
135import { WelcomeWizard } from "./WelcomeWizard";
136​
137const primaryId = EnvironmentId.make("primary");
138const remoteId = EnvironmentId.make("remote");
139const permissionMessage = "This connection cannot import projects or thread history.";
140​
141function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
142 return {
143 authenticated: true,
144 scopes: [AuthOrchestrationReadScope, ...scopes],
145 auth: {
146 policy: "remote-reachable",
147 bootstrapMethods: ["one-time-token"],
148 sessionMethods: ["bearer-access-token"],
149 sessionCookieName: "t3_session",
150 },
151 };
153​
154function sessionAtom(environmentId: EnvironmentId) {
155 return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
157​
158function projectsAtom() {
159 return state.projects as Atom.Writable<ReadonlyArray<Project>>;
161​
162function setGrant(environmentId: EnvironmentId, allowed: boolean) {
163 appAtomRegistry.set(
164 sessionAtom(environmentId),
165 AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
166 );
168​
169// Default selection only picks recently active projects, so pin "now".
170const NOW = Date.parse("2026-01-01T00:00:00.000Z");
171​
172function candidate(path: string): AgentSessionProjectCandidate {
173 return {
174 path,
175 title: path.split("/").at(-1)!,
176 sources: ["codex"],
177 threadCount: 10,
178 lastActiveAt: new Date(NOW - 60_000).toISOString(),
179 alreadyImported: false,
180 };
182​
183function recordProject({ environmentId, input }: CreateProjectInput) {
184 appAtomRegistry.set(projectsAtom(), [
185 ...appAtomRegistry.get(projectsAtom()),
186 { id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
187 ]);
188 return AsyncResult.success(undefined);
190​
191// Resolves once the project reaches the mocked projects atom; the real helper's timeout is
192// replaced per test with a rejection.
193function waitForRecordedProject(ref: { environmentId: EnvironmentId; projectId: string }) {
194 const find = () =>
195 appAtomRegistry
196 .get(projectsAtom())
197 .find(
198 (project) => project.id === ref.projectId && project.environmentId === ref.environmentId,
199 );
200 return new Promise<Project>((resolve) => {
201 const current = find();
202 if (current) return resolve(current);
203 const unsubscribe = appAtomRegistry.subscribe(projectsAtom(), () => {
204 const project = find();
205 if (!project) return;
206 unsubscribe();
207 resolve(project);
208 });
209 });
211​
212function deferred<T>() {
213 let resolve!: (value: T) => void;
214 const promise = new Promise<T>((complete) => {
215 resolve = complete;
216 });
217 return { promise, resolve };
219​
220function pageText() {
221 return document.body.textContent ?? "";
223​
224function button(label: string) {
225 const found = [...document.querySelectorAll("button")].find(
226 (element) => element.textContent?.trim() === label,
227 );
228 if (!found) throw new Error(`Missing button: ${label}`);
229 return found;
231​
232async function click(label: string) {
233 const target = button(label);
234 expect(target.disabled).toBe(false);
235 await act(async () => target.click());
237​
238async function clickStage(label: string) {
239 const stage = document.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
240 expect(stage?.disabled).toBe(false);
241 await act(async () => stage?.click());
243​
244async function mountImport(remote = false) {
245 state.selectedEnvironment = remote ? "remote" : "primary";
246 await using stack = new AsyncDisposableStack();
247 const screen = stack.use(
248 await render(
249 <RegistryContext.Provider value={appAtomRegistry}>
250 <WelcomeWizard localAvailable={!remote} onDone={state.onDone} />
251 </RegistryContext.Provider>,
252 ),
253 );
254 await click("Continue");
255 await click("Continue");
256 expect(pageText()).toContain("Import your projects");
257 stack.move();
258 return screen;
260​
261// The mocked modules read `state`, so every test starts by replacing all of it.
262// Returns the clock spy so each test can `using` it; the spy would otherwise outlive the test.
263function setup() {
264 const now = vi.spyOn(Date, "now").mockReturnValue(NOW);
265 state.addedEnvironments = [];
266 state.sessions.clear();
267 for (const id of [primaryId, remoteId]) {
268 state.sessions.set(
269 id,
270 Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
271 Atom.keepAlive,
272 ),
273 );
274 }
275 state.projects = Atom.make<ReadonlyArray<Project>>([]).pipe(Atom.keepAlive);
276 state.providers = Atom.make<ReadonlyArray<never>>([]).pipe(Atom.keepAlive);
277 state.config = Atom.make(null).pipe(Atom.keepAlive);
278 state.candidates = [candidate("/projects/first"), candidate("/projects/second")];
279 state.createProject
280 .mockReset()
281 .mockImplementation(async (input: CreateProjectInput) => recordProject(input));
282 state.importThreads
283 .mockReset()
284 .mockResolvedValue(AsyncResult.success({ importedCount: 1, skippedCount: 0 }));
285 state.refreshProviders.mockReset().mockResolvedValue(AsyncResult.success(undefined));
286 state.connectPairing.mockReset().mockResolvedValue(AsyncResult.success(remoteId));
287 state.completeOnboarding.mockReset().mockResolvedValue(undefined);
288 state.onDone.mockReset();
289 state.scan.mockReset();
290 state.refreshScan.mockReset();
291 state.waitForProject.mockReset().mockImplementation(waitForRecordedProject);
292 return now;
294​
295it("keeps the project selection after going back a stage", async () => {
296 using _now = setup();
297 await using _screen = await mountImport();
298 await click("Select none");
299 expect(pageText()).toContain("0 of 2 selected");
300​
301 await clickStage("Agents, step 2");
302 await click("Continue");
303 expect(pageText()).toContain("Import your projects");
304 expect(pageText()).toContain("0 of 2 selected");
305});
306​
307it("ticks the recent projects of a computer added after the selection changed", async () => {
308 using _now = setup();
309 await using _screen = await mountImport();
310 await click("Select none");
311​
312 state.addedEnvironments = ["remote"];
313 await clickStage("Connect, step 1");
314 await click("Continue");
315 await click("Continue");
316 expect(pageText()).toContain("2 of 4 selected");
317​
318 await click("Import 2 projects");
319 const created = state.createProject.mock.calls as Array<[CreateProjectInput]>;
320 expect(created.map(([call]) => call.environmentId)).toEqual([remoteId, remoteId]);
321});
322​
323it("rechecks after project creation and can retry its history without recreating the project", async () => {
324 using _now = setup();
325 const creation = deferred<void>();
326 state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
327 await creation.promise;
328 return recordProject(input);
329 });
330 await using _screen = await mountImport();
331 await click("Import 2 projects");
332 expect(state.createProject).toHaveBeenCalledOnce();
333 await act(async () => {
334 setGrant(primaryId, false);
335 creation.resolve();
336 await creation.promise;
337 });
338 expect(state.importThreads).not.toHaveBeenCalled();
339 expect(state.createProject).toHaveBeenCalledOnce();
340 expect(state.onDone).not.toHaveBeenCalled();
341 expect(pageText()).toContain(permissionMessage);
342​
343 await act(async () => setGrant(primaryId, true));
344 await click("Import 2 projects");
345 expect(state.createProject).toHaveBeenCalledTimes(2);
346 expect(state.importThreads).toHaveBeenCalledTimes(2);
347 expect(state.onDone).toHaveBeenCalledOnce();
348});
349​
350it("completes accepted imports when permission is revoked after the final server write", async () => {
351 using _now = setup();
352 state.candidates = state.candidates.slice(0, 1);
353 const imported = deferred<{ importedCount: number; skippedCount: number }>();
354 state.importThreads.mockImplementationOnce(async () =>
355 AsyncResult.success(await imported.promise),
356 );
357 await using _screen = await mountImport();
358 await click("Import 1 project");
359 await act(async () => {
360 setGrant(primaryId, false);
361 imported.resolve({ importedCount: 1, skippedCount: 0 });
362 await imported.promise;
363 });
364 expect(state.createProject).toHaveBeenCalledOnce();
365 expect(state.importThreads).toHaveBeenCalledOnce();
366 expect(state.completeOnboarding).toHaveBeenCalledOnce();
367 expect(state.onDone).toHaveBeenCalledOnce();
368});
369​
370it("finishes setup without landing when the imported project never reaches the client", async () => {
371 using _now = setup();
372 state.candidates = state.candidates.slice(0, 1);
373 // The server accepts the project, but it never shows up in the client's projects.
374 state.createProject.mockResolvedValue(AsyncResult.success(undefined));
375 state.waitForProject.mockRejectedValue(new Error("The project did not appear."));
376 state.completeOnboarding.mockRejectedValueOnce(new Error("offline"));
377 await using _screen = await mountImport();
378​
379 await click("Import 1 project");
380 await vi.waitFor(() => expect(state.completeOnboarding).toHaveBeenCalledOnce());
381 // A failed completion hands the step back instead of leaving it importing.
382 await vi.waitFor(() => expect(button("Import 1 project").disabled).toBe(false));
383 expect(state.onDone).not.toHaveBeenCalled();
384​
385 await click("Import 1 project");
386 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
387 expect(state.onDone).toHaveBeenCalledWith(undefined);
388});