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

WelcomeWizard.import.browser.test.tsx

306 lines10.3 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 sessions: new Map<string, unknown>(),
26 projects: null as unknown,
27 providers: null as unknown,
28 config: null as unknown,
29 candidates: [] as AgentSessionProjectCandidate[],
30 createProject: vi.fn(),
31 importThreads: vi.fn(),
32 refreshProviders: vi.fn(),
33 connectPairing: vi.fn(),
34 completeOnboarding: vi.fn(),
35 onDone: vi.fn(),
36 scan: vi.fn(),
37 refreshScan: vi.fn(),
38}));
39​
40vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
41 const actual = await original();
42 return {
43 ...actual,
44 createEnvironmentSessionAtoms: ((runtime: never) => ({
45 ...actual.createEnvironmentSessionAtoms(runtime),
46 sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id),
47 })) as never,
48 };
49});
50vi.mock(import("../../cloud/publicConfig"), async (original) => ({
51 ...(await original()),
52 hasCloudPublicConfig: () => false,
53}));
54vi.mock(import("../../onboarding/firstRun"), async (original) => ({
55 ...(await original()),
56 completeOnboarding: state.completeOnboarding,
57}));
58vi.mock(import("../../state/environments"), async (original) => {
59 const environment = (environmentId: string) => ({
60 environmentId,
61 label: environmentId,
62 connection: { phase: "connected" },
63 entry: { enabled: true, target: { _tag: "DirectConnectionTarget" } },
64 });
65 const primary = environment("primary");
66 return {
67 ...(await original()),
68 usePrimaryEnvironment: (() => primary) as never,
69 useEnvironments: (() => ({ environments: [environment(state.selectedEnvironment)] })) as never,
70 };
71});
72vi.mock(import("../../state/server"), async (original) => {
73 const actual = await original();
74 return {
75 ...actual,
76 serverEnvironment: {
77 ...actual.serverEnvironment,
78 providersValueAtom: (() => state.providers) as never,
79 configValueAtom: (() => state.config) as never,
80 refreshProviders: "refreshProviders" as never,
81 },
82 };
83});
84vi.mock(import("../../state/entities"), async (original) => {
85 const { useAtomValue } = await import("@effect/atom-react");
86 return {
87 ...(await original()),
88 useProjects: (() => useAtomValue(state.projects as Atom.Atom<Project[]>)) as never,
89 readProjects: (() => appAtomRegistry.get(state.projects as Atom.Atom<Project[]>)) as never,
90 };
91});
92vi.mock(import("../../state/projects"), async (original) => ({
93 ...(await original()),
94 projectEnvironment: { create: "createProject" } as never,
95}));
96vi.mock(import("../../state/agentSessions"), async (original) => ({
97 ...(await original()),
98 agentSessionImport: "importThreads" as never,
99}));
100vi.mock(import("../../onboarding/useProjectScans"), async (original) => ({
101 ...(await original()),
102 useProjectScans: (ids: readonly EnvironmentId[]) =>
103 ids.map((environmentId) => {
104 state.scan({ environmentId });
105 return {
106 environmentId,
107 data: { candidates: state.candidates, truncated: false } as never,
108 isPending: false,
109 error: null,
110 refresh: state.refreshScan,
111 };
112 }),
113}));
114vi.mock(import("../../connection/onboarding"), async (original) => ({
115 ...(await original()),
116 connectPairing: "connectPairing" as never,
117}));
118vi.mock(import("../../state/use-atom-command"), async (original) => ({
119 ...(await original()),
120 useAtomCommand: ((
121 command: "createProject" | "importThreads" | "refreshProviders" | "connectPairing",
122 ) => state[command]) as never,
123}));
124vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
125 ...(await original()),
126 ChatGptWelcomeCoordinator: () => <></>,
127}));
128​
129import { appAtomRegistry } from "../../rpc/atomRegistry";
130import { WelcomeWizard } from "./WelcomeWizard";
131​
132const primaryId = EnvironmentId.make("primary");
133const remoteId = EnvironmentId.make("remote");
134const permissionMessage = "This connection cannot import projects or thread history.";
135​
136function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
137 return {
138 authenticated: true,
139 scopes: [AuthOrchestrationReadScope, ...scopes],
140 auth: {
141 policy: "remote-reachable",
142 bootstrapMethods: ["one-time-token"],
143 sessionMethods: ["bearer-access-token"],
144 sessionCookieName: "t3_session",
145 },
146 };
148​
149function sessionAtom(environmentId: EnvironmentId) {
150 return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
152​
153function projectsAtom() {
154 return state.projects as Atom.Writable<ReadonlyArray<Project>>;
156​
157function setGrant(environmentId: EnvironmentId, allowed: boolean) {
158 appAtomRegistry.set(
159 sessionAtom(environmentId),
160 AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
161 );
163​
164// Default selection only picks recently active projects, so pin "now".
165const NOW = Date.parse("2026-01-01T00:00:00.000Z");
166​
167function candidate(path: string): AgentSessionProjectCandidate {
168 return {
169 path,
170 title: path.split("/").at(-1)!,
171 sources: ["codex"],
172 threadCount: 10,
173 lastActiveAt: new Date(NOW - 60_000).toISOString(),
174 alreadyImported: false,
175 };
177​
178function recordProject({ environmentId, input }: CreateProjectInput) {
179 appAtomRegistry.set(projectsAtom(), [
180 ...appAtomRegistry.get(projectsAtom()),
181 { id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
182 ]);
183 return AsyncResult.success(undefined);
185​
186function deferred<T>() {
187 let resolve!: (value: T) => void;
188 const promise = new Promise<T>((complete) => {
189 resolve = complete;
190 });
191 return { promise, resolve };
193​
194function pageText() {
195 return document.body.textContent ?? "";
197​
198function button(label: string) {
199 const found = [...document.querySelectorAll("button")].find(
200 (element) => element.textContent?.trim() === label,
201 );
202 if (!found) throw new Error(`Missing button: ${label}`);
203 return found;
205​
206async function click(label: string) {
207 const target = button(label);
208 expect(target.disabled).toBe(false);
209 await act(async () => target.click());
211​
212async function mountImport(remote = false) {
213 state.selectedEnvironment = remote ? "remote" : "primary";
214 await using stack = new AsyncDisposableStack();
215 const screen = stack.use(
216 await render(
217 <RegistryContext.Provider value={appAtomRegistry}>
218 <WelcomeWizard localAvailable={!remote} onDone={state.onDone} />
219 </RegistryContext.Provider>,
220 ),
221 );
222 await click("Continue");
223 await click("Continue");
224 expect(pageText()).toContain("Import your projects");
225 stack.move();
226 return screen;
228​
229// The mocked modules read `state`, so every test starts by replacing all of it.
230// Returns the clock spy so each test can `using` it; the spy would otherwise outlive the test.
231function setup() {
232 const now = vi.spyOn(Date, "now").mockReturnValue(NOW);
233 state.sessions.clear();
234 for (const id of [primaryId, remoteId]) {
235 state.sessions.set(
236 id,
237 Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
238 Atom.keepAlive,
239 ),
240 );
241 }
242 state.projects = Atom.make<ReadonlyArray<Project>>([]).pipe(Atom.keepAlive);
243 state.providers = Atom.make<ReadonlyArray<never>>([]).pipe(Atom.keepAlive);
244 state.config = Atom.make(null).pipe(Atom.keepAlive);
245 state.candidates = [candidate("/projects/first"), candidate("/projects/second")];
246 state.createProject
247 .mockReset()
248 .mockImplementation(async (input: CreateProjectInput) => recordProject(input));
249 state.importThreads
250 .mockReset()
251 .mockResolvedValue(AsyncResult.success({ importedCount: 1, skippedCount: 0 }));
252 state.refreshProviders.mockReset().mockResolvedValue(AsyncResult.success(undefined));
253 state.connectPairing.mockReset().mockResolvedValue(AsyncResult.success(remoteId));
254 state.completeOnboarding.mockReset().mockResolvedValue(undefined);
255 state.onDone.mockReset();
256 state.scan.mockReset();
257 state.refreshScan.mockReset();
258 return now;
260​
261it("rechecks after project creation and can retry its history without recreating the project", async () => {
262 using _now = setup();
263 const creation = deferred<void>();
264 state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
265 await creation.promise;
266 return recordProject(input);
267 });
268 await using _screen = await mountImport();
269 await click("Import 2 projects");
270 expect(state.createProject).toHaveBeenCalledOnce();
271 await act(async () => {
272 setGrant(primaryId, false);
273 creation.resolve();
274 await creation.promise;
275 });
276 expect(state.importThreads).not.toHaveBeenCalled();
277 expect(state.createProject).toHaveBeenCalledOnce();
278 expect(state.onDone).not.toHaveBeenCalled();
279 expect(pageText()).toContain(permissionMessage);
280​
281 await act(async () => setGrant(primaryId, true));
282 await click("Import 2 projects");
283 expect(state.createProject).toHaveBeenCalledTimes(2);
284 expect(state.importThreads).toHaveBeenCalledTimes(2);
285 expect(state.onDone).toHaveBeenCalledOnce();
286});
287​
288it("completes accepted imports when permission is revoked after the final server write", async () => {
289 using _now = setup();
290 state.candidates = state.candidates.slice(0, 1);
291 const imported = deferred<{ importedCount: number; skippedCount: number }>();
292 state.importThreads.mockImplementationOnce(async () =>
293 AsyncResult.success(await imported.promise),
294 );
295 await using _screen = await mountImport();
296 await click("Import 1 project");
297 await act(async () => {
298 setGrant(primaryId, false);
299 imported.resolve({ importedCount: 1, skippedCount: 0 });
300 await imported.promise;
301 });
302 expect(state.createProject).toHaveBeenCalledOnce();
303 expect(state.importThreads).toHaveBeenCalledOnce();
304 expect(state.completeOnboarding).toHaveBeenCalledOnce();
305 expect(state.onDone).toHaveBeenCalledOnce();
306});