The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 816 lines 30.2 KB
Raw
1 import { RegistryContext } from "@effect/atom-react";
2 import {
3 AuthOrchestrationOperateScope,
4 AuthOrchestrationReadScope,
5 AuthRelayReadScope,
6 AuthRelayWriteScope,
7 AuthTerminalOperateScope,
8 EnvironmentId,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 type AgentSessionProjectCandidate,
13 type AuthEnvironmentScope,
14 type AuthSessionState,
15 type EnvironmentCloudLinkStateResult,
16 type ServerProvider,
17 } from "@t3tools/contracts";
18 import { AsyncResult, Atom } from "effect/reactivity";
19 import { expect, it, vi } from "vite-plus/test";
20
21 import "~/index.css";
22 import { act, render } from "../../../test/render";
23
24 type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
25 type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
26 type CreateProjectInput = {
27 environmentId: EnvironmentId;
28 input: { projectId: ProjectId; workspaceRoot: string };
29 };
30 const state = vi.hoisted(() => ({
31 sessions: new Map<string, unknown>(),
32 projects: null as unknown,
33 providers: null as unknown,
34 config: null as unknown,
35 candidates: null as unknown,
36 createProject: vi.fn(),
37 importThreads: vi.fn(),
38 refreshProviders: vi.fn(),
39 completeOnboarding: vi.fn(),
40 onDone: vi.fn(),
41 scan: vi.fn(),
42 refreshScan: vi.fn(),
43 waitForProject: vi.fn(),
44 cloud: false,
45 auth: { isLoaded: true, isSignedIn: false, userId: null as string | null },
46 linkState: null as unknown,
47 linkError: null as string | null,
48 refreshLinkState: vi.fn(),
49 scanError: null as string | null,
50 scanPending: false,
51 runningTerminalIds: null as unknown,
52 openTerminal: vi.fn(),
53 writeTerminal: vi.fn(),
54 closeTerminal: vi.fn(),
55 }));
56
57 vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
58 const actual = await original();
59 return {
60 ...actual,
61 createEnvironmentSessionAtoms: ((runtime: never) => ({
62 ...actual.createEnvironmentSessionAtoms(runtime),
63 sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id),
64 })) as never,
65 };
66 });
67 vi.mock(import("../../cloud/publicConfig"), async (original) => ({
68 ...(await original()),
69 hasCloudPublicConfig: () => state.cloud,
70 }));
71 vi.mock(import("@clerk/react"), async (original) => ({
72 ...(await original()),
73 useAuth: (() => state.auth) as never,
74 }));
75 vi.mock(import("../clerk/clerkLoadFailure"), async (original) => ({
76 ...(await original()),
77 useClerkLoadFailed: () => false,
78 }));
79 vi.mock(import("../clerk/useT3ConnectAuthPrompt"), async (original) => ({
80 ...(await original()),
81 useT3ConnectAuthPrompt: (() => ({ openAuthPrompt: () => {} })) as never,
82 }));
83 vi.mock(import("../../cloud/cloudLinkState"), async (original) => {
84 const { useAtomValue } = await import("@effect/atom-react");
85 return {
86 ...(await original()),
87 useCloudLinkState: (() => ({
88 data: useAtomValue(state.linkState as Atom.Atom<EnvironmentCloudLinkStateResult | null>),
89 error: state.linkError,
90 isPending: false,
91 refresh: state.refreshLinkState,
92 })) as never,
93 };
94 });
95 vi.mock(import("../../onboarding/firstRun"), async (original) => ({
96 ...(await original()),
97 completeOnboarding: state.completeOnboarding,
98 }));
99 vi.mock(import("../../state/environments"), async (original) => ({
100 ...(await original()),
101 useEnvironments: (() => ({
102 environments: [{ environmentId: "primary", label: "primary" }],
103 })) as never,
104 usePrimaryEnvironmentId: (() => "primary") as never,
105 }));
106 vi.mock(import("../../state/server"), async (original) => {
107 const actual = await original();
108 return {
109 ...actual,
110 serverEnvironment: {
111 ...actual.serverEnvironment,
112 providersValueAtom: (() => state.providers) as never,
113 configValueAtom: (() => state.config) as never,
114 refreshProviders: "refreshProviders" as never,
115 },
116 };
117 });
118 vi.mock(import("../../state/entities"), async (original) => {
119 const { useAtomValue } = await import("@effect/atom-react");
120 return {
121 ...(await original()),
122 useProjects: (() => useAtomValue(state.projects as Atom.Atom<Project[]>)) as never,
123 readProjects: (() => appAtomRegistry.get(state.projects as Atom.Atom<Project[]>)) as never,
124 waitForProject: ((ref: unknown) => state.waitForProject(ref)) as never,
125 };
126 });
127 vi.mock(import("../../state/projects"), async (original) => ({
128 ...(await original()),
129 projectEnvironment: { create: "createProject" } as never,
130 }));
131 vi.mock(import("../../state/agentSessions"), async (original) => ({
132 ...(await original()),
133 agentSessionImport: "importThreads" as never,
134 }));
135 vi.mock(import("../../onboarding/useProjectScans"), async (original) => {
136 const { useAtomValue } = await import("@effect/atom-react");
137 return {
138 ...(await original()),
139 useProjectScans: (ids: readonly EnvironmentId[]) => {
140 const candidates = useAtomValue(
141 state.candidates as Atom.Atom<AgentSessionProjectCandidate[]>,
142 );
143 return ids.map((environmentId) => {
144 state.scan({ environmentId });
145 return {
146 environmentId,
147 data: (state.scanPending ? null : { candidates, truncated: false }) as never,
148 isPending: state.scanPending,
149 error: state.scanError,
150 refresh: state.refreshScan,
151 };
152 });
153 },
154 };
155 });
156 vi.mock(import("../../state/terminal"), async (original) => {
157 const actual = await original();
158 return {
159 ...actual,
160 terminalEnvironment: {
161 ...actual.terminalEnvironment,
162 open: "openTerminal",
163 write: "writeTerminal",
164 close: "closeTerminal",
165 } as never,
166 };
167 });
168 vi.mock(import("../../state/terminalSessions"), async (original) => {
169 const { useAtomValue } = await import("@effect/atom-react");
170 return {
171 ...(await original()),
172 useThreadRunningTerminalIds: (() =>
173 useAtomValue(state.runningTerminalIds as Atom.Atom<ReadonlyArray<string>>)) as never,
174 };
175 });
176 vi.mock(import("../ThreadTerminalDrawer"), async (original) => ({
177 ...(await original()),
178 TerminalViewport: () => <div />,
179 }));
180 vi.mock(import("../../state/use-atom-command"), async (original) => ({
181 ...(await original()),
182 useAtomCommand: ((
183 command:
184 | "createProject"
185 | "importThreads"
186 | "refreshProviders"
187 | "openTerminal"
188 | "writeTerminal"
189 | "closeTerminal",
190 ) => state[command]) as never,
191 }));
192
193 import { welcomeImportSelectionKey } from "../../onboarding/welcomeState";
194 import { appAtomRegistry } from "../../rpc/atomRegistry";
195 import { toastManager } from "../ui/toast";
196 import { WelcomePage } from "./WelcomePage";
197
198 const primaryId = EnvironmentId.make("primary");
199 const readyClaude: ServerProvider = {
200 instanceId: ProviderInstanceId.make("claudeAgent"),
201 driver: ProviderDriverKind.make("claudeAgent"),
202 enabled: true,
203 installed: true,
204 version: "1.0.0",
205 status: "ready",
206 auth: { status: "authenticated" },
207 checkedAt: "2026-01-01T00:00:00.000Z",
208 models: [],
209 slashCommands: [],
210 skills: [],
211 };
212 const permissionMessage = "This connection cannot import projects or thread history.";
213
214 function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
215 return {
216 authenticated: true,
217 scopes: [AuthOrchestrationReadScope, ...scopes],
218 auth: {
219 policy: "remote-reachable",
220 bootstrapMethods: ["one-time-token"],
221 sessionMethods: ["bearer-access-token"],
222 sessionCookieName: "t3_session",
223 },
224 };
225 }
226
227 function sessionAtom(environmentId: EnvironmentId) {
228 return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
229 }
230
231 function projectsAtom() {
232 return state.projects as Atom.Writable<ReadonlyArray<Project>>;
233 }
234
235 function candidatesAtom() {
236 return state.candidates as Atom.Writable<ReadonlyArray<AgentSessionProjectCandidate>>;
237 }
238
239 function setGrant(environmentId: EnvironmentId, allowed: boolean) {
240 appAtomRegistry.set(
241 sessionAtom(environmentId),
242 AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
243 );
244 }
245
246 // Default selection only picks recently active projects, so pin "now".
247 const NOW = Date.parse("2026-01-01T00:00:00.000Z");
248
249 function candidate(
250 path: string,
251 overrides: Partial<AgentSessionProjectCandidate> = {},
252 ): AgentSessionProjectCandidate {
253 return {
254 path,
255 title: path.split("/").at(-1)!,
256 sources: ["codex"],
257 threadCount: 10,
258 lastActiveAt: new Date(NOW - 60_000).toISOString(),
259 alreadyImported: false,
260 ...overrides,
261 };
262 }
263
264 function recordProject({ environmentId, input }: CreateProjectInput) {
265 appAtomRegistry.set(projectsAtom(), [
266 ...appAtomRegistry.get(projectsAtom()),
267 { id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
268 ]);
269 return AsyncResult.success(undefined);
270 }
271
272 // Resolves once the project reaches the mocked projects atom; the real helper's timeout is
273 // replaced per test with a rejection.
274 function waitForRecordedProject(ref: { environmentId: EnvironmentId; projectId: string }) {
275 const find = () =>
276 appAtomRegistry
277 .get(projectsAtom())
278 .find(
279 (project) => project.id === ref.projectId && project.environmentId === ref.environmentId,
280 );
281 return new Promise<Project>((resolve) => {
282 const current = find();
283 if (current) return resolve(current);
284 const unsubscribe = appAtomRegistry.subscribe(projectsAtom(), () => {
285 const project = find();
286 if (!project) return;
287 unsubscribe();
288 resolve(project);
289 });
290 });
291 }
292
293 function deferred<T>() {
294 let resolve!: (value: T) => void;
295 const promise = new Promise<T>((complete) => {
296 resolve = complete;
297 });
298 return { promise, resolve };
299 }
300
301 function pageText() {
302 return document.body.textContent ?? "";
303 }
304
305 function button(label: string) {
306 const found = [...document.querySelectorAll("button")].find(
307 (element) => element.textContent?.trim() === label,
308 );
309 if (!found) throw new Error(`Missing button: ${label}`);
310 return found;
311 }
312
313 async function click(label: string) {
314 const target = button(label);
315 expect(target.disabled).toBe(false);
316 await act(async () => target.click());
317 }
318
319 async function mountWelcome() {
320 return render(
321 <RegistryContext.Provider value={appAtomRegistry}>
322 <WelcomePage environmentId={primaryId} onDone={state.onDone} />
323 </RegistryContext.Provider>,
324 );
325 }
326
327 // The mocked modules read `state`, so every test starts by replacing all of it.
328 // Returns the clock spy so each test can `using` it; the spy would otherwise outlive the test.
329 function setup() {
330 const now = vi.spyOn(Date, "now").mockReturnValue(NOW);
331 state.sessions.clear();
332 for (const id of [primaryId]) {
333 state.sessions.set(
334 id,
335 Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
336 Atom.keepAlive,
337 ),
338 );
339 }
340 state.projects = Atom.make<ReadonlyArray<Project>>([]).pipe(Atom.keepAlive);
341 state.providers = Atom.make<ReadonlyArray<ServerProvider>>([readyClaude]).pipe(Atom.keepAlive);
342 state.config = Atom.make(null).pipe(Atom.keepAlive);
343 state.candidates = Atom.make<ReadonlyArray<AgentSessionProjectCandidate>>([
344 candidate("/projects/first"),
345 candidate("/projects/second"),
346 ]).pipe(Atom.keepAlive);
347 state.createProject
348 .mockReset()
349 .mockImplementation(async (input: CreateProjectInput) => recordProject(input));
350 state.importThreads
351 .mockReset()
352 .mockResolvedValue(AsyncResult.success({ importedCount: 1, skippedCount: 0 }));
353 state.refreshProviders.mockReset().mockResolvedValue(AsyncResult.success(undefined));
354 state.completeOnboarding.mockReset().mockResolvedValue(undefined);
355 state.onDone.mockReset();
356 state.scan.mockReset();
357 state.refreshScan.mockReset();
358 state.waitForProject.mockReset().mockImplementation(waitForRecordedProject);
359 state.cloud = false;
360 state.auth = { isLoaded: true, isSignedIn: false, userId: null };
361 state.linkState = Atom.make<EnvironmentCloudLinkStateResult | null>(null).pipe(Atom.keepAlive);
362 state.linkError = null;
363 state.refreshLinkState.mockReset();
364 state.scanError = null;
365 state.scanPending = false;
366 state.runningTerminalIds = Atom.make<ReadonlyArray<string>>([]).pipe(Atom.keepAlive);
367 for (const command of [state.openTerminal, state.writeTerminal, state.closeTerminal]) {
368 command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
369 }
370 localStorage.removeItem(welcomeImportSelectionKey(primaryId));
371 return now;
372 }
373
374 it("rechecks after project creation and can retry its history without recreating the project", async () => {
375 using _now = setup();
376 const creation = deferred<void>();
377 state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
378 await creation.promise;
379 return recordProject(input);
380 });
381 await using _screen = await mountWelcome();
382 await click("Import 2 projects and start");
383 expect(state.createProject).toHaveBeenCalledOnce();
384 await act(async () => {
385 setGrant(primaryId, false);
386 creation.resolve();
387 await creation.promise;
388 });
389 expect(state.importThreads).not.toHaveBeenCalled();
390 expect(state.createProject).toHaveBeenCalledOnce();
391 expect(state.onDone).not.toHaveBeenCalled();
392 await vi.waitFor(() => expect(pageText()).toContain(permissionMessage));
393
394 await act(async () => setGrant(primaryId, true));
395 // The first project now exists, so only the second counts as new.
396 await click("Import 1 project and start");
397 expect(state.createProject).toHaveBeenCalledTimes(2);
398 expect(state.importThreads).toHaveBeenCalledTimes(2);
399 expect(state.onDone).toHaveBeenCalledOnce();
400 });
401
402 it("completes accepted imports when permission is revoked after the final server write", async () => {
403 using _now = setup();
404 appAtomRegistry.set(candidatesAtom(), [candidate("/projects/first")]);
405 const imported = deferred<{ importedCount: number; skippedCount: number }>();
406 state.importThreads.mockImplementationOnce(async () =>
407 AsyncResult.success(await imported.promise),
408 );
409 await using _screen = await mountWelcome();
410 await click("Import 1 project and start");
411 await act(async () => {
412 setGrant(primaryId, false);
413 imported.resolve({ importedCount: 1, skippedCount: 0 });
414 await imported.promise;
415 });
416 expect(state.createProject).toHaveBeenCalledOnce();
417 expect(state.importThreads).toHaveBeenCalledOnce();
418 expect(state.completeOnboarding).toHaveBeenCalledOnce();
419 expect(state.onDone).toHaveBeenCalledOnce();
420 });
421
422 it("finishes setup without landing when the imported project never reaches the client", async () => {
423 using _now = setup();
424 appAtomRegistry.set(candidatesAtom(), [candidate("/projects/first")]);
425 // The server accepts the project, but it never shows up in the client's projects.
426 state.createProject.mockResolvedValue(AsyncResult.success(undefined));
427 state.waitForProject.mockRejectedValue(new Error("The project did not appear."));
428 state.completeOnboarding.mockRejectedValueOnce(new Error("offline"));
429 await using _screen = await mountWelcome();
430 using toastAdd = vi.spyOn(toastManager, "add");
431
432 await click("Import 1 project and start");
433 await vi.waitFor(() => expect(state.completeOnboarding).toHaveBeenCalledOnce());
434 // A failed completion hands the step back instead of leaving it importing.
435 await vi.waitFor(() => expect(button("Import 1 project and start").disabled).toBe(false));
436 expect(state.onDone).not.toHaveBeenCalled();
437
438 await click("Import 1 project and start");
439 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
440 expect(state.onDone).toHaveBeenCalledWith(undefined);
441 // The retry skips the project it already imported, but still counts its thread.
442 await vi.waitFor(() =>
443 expect(toastAdd).toHaveBeenCalledWith(
444 expect.objectContaining({ type: "success", title: "Imported 1 thread" }),
445 ),
446 );
447 });
448
449 it("waits for a ready agent to start, and Start without an agent still finishes setup", async () => {
450 using _now = setup();
451 appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, []);
452 await using _screen = await mountWelcome();
453 expect(button("Import 2 projects and start").disabled).toBe(true);
454
455 await click("Start without an agent");
456 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
457 expect(state.createProject).toHaveBeenCalledTimes(2);
458 });
459
460 it("blocks leaving the page until the imported projects have landed", async () => {
461 using _now = setup();
462 const creation = deferred<void>();
463 state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
464 await creation.promise;
465 return recordProject(input);
466 });
467 const landing = deferred<void>();
468 state.waitForProject.mockImplementation(
469 async (ref: { environmentId: EnvironmentId; projectId: string }) => {
470 await landing.promise;
471 return waitForRecordedProject(ref);
472 },
473 );
474 await using screen = await mountWelcome();
475 await click("Import 2 projects and start");
476
477 // A blocked navigation never settles, so it is not awaited.
478 const leave = () =>
479 act(async () => {
480 void screen.router?.navigate({ to: "/settings" });
481 });
482 await leave();
483 await act(async () => {
484 creation.resolve();
485 await creation.promise;
486 });
487 await vi.waitFor(() => expect(state.waitForProject).toHaveBeenCalledOnce());
488 await leave();
489 expect(screen.router?.state.location.pathname).toBe("/");
490
491 const saved = deferred<void>();
492 state.completeOnboarding.mockImplementationOnce(() => saved.promise);
493 await act(async () => {
494 landing.resolve();
495 await landing.promise;
496 });
497 await vi.waitFor(() => expect(state.completeOnboarding).toHaveBeenCalledOnce());
498 await leave();
499 expect(screen.router?.state.location.pathname).toBe("/");
500
501 await act(async () => {
502 saved.resolve();
503 await saved.promise;
504 });
505 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
506 expect(screen.router?.state.location.pathname).toBe("/");
507 expect(state.createProject).toHaveBeenCalledTimes(2);
508 });
509
510 it("gives projects a later scan finds the default, unless the main box was unchecked", async () => {
511 using _now = setup();
512 await using _screen = await mountWelcome();
513 // Turning on another agent rescans and finds a recent project the user has not seen.
514 const findProject = (path: string) =>
515 act(async () =>
516 appAtomRegistry.set(candidatesAtom(), [
517 ...appAtomRegistry.get(candidatesAtom()),
518 candidate(path),
519 ]),
520 );
521
522 await click("Review all 2");
523 await click("Select none");
524 await findProject("/projects/third");
525 await vi.waitFor(() => expect(button("Import 1 project and start").disabled).toBe(false));
526
527 const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
528 await act(async () => importProjects?.click());
529 await findProject("/projects/fourth");
530 await vi.waitFor(() => expect(button("Start").disabled).toBe(false));
531 });
532
533 it("keeps the project choice across a visit to Settings until setup finishes", async () => {
534 using _now = setup();
535 {
536 await using _first = await mountWelcome();
537 const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
538 await act(async () => importProjects?.click());
539 await vi.waitFor(() => expect(button("Start").disabled).toBe(false));
540 }
541 // Coming back from Settings mounts the page again.
542 {
543 await using _second = await mountWelcome();
544 expect(button("Start").disabled).toBe(false);
545 await click("Start");
546 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
547 expect(state.createProject).not.toHaveBeenCalled();
548 }
549 await using _third = await mountWelcome();
550 expect(button("Import 2 projects and start").disabled).toBe(false);
551 });
552
553 it("stays busy while setup saves after an import with nothing to open", async () => {
554 using _now = setup();
555 appAtomRegistry.set(candidatesAtom(), [candidate("/projects/first")]);
556 state.importThreads.mockResolvedValue(AsyncResult.success({ importedCount: 0, skippedCount: 1 }));
557 const saved = deferred<void>();
558 state.completeOnboarding.mockImplementationOnce(() => saved.promise);
559 await using _screen = await mountWelcome();
560
561 await click("Import 1 project and start");
562 await vi.waitFor(() => expect(state.completeOnboarding).toHaveBeenCalledOnce());
563 expect(button("Importing…").disabled).toBe(true);
564 await act(async () => {
565 saved.resolve();
566 await saved.promise;
567 });
568 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
569 expect(state.createProject).toHaveBeenCalledOnce();
570 });
571
572 it("leaves projects already in T3 Code out of the default import, unless the box is checked", async () => {
573 using _now = setup();
574 const existing = ProjectId.make("existing");
575 const justAdded = ProjectId.make("just-added");
576 appAtomRegistry.set(projectsAtom(), [
577 { id: existing, environmentId: primaryId, workspaceRoot: "/projects/first" },
578 // Added a moment ago, so the cached scan does not know it exists yet.
579 { id: justAdded, environmentId: primaryId, workspaceRoot: "/projects/second" },
580 ]);
581 appAtomRegistry.set(candidatesAtom(), [
582 candidate("/projects/first", { alreadyImported: true, projectId: existing }),
583 candidate("/projects/second"),
584 candidate("/projects/third"),
585 ]);
586 {
587 await using _screen = await mountWelcome();
588 await vi.waitFor(() => expect(pageText()).toContain("Import 1 project and their threads"));
589 }
590
591 // With every project already in T3 Code, checking the box still picks them.
592 appAtomRegistry.set(candidatesAtom(), appAtomRegistry.get(candidatesAtom()).slice(0, 2));
593 await using _screen = await mountWelcome();
594 const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
595 await act(async () => importProjects?.click());
596 await vi.waitFor(() => expect(pageText()).toContain("Import 2 projects and their threads"));
597 expect(button("Import threads and start").disabled).toBe(false);
598 });
599
600 it("keeps the started projects checked when the page opens again after a quit", async () => {
601 using _now = setup();
602 const imported = deferred<{ importedCount: number; skippedCount: number }>();
603 state.importThreads.mockImplementationOnce(async () =>
604 AsyncResult.success(await imported.promise),
605 );
606 {
607 await using _first = await mountWelcome();
608 await click("Import 2 projects and start");
609 await vi.waitFor(() => expect(state.importThreads).toHaveBeenCalledOnce());
610 }
611 // The app quit during the first project's history; it now exists in T3 Code.
612 const [first] = appAtomRegistry.get(projectsAtom());
613 appAtomRegistry.set(candidatesAtom(), [
614 candidate("/projects/first", { alreadyImported: true, projectId: first!.id }),
615 candidate("/projects/second"),
616 ]);
617 await using _second = await mountWelcome();
618 await vi.waitFor(() => expect(pageText()).toContain("Import 2 projects and their threads"));
619 });
620
621 it("keeps the project controls when a later scan fails", async () => {
622 using _now = setup();
623 await using _screen = await mountWelcome();
624 state.scanError = "The scan timed out.";
625 await act(async () =>
626 appAtomRegistry.set(candidatesAtom(), [...appAtomRegistry.get(candidatesAtom())]),
627 );
628 await vi.waitFor(() => expect(pageText()).toContain("Could not check projects again."));
629 expect(button("Import 2 projects and start").disabled).toBe(false);
630 expect(button("Retry").disabled).toBe(false);
631 });
632
633 it("keeps saved picks when Start comes before the project list loads", async () => {
634 using _now = setup();
635 const saved = JSON.stringify({ knownKeys: ["a"], keys: ["a"], optedOut: false });
636 localStorage.setItem(welcomeImportSelectionKey(primaryId), saved);
637 state.scanPending = true;
638 await using _screen = await mountWelcome();
639
640 await click("Start");
641 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
642 // An import a quit cut short is still checked on the next visit.
643 expect(localStorage.getItem(welcomeImportSelectionKey(primaryId))).toBe(saved);
644 });
645
646 it("offers Update for a signed-in agent whose version is broken, and keeps Start off", async () => {
647 using _now = setup();
648 appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
649 {
650 ...readyClaude,
651 compatibilityAdvisory: {
652 status: "broken",
653 message: "Update Claude Code to 2.0 or later.",
654 recommendedVersion: "2.0.0",
655 recommendedRange: null,
656 },
657 },
658 ]);
659 await using _screen = await mountWelcome();
660 await vi.waitFor(() => expect(pageText()).toContain("Update Claude Code to 2.0 or later."));
661 const update = [...document.querySelectorAll("a")].find(
662 (element) => element.textContent?.trim() === "Update",
663 );
664 expect(update?.getAttribute("href")).toContain("/settings/providers");
665 expect(button("Import 2 projects and start").disabled).toBe(true);
666 });
667
668 it("checks an agent again once its install command finishes in the setup terminal", async () => {
669 using _now = setup();
670 appAtomRegistry.set(
671 sessionAtom(primaryId),
672 AsyncResult.success(session([AuthOrchestrationOperateScope, AuthTerminalOperateScope])),
673 );
674 appAtomRegistry.set(state.config as Atom.Writable<unknown>, {
675 cwd: "/Users/dev",
676 environment: { platform: { os: "darwin" } },
677 keybindings: [],
678 settings: { providerInstances: {}, projectSettingsOverrides: {} },
679 });
680 appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
681 { ...readyClaude, installed: false, status: "error", auth: { status: "unknown" } },
682 ]);
683 await using _screen = await mountWelcome();
684 await vi.waitFor(() => button("Install"));
685 await click("Install");
686 await vi.waitFor(() => expect(state.writeTerminal).toHaveBeenCalledOnce());
687 const { terminalId } = state.openTerminal.mock.calls[0]![0].input;
688 const runningTerminalIds = state.runningTerminalIds as Atom.Writable<ReadonlyArray<string>>;
689 const recheck = { environmentId: primaryId, input: { instanceId: readyClaude.instanceId } };
690
691 await act(async () => appAtomRegistry.set(runningTerminalIds, [terminalId]));
692 expect(state.refreshProviders).not.toHaveBeenCalledWith(recheck);
693 // The shell stays open at its prompt after the install, so only the command exits.
694 await act(async () => appAtomRegistry.set(runningTerminalIds, []));
695 expect(state.refreshProviders).toHaveBeenCalledWith(recheck);
696 expect(state.closeTerminal).not.toHaveBeenCalled();
697 });
698
699 it("keeps an import opt-out on the page when storage cannot save it", async () => {
700 using _now = setup();
701 await using _screen = await mountWelcome();
702 using _full = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
703 throw new DOMException("The quota has been exceeded.", "QuotaExceededError");
704 });
705 const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
706 await act(async () => importProjects?.click());
707
708 await click("Start");
709 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
710 expect(state.createProject).not.toHaveBeenCalled();
711 });
712
713 it("opens the list of agents to add once the checks find none, even after a wrong first status", async () => {
714 using _now = setup();
715 const pi = {
716 ...readyClaude,
717 instanceId: ProviderInstanceId.make("pi"),
718 driver: ProviderDriverKind.make("pi"),
719 };
720 // Pi's first status says installed before its check runs.
721 appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
722 { ...pi, status: "warning", auth: { status: "unknown" } },
723 ]);
724 await using _screen = await mountWelcome();
725 await act(async () =>
726 appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
727 { ...pi, installed: false, status: "error", auth: { status: "unknown" } },
728 ]),
729 );
730 const fold = () =>
731 [...document.querySelectorAll("button")].find((element) =>
732 element.textContent?.startsWith("Set up an agent"),
733 );
734 await vi.waitFor(() => expect(fold()?.getAttribute("aria-expanded")).toBe("true"));
735
736 // Turning an agent on starts a new check; the open list stays where the user is working.
737 await act(async () =>
738 appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
739 { ...pi, installed: false, status: "warning", auth: { status: "unknown" } },
740 ]),
741 );
742 expect(fold()?.getAttribute("aria-expanded")).toBe("true");
743 });
744
745 it("starts without importing when this connection cannot import projects", async () => {
746 using _now = setup();
747 setGrant(primaryId, false);
748 await using _screen = await mountWelcome();
749 expect(pageText()).not.toContain("Review all");
750
751 await click("Start");
752 await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
753 expect(state.createProject).not.toHaveBeenCalled();
754 });
755
756 it("says the phone is set up only once this computer is shared with the signed-in account", async () => {
757 using _now = setup();
758 state.cloud = true;
759 state.auth = { isLoaded: true, isSignedIn: true, userId: "user_1" };
760 appAtomRegistry.set(
761 sessionAtom(primaryId),
762 AsyncResult.success(
763 session([AuthOrchestrationOperateScope, AuthRelayReadScope, AuthRelayWriteScope]),
764 ),
765 );
766 state.linkError = "Could not read T3 Connect link state.";
767 await using _screen = await mountWelcome();
768 await click("Set up");
769 // A failed read says so instead of asking to share the computer again.
770 await vi.waitFor(() => expect(pageText()).toContain("Could not check T3 Connect."));
771 expect(pageText()).not.toContain("Set up T3 Connect");
772
773 state.linkError = null;
774 await act(async () =>
775 appAtomRegistry.set(state.linkState as Atom.Writable<EnvironmentCloudLinkStateResult | null>, {
776 linked: false,
777 cloudUserId: null,
778 relayUrl: null,
779 relayIssuer: null,
780 publishAgentActivity: false,
781 }),
782 );
783 // Signed in, but "Not now" on the share step left this computer unreachable.
784 await vi.waitFor(() => expect(pageText()).toContain("Set up T3 Connect"));
785
786 const share = (reachability: EnvironmentCloudLinkStateResult["reachability"]) =>
787 act(async () =>
788 appAtomRegistry.set(
789 state.linkState as Atom.Writable<EnvironmentCloudLinkStateResult | null>,
790 {
791 linked: true,
792 cloudUserId: "user_1",
793 relayUrl: null,
794 relayIssuer: null,
795 managedTunnelActive: true,
796 publishAgentActivity: true,
797 reachability,
798 },
799 ),
800 );
801 const checkedAt = "2026-01-01T00:00:00.000Z";
802 await share({
803 status: "unreachable",
804 checkedAt,
805 cause: "connector_not_running",
806 reason: "The tunnel is not running.",
807 hint: null,
808 fix: "Turn T3 Connect off and on.",
809 });
810 await vi.waitFor(() => expect(pageText()).toContain("Check T3 Connect"));
811 expect(pageText()).not.toContain("Your phone can reach this computer.");
812
813 await share({ status: "reachable", checkedAt, readyConnections: 4, protocol: "quic" });
814 await vi.waitFor(() => expect(pageText()).toContain("Your phone can reach this computer."));
815 expect(pageText()).not.toContain("Check T3 Connect");
816 });