@devries-cameron20 / t3code Mirror · read-only / commits / 4f0b74e190
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 02:00 UTC

feat(web): first run is one Welcome page instead of a 3-step wizard (#33209)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Nov 9, 2026 at 04:23 UTC 4f0b74e190261c8233ae52af17b0fd1734e99e50
29 files changed +3493 -2648
apps/marketing/vercel.ts
+18
@@ -32,5 +32,23 @@ export const config: VercelConfig = {
32 destination: "https://app.t3.codes",
33 permanent: true,
34 },
35 + // One QR code in the desktop app serves both stores. iPadOS reports a Mac, so it gets /download.
36 + {
37 + source: "/mobile",
38 + has: [{ type: "header", key: "user-agent", value: ".*(iPhone|iPad|iPod).*" }],
39 + destination: "https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824",
40 + permanent: false,
41 + },
42 + {
43 + source: "/mobile",
44 + has: [{ type: "header", key: "user-agent", value: ".*Android.*" }],
45 + destination: "https://play.google.com/store/apps/details?id=com.t3tools.t3code",
46 + permanent: false,
47 + },
48 + {
49 + source: "/mobile",
50 + destination: "/download",
51 + permanent: false,
52 + },
53 ],
54 };
apps/web/src/branding.ts
+2
@@ -26,3 +26,5 @@ export const APP_DISPLAY_NAME =
26 formatAppDisplayName({ baseName: APP_BASE_NAME, stageLabel: APP_STAGE_LABEL });
27 export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";
28 export const DESKTOP_DOWNLOAD_URL = "https://t3.codes/download";
29 +// Redirects to the App Store or Google Play to match the phone that opens it.
30 +export const MOBILE_APP_URL = "https://t3.codes/mobile";
apps/web/src/components/AppSidebarLayout.tsx
+57 -43
@@ -312,7 +312,7 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): ()
312 };
313 }
314
315 -function SidebarControl() {
315 +function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) {
316 const router = useRouter();
317 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
318 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
@@ -326,6 +326,8 @@ function SidebarControl() {
326
327 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener that toggles the sidebar on its shortcut
328 useEffect(() => {
329 + // A hidden sidebar would still save the toggle, so the shortcut does nothing without one.
330 + if (!showSidebar) return;
331 const onKeyDown = (event: KeyboardEvent) => {
332 if (event.defaultPrevented) return;
333 if (
@@ -362,7 +364,7 @@ function SidebarControl() {
364 window.removeEventListener("keydown", onKeyDown, true);
365 unsubscribe?.();
366 };
365 - }, [keybindings, toggleSidebar, usagePageOpen]);
367 + }, [keybindings, showSidebar, toggleSidebar, usagePageOpen]);
368
369 // The control lives as long as the shell, so it carries the shell's commands. Created
370 // once so re-renders never re-register them.
@@ -380,28 +382,36 @@ function SidebarControl() {
382 )}
383 data-sidebar-control=""
384 >
383 - <Tooltip>
384 - <TooltipTrigger
385 - render={
386 - <SidebarTrigger
387 - variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
388 - className={cn(
389 - "pointer-events-auto",
390 - isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
391 - )}
392 - aria-label="Toggle main sidebar"
393 - />
394 - }
395 - />
396 - <TooltipPopup side="bottom">
397 - Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
398 - </TooltipPopup>
399 - </Tooltip>
385 + {showSidebar ? (
386 + <Tooltip>
387 + <TooltipTrigger
388 + render={
389 + <SidebarTrigger
390 + variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
391 + className={cn(
392 + "pointer-events-auto",
393 + isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
394 + )}
395 + aria-label="Toggle main sidebar"
396 + />
397 + }
398 + />
399 + <TooltipPopup side="bottom">
400 + Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
401 + </TooltipPopup>
402 + </Tooltip>
403 + ) : null}
404 </div>
405 );
406 }
407
404 -export function AppSidebarLayout({ children }: { children: ReactNode }) {
408 +export function AppSidebarLayout({
409 + children,
410 + showSidebar = true,
411 +}: {
412 + children: ReactNode;
413 + showSidebar?: boolean;
414 +}) {
415 const sidebarArea = workspaceAreaProps("sidebar", 0, "Threads");
416 const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
417 observedKey: null,
@@ -450,31 +460,35 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
460 storageKey="chat_thread_sidebar_open"
461 style={sidebarProviderStyle}
462 >
453 - <SidebarBrandWidthProbe isElectron={isElectron} onWidthChange={setBrandWidth} />
454 - <Sidebar
455 - side="left"
456 - collapsible="offcanvas"
457 - data-app-sidebar=""
458 - {...sidebarArea}
459 - role="navigation"
460 - aria-label="Threads"
461 - resizable={{
462 - maxWidth: sidebarMaximumWidth,
463 - minWidth: sidebarMinimumWidth,
464 - shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
465 - nextWidth <= currentWidth ||
466 - wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
467 - storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
468 - onResize: setSidebarWidth,
469 - }}
470 - style={windowControlsInsetStyle}
471 - >
472 - <ThreadSidebar routeReveal={sidebarRouteReveal} />
473 - <SidebarRail onDoubleClick={resetSidebarWidth} />
474 - </Sidebar>
463 + {showSidebar ? (
464 + <>
465 + <SidebarBrandWidthProbe isElectron={isElectron} onWidthChange={setBrandWidth} />
466 + <Sidebar
467 + side="left"
468 + collapsible="offcanvas"
469 + data-app-sidebar=""
470 + {...sidebarArea}
471 + role="navigation"
472 + aria-label="Threads"
473 + resizable={{
474 + maxWidth: sidebarMaximumWidth,
475 + minWidth: sidebarMinimumWidth,
476 + shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
477 + nextWidth <= currentWidth ||
478 + wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
479 + storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
480 + onResize: setSidebarWidth,
481 + }}
482 + style={windowControlsInsetStyle}
483 + >
484 + <ThreadSidebar routeReveal={sidebarRouteReveal} />
485 + <SidebarRail onDoubleClick={resetSidebarWidth} />
486 + </Sidebar>
487 + </>
488 + ) : null}
489 {children}
490 <BackgroundThreadAnnouncer />
477 - <SidebarControl />
491 + <SidebarControl showSidebar={showSidebar} />
492 {isElectron ? <HistorySwipeNavigation /> : null}
493 </SidebarProvider>
494 </PanelAnimationSuppressionProvider>
apps/web/src/components/onboarding/WelcomePage.import.browser.test.tsx new
+741
@@ -0,0 +1,741 @@
1 +import { RegistryContext } from "@effect/atom-react";
2 +import {
3 + AuthOrchestrationOperateScope,
4 + AuthOrchestrationReadScope,
5 + AuthRelayReadScope,
6 + AuthRelayWriteScope,
7 + EnvironmentId,
8 + ProjectId,
9 + ProviderDriverKind,
10 + ProviderInstanceId,
11 + type AgentSessionProjectCandidate,
12 + type AuthEnvironmentScope,
13 + type AuthSessionState,
14 + type EnvironmentCloudLinkStateResult,
15 + type ServerProvider,
16 +} from "@t3tools/contracts";
17 +import { AsyncResult, Atom } from "effect/reactivity";
18 +import { expect, it, vi } from "vite-plus/test";
19 +
20 +import "~/index.css";
21 +import { act, render } from "../../../test/render";
22 +
23 +type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
24 +type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
25 +type CreateProjectInput = {
26 + environmentId: EnvironmentId;
27 + input: { projectId: ProjectId; workspaceRoot: string };
28 +};
29 +const state = vi.hoisted(() => ({
30 + sessions: new Map<string, unknown>(),
31 + projects: null as unknown,
32 + providers: null as unknown,
33 + config: null as unknown,
34 + candidates: null as unknown,
35 + createProject: vi.fn(),
36 + importThreads: vi.fn(),
37 + refreshProviders: vi.fn(),
38 + completeOnboarding: vi.fn(),
39 + onDone: vi.fn(),
40 + scan: vi.fn(),
41 + refreshScan: vi.fn(),
42 + waitForProject: vi.fn(),
43 + cloud: false,
44 + auth: { isLoaded: true, isSignedIn: false, userId: null as string | null },
45 + linkState: null as unknown,
46 + linkError: null as string | null,
47 + refreshLinkState: vi.fn(),
48 + scanError: null as string | null,
49 + scanPending: false,
50 +}));
51 +
52 +vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
53 + const actual = await original();
54 + return {
55 + ...actual,
56 + createEnvironmentSessionAtoms: ((runtime: never) => ({
57 + ...actual.createEnvironmentSessionAtoms(runtime),
58 + sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id),
59 + })) as never,
60 + };
61 +});
62 +vi.mock(import("../../cloud/publicConfig"), async (original) => ({
63 + ...(await original()),
64 + hasCloudPublicConfig: () => state.cloud,
65 +}));
66 +vi.mock(import("@clerk/react"), async (original) => ({
67 + ...(await original()),
68 + useAuth: (() => state.auth) as never,
69 +}));
70 +vi.mock(import("../clerk/useT3ConnectAuthPrompt"), async (original) => ({
71 + ...(await original()),
72 + useT3ConnectAuthPrompt: (() => ({ openAuthPrompt: () => {} })) as never,
73 +}));
74 +vi.mock(import("../../cloud/cloudLinkState"), async (original) => {
75 + const { useAtomValue } = await import("@effect/atom-react");
76 + return {
77 + ...(await original()),
78 + useCloudLinkState: (() => ({
79 + data: useAtomValue(state.linkState as Atom.Atom<EnvironmentCloudLinkStateResult | null>),
80 + error: state.linkError,
81 + isPending: false,
82 + refresh: state.refreshLinkState,
83 + })) as never,
84 + };
85 +});
86 +vi.mock(import("../../onboarding/firstRun"), async (original) => ({
87 + ...(await original()),
88 + completeOnboarding: state.completeOnboarding,
89 +}));
90 +vi.mock(import("../../state/environments"), async (original) => ({
91 + ...(await original()),
92 + useEnvironments: (() => ({
93 + environments: [{ environmentId: "primary", label: "primary" }],
94 + })) as never,
95 + usePrimaryEnvironmentId: (() => "primary") as never,
96 +}));
97 +vi.mock(import("../../state/server"), async (original) => {
98 + const actual = await original();
99 + return {
100 + ...actual,
101 + serverEnvironment: {
102 + ...actual.serverEnvironment,
103 + providersValueAtom: (() => state.providers) as never,
104 + configValueAtom: (() => state.config) as never,
105 + refreshProviders: "refreshProviders" as never,
106 + },
107 + };
108 +});
109 +vi.mock(import("../../state/entities"), async (original) => {
110 + const { useAtomValue } = await import("@effect/atom-react");
111 + return {
112 + ...(await original()),
113 + useProjects: (() => useAtomValue(state.projects as Atom.Atom<Project[]>)) as never,
114 + readProjects: (() => appAtomRegistry.get(state.projects as Atom.Atom<Project[]>)) as never,
115 + waitForProject: ((ref: unknown) => state.waitForProject(ref)) as never,
116 + };
117 +});
118 +vi.mock(import("../../state/projects"), async (original) => ({
119 + ...(await original()),
120 + projectEnvironment: { create: "createProject" } as never,
121 +}));
122 +vi.mock(import("../../state/agentSessions"), async (original) => ({
123 + ...(await original()),
124 + agentSessionImport: "importThreads" as never,
125 +}));
126 +vi.mock(import("../../onboarding/useProjectScans"), async (original) => {
127 + const { useAtomValue } = await import("@effect/atom-react");
128 + return {
129 + ...(await original()),
130 + useProjectScans: (ids: readonly EnvironmentId[]) => {
131 + const candidates = useAtomValue(
132 + state.candidates as Atom.Atom<AgentSessionProjectCandidate[]>,
133 + );
134 + return ids.map((environmentId) => {
135 + state.scan({ environmentId });
136 + return {
137 + environmentId,
138 + data: (state.scanPending ? null : { candidates, truncated: false }) as never,
139 + isPending: state.scanPending,
140 + error: state.scanError,
141 + refresh: state.refreshScan,
142 + };
143 + });
144 + },
145 + };
146 +});
147 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
148 + ...(await original()),
149 + useAtomCommand: ((command: "createProject" | "importThreads" | "refreshProviders") =>
150 + state[command]) as never,
151 +}));
152 +
153 +import { welcomeImportSelectionKey } from "../../onboarding/welcomeState";
154 +import { appAtomRegistry } from "../../rpc/atomRegistry";
155 +import { toastManager } from "../ui/toast";
156 +import { WelcomePage } from "./WelcomePage";
157 +
158 +const primaryId = EnvironmentId.make("primary");
159 +const readyClaude: ServerProvider = {
160 + instanceId: ProviderInstanceId.make("claudeAgent"),
161 + driver: ProviderDriverKind.make("claudeAgent"),
162 + enabled: true,
163 + installed: true,
164 + version: "1.0.0",
165 + status: "ready",
166 + auth: { status: "authenticated" },
167 + checkedAt: "2026-01-01T00:00:00.000Z",
168 + models: [],
169 + slashCommands: [],
170 + skills: [],
171 +};
172 +const permissionMessage = "This connection cannot import projects or thread history.";
173 +
174 +function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
175 + return {
176 + authenticated: true,
177 + scopes: [AuthOrchestrationReadScope, ...scopes],
178 + auth: {
179 + policy: "remote-reachable",
180 + bootstrapMethods: ["one-time-token"],
181 + sessionMethods: ["bearer-access-token"],
182 + sessionCookieName: "t3_session",
183 + },
184 + };
185 +}
186 +
187 +function sessionAtom(environmentId: EnvironmentId) {
188 + return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
189 +}
190 +
191 +function projectsAtom() {
192 + return state.projects as Atom.Writable<ReadonlyArray<Project>>;
193 +}
194 +
195 +function candidatesAtom() {
196 + return state.candidates as Atom.Writable<ReadonlyArray<AgentSessionProjectCandidate>>;
197 +}
198 +
199 +function setGrant(environmentId: EnvironmentId, allowed: boolean) {
200 + appAtomRegistry.set(
201 + sessionAtom(environmentId),
202 + AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
203 + );
204 +}
205 +
206 +// Default selection only picks recently active projects, so pin "now".
207 +const NOW = Date.parse("2026-01-01T00:00:00.000Z");
208 +
209 +function candidate(
210 + path: string,
211 + overrides: Partial<AgentSessionProjectCandidate> = {},
212 +): AgentSessionProjectCandidate {
213 + return {
214 + path,
215 + title: path.split("/").at(-1)!,
216 + sources: ["codex"],
217 + threadCount: 10,
218 + lastActiveAt: new Date(NOW - 60_000).toISOString(),
219 + alreadyImported: false,
220 + ...overrides,
221 + };
222 +}
223 +
224 +function recordProject({ environmentId, input }: CreateProjectInput) {
225 + appAtomRegistry.set(projectsAtom(), [
226 + ...appAtomRegistry.get(projectsAtom()),
227 + { id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
228 + ]);
229 + return AsyncResult.success(undefined);
230 +}
231 +
232 +// Resolves once the project reaches the mocked projects atom; the real helper's timeout is
233 +// replaced per test with a rejection.
234 +function waitForRecordedProject(ref: { environmentId: EnvironmentId; projectId: string }) {
235 + const find = () =>
236 + appAtomRegistry
237 + .get(projectsAtom())
238 + .find(
239 + (project) => project.id === ref.projectId && project.environmentId === ref.environmentId,
240 + );
241 + return new Promise<Project>((resolve) => {
242 + const current = find();
243 + if (current) return resolve(current);
244 + const unsubscribe = appAtomRegistry.subscribe(projectsAtom(), () => {
245 + const project = find();
246 + if (!project) return;
247 + unsubscribe();
248 + resolve(project);
249 + });
250 + });
251 +}
252 +
253 +function deferred<T>() {
254 + let resolve!: (value: T) => void;
255 + const promise = new Promise<T>((complete) => {
256 + resolve = complete;
257 + });
258 + return { promise, resolve };
259 +}
260 +
261 +function pageText() {
262 + return document.body.textContent ?? "";
263 +}
264 +
265 +function button(label: string) {
266 + const found = [...document.querySelectorAll("button")].find(
267 + (element) => element.textContent?.trim() === label,
268 + );
269 + if (!found) throw new Error(`Missing button: ${label}`);
270 + return found;
271 +}
272 +
273 +async function click(label: string) {
274 + const target = button(label);
275 + expect(target.disabled).toBe(false);
276 + await act(async () => target.click());
277 +}
278 +
279 +async function mountWelcome() {
280 + return render(
281 + <RegistryContext.Provider value={appAtomRegistry}>
282 + <WelcomePage environmentId={primaryId} onDone={state.onDone} />
283 + </RegistryContext.Provider>,
284 + );
285 +}
286 +
287 +// The mocked modules read `state`, so every test starts by replacing all of it.
288 +// Returns the clock spy so each test can `using` it; the spy would otherwise outlive the test.
289 +function setup() {
290 + const now = vi.spyOn(Date, "now").mockReturnValue(NOW);
291 + state.sessions.clear();
292 + for (const id of [primaryId]) {
293 + state.sessions.set(
294 + id,
295 + Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
296 + Atom.keepAlive,
297 + ),
298 + );
299 + }
300 + state.projects = Atom.make<ReadonlyArray<Project>>([]).pipe(Atom.keepAlive);
301 + state.providers = Atom.make<ReadonlyArray<ServerProvider>>([readyClaude]).pipe(Atom.keepAlive);
302 + state.config = Atom.make(null).pipe(Atom.keepAlive);
303 + state.candidates = Atom.make<ReadonlyArray<AgentSessionProjectCandidate>>([
304 + candidate("/projects/first"),
305 + candidate("/projects/second"),
306 + ]).pipe(Atom.keepAlive);
307 + state.createProject
308 + .mockReset()
309 + .mockImplementation(async (input: CreateProjectInput) => recordProject(input));
310 + state.importThreads
311 + .mockReset()
312 + .mockResolvedValue(AsyncResult.success({ importedCount: 1, skippedCount: 0 }));
313 + state.refreshProviders.mockReset().mockResolvedValue(AsyncResult.success(undefined));
314 + state.completeOnboarding.mockReset().mockResolvedValue(undefined);
315 + state.onDone.mockReset();
316 + state.scan.mockReset();
317 + state.refreshScan.mockReset();
318 + state.waitForProject.mockReset().mockImplementation(waitForRecordedProject);
319 + state.cloud = false;
320 + state.auth = { isLoaded: true, isSignedIn: false, userId: null };
321 + state.linkState = Atom.make<EnvironmentCloudLinkStateResult | null>(null).pipe(Atom.keepAlive);
322 + state.linkError = null;
323 + state.refreshLinkState.mockReset();
324 + state.scanError = null;
325 + state.scanPending = false;
326 + localStorage.removeItem(welcomeImportSelectionKey(primaryId));
327 + return now;
328 +}
329 +
330 +it("rechecks after project creation and can retry its history without recreating the project", async () => {
331 + using _now = setup();
332 + const creation = deferred<void>();
333 + state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
334 + await creation.promise;
335 + return recordProject(input);
336 + });
337 + await using _screen = await mountWelcome();
338 + await click("Import 2 projects and start");
339 + expect(state.createProject).toHaveBeenCalledOnce();
340 + await act(async () => {
341 + setGrant(primaryId, false);
342 + creation.resolve();
343 + await creation.promise;
344 + });
345 + expect(state.importThreads).not.toHaveBeenCalled();
346 + expect(state.createProject).toHaveBeenCalledOnce();
347 + expect(state.onDone).not.toHaveBeenCalled();
348 + await vi.waitFor(() => expect(pageText()).toContain(permissionMessage));
349 +
350 + await act(async () => setGrant(primaryId, true));
351 + // The first project now exists, so only the second counts as new.
352 + await click("Import 1 project and start");
353 + expect(state.createProject).toHaveBeenCalledTimes(2);
354 + expect(state.importThreads).toHaveBeenCalledTimes(2);
355 + expect(state.onDone).toHaveBeenCalledOnce();
356 +});
357 +
358 +it("completes accepted imports when permission is revoked after the final server write", async () => {
359 + using _now = setup();
360 + appAtomRegistry.set(candidatesAtom(), [candidate("/projects/first")]);
361 + const imported = deferred<{ importedCount: number; skippedCount: number }>();
362 + state.importThreads.mockImplementationOnce(async () =>
363 + AsyncResult.success(await imported.promise),
364 + );
365 + await using _screen = await mountWelcome();
366 + await click("Import 1 project and start");
367 + await act(async () => {
368 + setGrant(primaryId, false);
369 + imported.resolve({ importedCount: 1, skippedCount: 0 });
370 + await imported.promise;
371 + });
372 + expect(state.createProject).toHaveBeenCalledOnce();
373 + expect(state.importThreads).toHaveBeenCalledOnce();
374 + expect(state.completeOnboarding).toHaveBeenCalledOnce();
375 + expect(state.onDone).toHaveBeenCalledOnce();
376 +});
377 +
378 +it("finishes setup without landing when the imported project never reaches the client", async () => {
379 + using _now = setup();
380 + appAtomRegistry.set(candidatesAtom(), [candidate("/projects/first")]);
381 + // The server accepts the project, but it never shows up in the client's projects.
382 + state.createProject.mockResolvedValue(AsyncResult.success(undefined));
383 + state.waitForProject.mockRejectedValue(new Error("The project did not appear."));
384 + state.completeOnboarding.mockRejectedValueOnce(new Error("offline"));
385 + await using _screen = await mountWelcome();
386 + using toastAdd = vi.spyOn(toastManager, "add");
387 +
388 + await click("Import 1 project and start");
389 + await vi.waitFor(() => expect(state.completeOnboarding).toHaveBeenCalledOnce());
390 + // A failed completion hands the step back instead of leaving it importing.
391 + await vi.waitFor(() => expect(button("Import 1 project and start").disabled).toBe(false));
392 + expect(state.onDone).not.toHaveBeenCalled();
393 +
394 + await click("Import 1 project and start");
395 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
396 + expect(state.onDone).toHaveBeenCalledWith(undefined);
397 + // The retry skips the project it already imported, but still counts its thread.
398 + await vi.waitFor(() =>
399 + expect(toastAdd).toHaveBeenCalledWith(
400 + expect.objectContaining({ type: "success", title: "Imported 1 thread" }),
401 + ),
402 + );
403 +});
404 +
405 +it("waits for a ready agent to start, and Start without an agent still finishes setup", async () => {
406 + using _now = setup();
407 + appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, []);
408 + await using _screen = await mountWelcome();
409 + expect(button("Import 2 projects and start").disabled).toBe(true);
410 +
411 + await click("Start without an agent");
412 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
413 + expect(state.createProject).toHaveBeenCalledTimes(2);
414 +});
415 +
416 +it("blocks leaving the page until the imported projects have landed", async () => {
417 + using _now = setup();
418 + const creation = deferred<void>();
419 + state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
420 + await creation.promise;
421 + return recordProject(input);
422 + });
423 + const landing = deferred<void>();
424 + state.waitForProject.mockImplementation(
425 + async (ref: { environmentId: EnvironmentId; projectId: string }) => {
426 + await landing.promise;
427 + return waitForRecordedProject(ref);
428 + },
429 + );
430 + await using screen = await mountWelcome();
431 + await click("Import 2 projects and start");
432 +
433 + // A blocked navigation never settles, so it is not awaited.
434 + const leave = () =>
435 + act(async () => {
436 + void screen.router?.navigate({ to: "/settings" });
437 + });
438 + await leave();
439 + await act(async () => {
440 + creation.resolve();
441 + await creation.promise;
442 + });
443 + await vi.waitFor(() => expect(state.waitForProject).toHaveBeenCalledOnce());
444 + await leave();
445 + expect(screen.router?.state.location.pathname).toBe("/");
446 +
447 + const saved = deferred<void>();
448 + state.completeOnboarding.mockImplementationOnce(() => saved.promise);
449 + await act(async () => {
450 + landing.resolve();
451 + await landing.promise;
452 + });
453 + await vi.waitFor(() => expect(state.completeOnboarding).toHaveBeenCalledOnce());
454 + await leave();
455 + expect(screen.router?.state.location.pathname).toBe("/");
456 +
457 + await act(async () => {
458 + saved.resolve();
459 + await saved.promise;
460 + });
461 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
462 + expect(screen.router?.state.location.pathname).toBe("/");
463 + expect(state.createProject).toHaveBeenCalledTimes(2);
464 +});
465 +
466 +it("gives projects a later scan finds the default, unless the main box was unchecked", async () => {
467 + using _now = setup();
468 + await using _screen = await mountWelcome();
469 + // Turning on another agent rescans and finds a recent project the user has not seen.
470 + const findProject = (path: string) =>
471 + act(async () =>
472 + appAtomRegistry.set(candidatesAtom(), [
473 + ...appAtomRegistry.get(candidatesAtom()),
474 + candidate(path),
475 + ]),
476 + );
477 +
478 + await click("Review all 2");
479 + await click("Select none");
480 + await findProject("/projects/third");
481 + await vi.waitFor(() => expect(button("Import 1 project and start").disabled).toBe(false));
482 +
483 + const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
484 + await act(async () => importProjects?.click());
485 + await findProject("/projects/fourth");
486 + await vi.waitFor(() => expect(button("Start").disabled).toBe(false));
487 +});
488 +
489 +it("keeps the project choice across a visit to Settings until setup finishes", async () => {
490 + using _now = setup();
491 + {
492 + await using _first = await mountWelcome();
493 + const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
494 + await act(async () => importProjects?.click());
495 + await vi.waitFor(() => expect(button("Start").disabled).toBe(false));
496 + }
497 + // Coming back from Settings mounts the page again.
498 + {
499 + await using _second = await mountWelcome();
500 + expect(button("Start").disabled).toBe(false);
501 + await click("Start");
502 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
503 + expect(state.createProject).not.toHaveBeenCalled();
504 + }
505 + await using _third = await mountWelcome();
506 + expect(button("Import 2 projects and start").disabled).toBe(false);
507 +});
508 +
509 +it("stays busy while setup saves after an import with nothing to open", async () => {
510 + using _now = setup();
511 + appAtomRegistry.set(candidatesAtom(), [candidate("/projects/first")]);
512 + state.importThreads.mockResolvedValue(AsyncResult.success({ importedCount: 0, skippedCount: 1 }));
513 + const saved = deferred<void>();
514 + state.completeOnboarding.mockImplementationOnce(() => saved.promise);
515 + await using _screen = await mountWelcome();
516 +
517 + await click("Import 1 project and start");
518 + await vi.waitFor(() => expect(state.completeOnboarding).toHaveBeenCalledOnce());
519 + expect(button("Importing…").disabled).toBe(true);
520 + await act(async () => {
521 + saved.resolve();
522 + await saved.promise;
523 + });
524 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
525 + expect(state.createProject).toHaveBeenCalledOnce();
526 +});
527 +
528 +it("leaves projects already in T3 Code out of the default import, unless the box is checked", async () => {
529 + using _now = setup();
530 + const existing = ProjectId.make("existing");
531 + const justAdded = ProjectId.make("just-added");
532 + appAtomRegistry.set(projectsAtom(), [
533 + { id: existing, environmentId: primaryId, workspaceRoot: "/projects/first" },
534 + // Added a moment ago, so the cached scan does not know it exists yet.
535 + { id: justAdded, environmentId: primaryId, workspaceRoot: "/projects/second" },
536 + ]);
537 + appAtomRegistry.set(candidatesAtom(), [
538 + candidate("/projects/first", { alreadyImported: true, projectId: existing }),
539 + candidate("/projects/second"),
540 + candidate("/projects/third"),
541 + ]);
542 + {
543 + await using _screen = await mountWelcome();
544 + await vi.waitFor(() => expect(pageText()).toContain("Import 1 project and their threads"));
545 + }
546 +
547 + // With every project already in T3 Code, checking the box still picks them.
548 + appAtomRegistry.set(candidatesAtom(), appAtomRegistry.get(candidatesAtom()).slice(0, 2));
549 + await using _screen = await mountWelcome();
550 + const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
551 + await act(async () => importProjects?.click());
552 + await vi.waitFor(() => expect(pageText()).toContain("Import 2 projects and their threads"));
553 + expect(button("Import threads and start").disabled).toBe(false);
554 +});
555 +
556 +it("keeps the started projects checked when the page opens again after a quit", async () => {
557 + using _now = setup();
558 + const imported = deferred<{ importedCount: number; skippedCount: number }>();
559 + state.importThreads.mockImplementationOnce(async () =>
560 + AsyncResult.success(await imported.promise),
561 + );
562 + {
563 + await using _first = await mountWelcome();
564 + await click("Import 2 projects and start");
565 + await vi.waitFor(() => expect(state.importThreads).toHaveBeenCalledOnce());
566 + }
567 + // The app quit during the first project's history; it now exists in T3 Code.
568 + const [first] = appAtomRegistry.get(projectsAtom());
569 + appAtomRegistry.set(candidatesAtom(), [
570 + candidate("/projects/first", { alreadyImported: true, projectId: first!.id }),
571 + candidate("/projects/second"),
572 + ]);
573 + await using _second = await mountWelcome();
574 + await vi.waitFor(() => expect(pageText()).toContain("Import 2 projects and their threads"));
575 +});
576 +
577 +it("keeps the project controls when a later scan fails", async () => {
578 + using _now = setup();
579 + await using _screen = await mountWelcome();
580 + state.scanError = "The scan timed out.";
581 + await act(async () =>
582 + appAtomRegistry.set(candidatesAtom(), [...appAtomRegistry.get(candidatesAtom())]),
583 + );
584 + await vi.waitFor(() => expect(pageText()).toContain("Could not check projects again."));
585 + expect(button("Import 2 projects and start").disabled).toBe(false);
586 + expect(button("Retry").disabled).toBe(false);
587 +});
588 +
589 +it("keeps saved picks when Start comes before the project list loads", async () => {
590 + using _now = setup();
591 + const saved = JSON.stringify({ knownKeys: ["a"], keys: ["a"], optedOut: false });
592 + localStorage.setItem(welcomeImportSelectionKey(primaryId), saved);
593 + state.scanPending = true;
594 + await using _screen = await mountWelcome();
595 +
596 + await click("Start");
597 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
598 + // An import a quit cut short is still checked on the next visit.
599 + expect(localStorage.getItem(welcomeImportSelectionKey(primaryId))).toBe(saved);
600 +});
601 +
602 +it("offers Update for a signed-in agent whose version is broken, and keeps Start off", async () => {
603 + using _now = setup();
604 + appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
605 + {
606 + ...readyClaude,
607 + compatibilityAdvisory: {
608 + status: "broken",
609 + message: "Update Claude Code to 2.0 or later.",
610 + recommendedVersion: "2.0.0",
611 + recommendedRange: null,
612 + },
613 + },
614 + ]);
615 + await using _screen = await mountWelcome();
616 + await vi.waitFor(() => expect(pageText()).toContain("Update Claude Code to 2.0 or later."));
617 + const update = [...document.querySelectorAll("a")].find(
618 + (element) => element.textContent?.trim() === "Update",
619 + );
620 + expect(update?.getAttribute("href")).toContain("/settings/providers");
621 + expect(button("Import 2 projects and start").disabled).toBe(true);
622 +});
623 +
624 +it("keeps an import opt-out on the page when storage cannot save it", async () => {
625 + using _now = setup();
626 + await using _screen = await mountWelcome();
627 + using _full = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
628 + throw new DOMException("The quota has been exceeded.", "QuotaExceededError");
629 + });
630 + const importProjects = document.querySelector<HTMLElement>('[role="checkbox"]');
631 + await act(async () => importProjects?.click());
632 +
633 + await click("Start");
634 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
635 + expect(state.createProject).not.toHaveBeenCalled();
636 +});
637 +
638 +it("opens the list of agents to add once the checks find none, even after a wrong first status", async () => {
639 + using _now = setup();
640 + const pi = {
641 + ...readyClaude,
642 + instanceId: ProviderInstanceId.make("pi"),
643 + driver: ProviderDriverKind.make("pi"),
644 + };
645 + // Pi's first status says installed before its check runs.
646 + appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
647 + { ...pi, status: "warning", auth: { status: "unknown" } },
648 + ]);
649 + await using _screen = await mountWelcome();
650 + await act(async () =>
651 + appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
652 + { ...pi, installed: false, status: "error", auth: { status: "unknown" } },
653 + ]),
654 + );
655 + const fold = () =>
656 + [...document.querySelectorAll("button")].find((element) =>
657 + element.textContent?.startsWith("Set up an agent"),
658 + );
659 + await vi.waitFor(() => expect(fold()?.getAttribute("aria-expanded")).toBe("true"));
660 +
661 + // Turning an agent on starts a new check; the open list stays where the user is working.
662 + await act(async () =>
663 + appAtomRegistry.set(state.providers as Atom.Writable<ReadonlyArray<ServerProvider>>, [
664 + { ...pi, installed: false, status: "warning", auth: { status: "unknown" } },
665 + ]),
666 + );
667 + expect(fold()?.getAttribute("aria-expanded")).toBe("true");
668 +});
669 +
670 +it("starts without importing when this connection cannot import projects", async () => {
671 + using _now = setup();
672 + setGrant(primaryId, false);
673 + await using _screen = await mountWelcome();
674 + expect(pageText()).not.toContain("Review all");
675 +
676 + await click("Start");
677 + await vi.waitFor(() => expect(state.onDone).toHaveBeenCalledOnce());
678 + expect(state.createProject).not.toHaveBeenCalled();
679 +});
680 +
681 +it("says the phone is set up only once this computer is shared with the signed-in account", async () => {
682 + using _now = setup();
683 + state.cloud = true;
684 + state.auth = { isLoaded: true, isSignedIn: true, userId: "user_1" };
685 + appAtomRegistry.set(
686 + sessionAtom(primaryId),
687 + AsyncResult.success(
688 + session([AuthOrchestrationOperateScope, AuthRelayReadScope, AuthRelayWriteScope]),
689 + ),
690 + );
691 + state.linkError = "Could not read T3 Connect link state.";
692 + await using _screen = await mountWelcome();
693 + await click("Set up");
694 + // A failed read says so instead of asking to share the computer again.
695 + await vi.waitFor(() => expect(pageText()).toContain("Could not check T3 Connect."));
696 + expect(pageText()).not.toContain("Set up T3 Connect");
697 +
698 + state.linkError = null;
699 + await act(async () =>
700 + appAtomRegistry.set(state.linkState as Atom.Writable<EnvironmentCloudLinkStateResult | null>, {
701 + linked: false,
702 + cloudUserId: null,
703 + relayUrl: null,
704 + relayIssuer: null,
705 + publishAgentActivity: false,
706 + }),
707 + );
708 + // Signed in, but "Not now" on the share step left this computer unreachable.
709 + await vi.waitFor(() => expect(pageText()).toContain("Set up T3 Connect"));
710 +
711 + const share = (reachability: EnvironmentCloudLinkStateResult["reachability"]) =>
712 + act(async () =>
713 + appAtomRegistry.set(
714 + state.linkState as Atom.Writable<EnvironmentCloudLinkStateResult | null>,
715 + {
716 + linked: true,
717 + cloudUserId: "user_1",
718 + relayUrl: null,
719 + relayIssuer: null,
720 + managedTunnelActive: true,
721 + publishAgentActivity: true,
722 + reachability,
723 + },
724 + ),
725 + );
726 + const checkedAt = "2026-01-01T00:00:00.000Z";
727 + await share({
728 + status: "unreachable",
729 + checkedAt,
730 + cause: "connector_not_running",
731 + reason: "The tunnel is not running.",
732 + hint: null,
733 + fix: "Turn T3 Connect off and on.",
734 + });
735 + await vi.waitFor(() => expect(pageText()).toContain("Check T3 Connect"));
736 + expect(pageText()).not.toContain("Your phone can reach this computer.");
737 +
738 + await share({ status: "reachable", checkedAt, readyConnections: 4, protocol: "quic" });
739 + await vi.waitFor(() => expect(pageText()).toContain("Your phone can reach this computer."));
740 + expect(pageText()).not.toContain("Check T3 Connect");
741 +});
apps/web/src/components/onboarding/WelcomePage.tsx new
+1885
@@ -0,0 +1,1885 @@
1 +import { useAuth } from "@clerk/react";
2 +import { useAtomValue } from "@effect/atom-react";
3 +import type {
4 + AgentSessionProjectCandidate,
5 + EnvironmentId,
6 + ProjectId,
7 + ProviderInstanceId,
8 + ScopedProjectRef,
9 + ServerConfig,
10 + ServerProvider,
11 +} from "@t3tools/contracts";
12 +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
13 +import { resolveProviderInstanceDisplayName as agentName } from "@t3tools/client-runtime/state/provider-instance-display";
14 +import {
15 + isAtomCommandInterrupted,
16 + squashAtomCommandFailure,
17 +} from "@t3tools/client-runtime/state/runtime";
18 +import {
19 + AgentSessionSource,
20 + AuthProvidersManageScope,
21 + AuthRelayReadScope,
22 + AuthRelayWriteScope,
23 + AuthTerminalOperateScope,
24 + CommandId,
25 + AuthOrchestrationOperateScope,
26 + isManagedDriverAllowed,
27 + ProviderDriverKind,
28 + ThreadId,
29 +} from "@t3tools/contracts";
30 +import { Link, useBlocker } from "@tanstack/react-router";
31 +import * as Schema from "effect/Schema";
32 +import {
33 + CheckIcon,
34 + ChevronDownIcon,
35 + ChevronRightIcon,
36 + PlusIcon,
37 + SmartphoneIcon,
38 + TerminalIcon,
39 +} from "lucide-react";
40 +import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
41 +
42 +import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";
43 +import { MOBILE_APP_URL } from "../../branding";
44 +import { isElectron } from "../../env";
45 +import { useLocalStorage } from "../../hooks/useLocalStorage";
46 +import { usePersistEnvironmentProviderInstanceMutation } from "../../hooks/useSettings";
47 +import { useCloudLinkState } from "../../cloud/cloudLinkState";
48 +import { hasCloudPublicConfig } from "../../cloud/publicConfig";
49 +import { PRIVACY_POLICY_URL } from "../../legalLinks";
50 +import { workspaceAreaProps } from "../../lib/workspaceFocus";
51 +import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
52 +import { completeOnboarding } from "../../onboarding/firstRun";
53 +import {
54 + groupOnboardingProjects,
55 + partitionOnboardingProjects,
56 + onboardingProjectKey,
57 + resolveOnboardingLandingProject,
58 + isNewOnboardingProject,
59 + resolveOnboardingProjectId,
60 + type OnboardingProjectGroup,
61 + splitOnboardingProjectPath,
62 +} from "../../onboarding/projectImport.logic";
63 +import {
64 + resolveOnboardingProviderInstallCommand,
65 + resolveOnboardingProviderLoginCommand,
66 +} from "../../onboarding/providerReadiness.logic";
67 +import {
68 + cliTerminalStep,
69 + codexCardProvider,
70 + codexNeedsSetup,
71 + groupWelcomeAgents,
72 + isBrokenVersion,
73 + turnedOnInstance,
74 + welcomeAgentState,
75 + welcomeOffersPhone,
76 +} from "../../onboarding/welcomePage.logic";
77 +import {
78 + StoredWelcomeImportSelection,
79 + type WelcomeImportSelection,
80 + welcomeImportSelectionKey,
81 +} from "../../onboarding/welcomeState";
82 +import { newProjectId, randomUUID } from "../../lib/utils";
83 +import { agentSessionImport } from "../../state/agentSessions";
84 +import { readProjects, useProjects, waitForProject } from "../../state/entities";
85 +import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
86 +import { managedTelemetryOffMessage, useManagedPolicy } from "../../state/managedPolicy";
87 +import { useProjectScans } from "../../onboarding/useProjectScans";
88 +import { projectEnvironment } from "../../state/projects";
89 +import { serverEnvironment } from "../../state/server";
90 +import {
91 + readEnvironmentScope,
92 + useEnvironmentScope,
93 + useEnvironmentsWithScope,
94 +} from "../../state/session";
95 +import { terminalEnvironment } from "../../state/terminal";
96 +import { useAtomCommand } from "../../state/use-atom-command";
97 +import { getProviderSummary } from "../settings/providerStatus";
98 +import { AddProviderInstanceDialog } from "../settings/AddProviderInstanceDialog";
99 +import { useDesktopCliCommand } from "../settings/CliCommandSettingsRow";
100 +import { CodexSetupSection } from "../settings/CodexSetupSection";
101 +import { readCodexSetupMode } from "../settings/CodexSetupSection.logic";
102 +import { TerminalViewport } from "../ThreadTerminalDrawer";
103 +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
104 +import { ACPRegistryIcon } from "../Icons";
105 +import { Button } from "../ui/button";
106 +import { Checkbox } from "../ui/checkbox";
107 +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
108 +import { QRCodeSvg } from "../ui/qr-code";
109 +import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
110 +import { ScrollArea } from "../ui/scroll-area";
111 +import { SidebarInset } from "../ui/sidebar";
112 +import { toastManager } from "../ui/toast";
113 +import { WorkspacePageHeader } from "../WorkspacePageHeader";
114 +import { cn } from "../../lib/utils";
115 +import { formatRelativeTime } from "../../timestampFormat";
116 +
117 +const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup");
118 +const SCAN_LIMIT_MESSAGE = "Scan limit reached. Some projects or conversations may be missing.";
119 +
120 +/**
121 + * First-run page for one computer: its agents, the projects found in agent history, and the
122 + * phone app. Every part is optional except one ready agent to start chatting.
123 + */
124 +export function WelcomePage({
125 + environmentId,
126 + onDone,
127 +}: {
128 + readonly environmentId: EnvironmentId;
129 + readonly onDone: (projectRef?: ScopedProjectRef) => void | Promise<void>;
130 +}) {
131 + const { environments } = useEnvironments();
132 + const label =
133 + environments.find((environment) => environment.environmentId === environmentId)?.label ??
134 + "this computer";
135 + const agentReady = useWelcomeAgents(environmentId).readyCount > 0;
136 + // The phone and `t3` on PATH belong to the primary computer, so only it offers them.
137 + const isPrimary = usePrimaryEnvironmentId() === environmentId;
138 + // The same access Settings → Sharing & access checks.
139 + const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
140 + const canWriteRelay = useEnvironmentScope(environmentId, AuthRelayWriteScope);
141 + const showPhone = welcomeOffersPhone({
142 + isPrimary,
143 + cloud: hasCloudPublicConfig(),
144 + canShare: canReadRelay && canWriteRelay,
145 + policy: useManagedPolicy(environmentId),
146 + });
147 + const scans = useProjectScans([environmentId]);
148 + const [storedSelection, storeSelection] = useLocalStorage(
149 + welcomeImportSelectionKey(environmentId),
150 + null,
151 + StoredWelcomeImportSelection,
152 + );
153 + // The page keeps its own copy, so a failed write (a full quota) cannot undo a choice.
154 + const [importSelection, setImportSelectionState] = useState(storedSelection);
155 + const setImportSelection = (next: WelcomeImportSelection | null) => {
156 + setImportSelectionState(next);
157 + storeSelection(next);
158 + };
159 + const [isImporting, setIsImporting] = useState(false);
160 + // True from Start until the landing; leaving earlier would drop the import or the landing.
161 + const holdPageRef = useRef(false);
162 + useBlocker({
163 + shouldBlockFn: () => {
164 + if (!holdPageRef.current) return false;
165 + toastManager.add({
166 + id: "welcome-finishing",
167 + type: "info",
168 + title: "Finishing setup",
169 + description: "One moment.",
170 + });
171 + return true;
172 + },
173 + // Electron cancels a quit silently when unload is blocked. A later visit resumes the import.
174 + enableBeforeUnload: false,
175 + });
176 + const finishingPromiseRef = useRef<Promise<boolean> | null>(null);
177 + // Starting before the project list loads keeps saved picks, such as an import a quit cut short.
178 + const keepChoicesRef = useRef(false);
179 + const completionErrorToastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
180 + const finish = (
181 + projectRef?: ScopedProjectRef,
182 + importWarning?: string,
183 + importedThreadCount = 0,
184 + ) => {
185 + if (finishingPromiseRef.current !== null) return finishingPromiseRef.current;
186 + if (completionErrorToastIdRef.current !== null) {
187 + toastManager.close(completionErrorToastIdRef.current);
188 + completionErrorToastIdRef.current = null;
189 + }
190 +
191 + holdPageRef.current = true;
192 + const completion = completeOnboarding()
193 + .then(async () => {
194 + if (completionErrorToastIdRef.current !== null) {
195 + toastManager.close(completionErrorToastIdRef.current);
196 + completionErrorToastIdRef.current = null;
197 + }
198 + // Release before onDone so its own navigation is not blocked.
199 + holdPageRef.current = false;
200 + await onDone(projectRef);
201 + if (!keepChoicesRef.current) setImportSelection(null);
202 + if (importWarning) {
203 + toastManager.add({
204 + type: "warning",
205 + title: "Some history was not imported",
206 + description: importWarning,
207 + timeout: 0,
208 + });
209 + } else if (importedThreadCount > 0) {
210 + toastManager.add({
211 + type: "success",
212 + title: `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}`,
213 + });
214 + }
215 + return true;
216 + })
217 + .catch(() => {
218 + holdPageRef.current = false;
219 + const errorToast = {
220 + type: "error",
221 + title: "Could not finish setup",
222 + description: "Your settings could not be saved. Try again.",
223 + } as const;
224 + if (completionErrorToastIdRef.current === null) {
225 + completionErrorToastIdRef.current = toastManager.add(errorToast);
226 + } else {
227 + toastManager.update(completionErrorToastIdRef.current, errorToast);
228 + }
229 + return false;
230 + })
231 + .finally(() => {
232 + if (finishingPromiseRef.current === completion) {
233 + finishingPromiseRef.current = null;
234 + }
235 + });
236 + finishingPromiseRef.current = completion;
237 + return completion;
238 + };
239 + const projectImport = useProjectImport({
240 + scans,
241 + importSelection,
242 + onImportSelectionChange: setImportSelection,
243 + isImporting,
244 + setIsImporting,
245 + holdPageRef,
246 + onDone: finish,
247 + });
248 + // Without import permission, starting simply skips the projects.
249 + const selected = projectImport.canWrite ? projectImport.selected : [];
250 + const newCount = selected.filter(projectImport.isNew).length;
251 + const start = () => {
252 + keepChoicesRef.current = scans.some((scan) => scan.data === null);
253 + if (selected.length === 0) {
254 + projectImport.finishAfterImport();
255 + return;
256 + }
257 + // Stored now, so after a restart mid-import these stay checked even once they exist.
258 + projectImport.setSelectedKeys(new Set(selected.map((candidate) => candidate.key)));
259 + void projectImport.runImport(selected);
260 + };
261 +
262 + return (
263 + <SidebarInset
264 + {...workspaceAreaProps("home", 1, "Welcome")}
265 + role="main"
266 + className="h-dvh min-h-0 overflow-hidden overscroll-y-none"
267 + >
268 + <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
269 + {/* The desktop window only moves where CSS opts in, so keep a titlebar strip. */}
270 + {isElectron ? <WorkspacePageHeader electron /> : null}
271 + <div className="min-h-0 flex-1 overflow-y-auto scrollbar-gutter-both">
272 + <div className="mx-auto flex min-h-full w-full max-w-3xl flex-col px-6 pt-12 pb-8 sm:pt-20">
273 + <h1 className="text-2xl font-semibold tracking-tight text-foreground">
274 + Welcome to T3 Code
275 + </h1>
276 + <p className="mt-1.5 text-sm text-muted-foreground">
277 + Setting up <span className="text-foreground">{label}</span>.
278 + </p>
279 + <div className="mt-10 border-t border-border/60">
280 + <AgentsSection
281 + environmentId={environmentId}
282 + label={label}
283 + isPrimary={isPrimary}
284 + onImportSourceEnabled={() => scans[0]?.refresh()}
285 + />
286 + <ProjectsSection
287 + scan={scans[0]}
288 + projectImport={projectImport}
289 + isImporting={isImporting}
290 + />
291 + {showPhone ? <PhoneSection environmentId={environmentId} /> : null}
292 + </div>
293 + <div className="mt-6 flex flex-wrap items-center justify-between gap-3">
294 + {agentReady ? (
295 + <span />
296 + ) : (
297 + <Button variant="ghost-muted" disabled={isImporting} onClick={start}>
298 + Start without an agent
299 + </Button>
300 + )}
301 + <div className="flex items-center gap-3">
302 + {agentReady ? null : (
303 + <span className="text-xs text-muted-foreground">Set up one agent to start.</span>
304 + )}
305 + <Button disabled={!agentReady || isImporting} onClick={start}>
306 + {isImporting
307 + ? selected.length > 0
308 + ? "Importing…"
309 + : "Starting…"
310 + : newCount > 0
311 + ? `Import ${newCount} ${newCount === 1 ? "project" : "projects"} and start`
312 + : selected.length > 0
313 + ? "Import threads and start"
314 + : "Start"}
315 + </Button>
316 + </div>
317 + </div>
318 + <TelemetryNotice environmentId={environmentId} />
319 + </div>
320 + </div>
321 + </div>
322 + </SidebarInset>
323 + );
324 +}
325 +
326 +function TelemetryNotice({ environmentId }: { readonly environmentId: EnvironmentId }) {
327 + const telemetryOff = managedTelemetryOffMessage(useManagedPolicy(environmentId));
328 + return (
329 + <p className="mt-auto pt-12 text-2xs leading-relaxed text-muted-foreground/70">
330 + {telemetryOff ?? "T3 Code collects anonymous usage data to improve the app."}{" "}
331 + {telemetryOff === undefined ? "To opt out, see the" : "See the"}{" "}
332 + <a
333 + className="underline decoration-current/40 underline-offset-2 hover:text-muted-foreground"
334 + href={PRIVACY_POLICY_URL}
335 + target="_blank"
336 + rel="noreferrer noopener"
337 + >
338 + privacy policy
339 + </a>
340 + .
341 + </p>
342 + );
343 +}
344 +
345 +// Each part of the page is one band: its label on the left, its rows on the right.
346 +function WelcomeSection({
347 + title,
348 + children,
349 +}: {
350 + readonly title: string;
351 + readonly children: ReactNode;
352 +}) {
353 + return (
354 + <section className="grid gap-x-10 border-b border-border/60 py-4 sm:grid-cols-[6rem_minmax(0,1fr)]">
355 + <h2 className="text-sm leading-10 text-muted-foreground">{title}</h2>
356 + <div className="min-w-0">{children}</div>
357 + </section>
358 + );
359 +}
360 +
361 +// Rows share one icon column, so names, checkboxes, and steps line up down the page.
362 +function RowIcon({ children }: { readonly children: ReactNode }) {
363 + return (
364 + <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">
365 + {children}
366 + </span>
367 + );
368 +}
369 +
370 +const INSTALLABLE_DRIVERS = ["codex", "claudeAgent"] as const;
371 +type OnboardingAgentDriver = (typeof INSTALLABLE_DRIVERS)[number];
372 +const isInstallableDriver = (driver: string): driver is OnboardingAgentDriver =>
373 + (INSTALLABLE_DRIVERS as ReadonlyArray<string>).includes(driver);
374 +
375 +interface AgentTerminalSession {
376 + readonly environmentId: EnvironmentId;
377 + readonly driver: OnboardingAgentDriver;
378 + readonly providerInstanceId: ServerProvider["instanceId"];
379 + readonly cwd: string;
380 + readonly command: string;
381 + readonly keybindings: ServerConfig["keybindings"];
382 +}
383 +
384 +// Shared by the page (to enable Start) and the agents section, so both agree on what is ready.
385 +function useWelcomeAgents(environmentId: EnvironmentId) {
386 + const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));
387 + const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
388 + const managedPolicy = serverConfig?.managedPolicy;
389 + return {
390 + providers,
391 + serverConfig,
392 + ...groupWelcomeAgents(providers, serverConfig?.settings, agentName, (provider) =>
393 + isManagedDriverAllowed(managedPolicy, provider.driver),
394 + ),
395 + };
396 +}
397 +
398 +const isImportSource = Schema.is(AgentSessionSource);
399 +
400 +// The setup card opens below a long list, so bring it into view once.
401 +const revealOnMount = (node: HTMLElement | null) => node?.scrollIntoView({ block: "nearest" });
402 +
403 +const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
404 +
405 +function AgentsSection({
406 + environmentId,
407 + label,
408 + isPrimary,
409 + onImportSourceEnabled,
410 +}: {
411 + readonly environmentId: EnvironmentId;
412 + readonly label: string;
413 + readonly isPrimary: boolean;
414 + // The project scan only reads agents that are on, so turning one on can find more history.
415 + readonly onImportSourceEnabled: () => void;
416 +}) {
417 + const { providers, serverConfig, checking, found, available } = useWelcomeAgents(environmentId);
418 + const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
419 + reportFailure: false,
420 + });
421 + const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
422 + const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
423 + const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
424 + const [terminalSession, setTerminalSession] = useState<AgentTerminalSession | null>(null);
425 + const [moreOpen, setMoreOpen] = useState<boolean | null>(null);
426 + const [addingProvider, setAddingProvider] = useState(false);
427 + const [codexSetupId, setCodexSetupId] = useState<ProviderInstanceId | null>(null);
428 + const [cliTerminalFor, setCliTerminalFor] = useState<ProviderInstanceId | null>(null);
429 +
430 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the environment to refresh its provider list when the environment changes
431 + useEffect(() => {
432 + void refreshProviders({ environmentId, input: {} });
433 + }, [environmentId, refreshProviders]);
434 +
435 + // Opened once the finished checks find nothing, since adding an agent is then the task. A first
436 + // status can be wrong, so this waits for the checks, and a later check never closes it.
437 + if (moreOpen === null && !checking && found.length === 0) setMoreOpen(true);
438 + const showMore = moreOpen ?? false;
439 + const acpAllowed = isManagedDriverAllowed(serverConfig?.managedPolicy, ACP_REGISTRY_DRIVER_KIND);
440 + const stateOf = (provider: ServerProvider) => welcomeAgentState(provider, serverConfig?.settings);
441 + const needsInstallOrSignIn = (provider: ServerProvider) => {
442 + const state = stateOf(provider);
443 + return (
444 + isInstallableDriver(provider.driver) &&
445 + !isBrokenVersion(provider) &&
446 + (state === "install" || state === "signIn")
447 + );
448 + };
449 + // Codex's card also offers ChatGPT sign-in, which still works when the CLI check failed.
450 + // Codex setup stays mounted by instance while its status changes, so a sign-in that starts
451 + // after an install is not lost when the agent moves between groups or briefly leaves the list.
452 + const [lastCodex, setLastCodex] = useState<ServerProvider | null>(null);
453 + const listedCodex =
454 + codexSetupId === null
455 + ? undefined
456 + : providers?.find((provider) => provider.instanceId === codexSetupId);
457 + if (listedCodex !== undefined && listedCodex !== lastCodex) setLastCodex(listedCodex);
458 + const codexSetupProvider = codexCardProvider({
459 + providers,
460 + instanceId: codexSetupId,
461 + last: lastCodex,
462 + settings: serverConfig?.settings,
463 + });
464 + // Once the card closes, a later status change does not reopen it and move the page.
465 + if (listedCodex !== undefined && codexSetupProvider === null) setCodexSetupId(null);
466 +
467 + const openTerminal = (provider: ServerProvider) => {
468 + if (
469 + !isInstallableDriver(provider.driver) ||
470 + serverConfig === null ||
471 + !readEnvironmentScope(environmentId, AuthTerminalOperateScope)
472 + )
473 + return;
474 + setTerminalSession({
475 + environmentId,
476 + driver: provider.driver,
477 + providerInstanceId: provider.instanceId,
478 + cwd: serverConfig.cwd,
479 + command: provider.installed
480 + ? resolveOnboardingProviderLoginCommand(
481 + provider,
482 + serverConfig.settings,
483 + serverConfig.environment.platform.os,
484 + )
485 + : resolveOnboardingProviderInstallCommand(
486 + provider.driver,
487 + serverConfig.environment.platform.os,
488 + ),
489 + keybindings: serverConfig.keybindings,
490 + });
491 + };
492 +
493 + // "Use existing CLI" opens the CLI's terminal once Codex has checked the CLI.
494 + const cliProvider =
495 + cliTerminalFor === null
496 + ? undefined
497 + : providers?.find((provider) => provider.instanceId === cliTerminalFor);
498 + const cliStep =
499 + cliProvider === undefined ? "done" : cliTerminalStep(cliProvider, serverConfig?.settings);
500 + if (cliProvider !== undefined && cliStep !== "wait") {
501 + setCliTerminalFor(null);
502 + if (cliStep === "open") openTerminal(cliProvider);
503 + }
504 +
505 + const turnOn = async (provider: ServerProvider) => {
506 + if (serverConfig === null) return;
507 + const instance = serverConfig.settings.providerInstances[provider.instanceId] ?? {
508 + driver: provider.driver,
509 + };
510 + const result = await persistProviderInstance({
511 + operation: "upsert",
512 + instanceId: provider.instanceId,
513 + instance: turnedOnInstance(instance),
514 + });
515 + if (result._tag === "Failure") {
516 + if (!isAtomCommandInterrupted(result)) {
517 + const cause = squashAtomCommandFailure(result);
518 + toastManager.add({
519 + type: "error",
520 + title: `Could not turn on ${agentName(provider)}`,
521 + ...(cause instanceof Error ? { description: cause.message } : {}),
522 + });
523 + }
524 + return;
525 + }
526 + void refreshProviders({ environmentId, input: { instanceId: provider.instanceId } });
527 + if (isImportSource(provider.driver)) onImportSourceEnabled();
528 + };
529 +
530 + // One action per agent, the same in the list and in the grid.
531 + const actionFor = (provider: ServerProvider) => {
532 + const state = stateOf(provider);
533 + const name = agentName(provider);
534 + const settingsAction = (actionLabel: string) => (
535 + <Button
536 + size="xs"
537 + variant="outline"
538 + aria-label={`${actionLabel}: ${name}`}
539 + render={
540 + <Link
541 + to="/settings/providers"
542 + search={{ environmentId, instanceId: provider.instanceId }}
543 + />
544 + }
545 + >
546 + {actionLabel}
547 + </Button>
548 + );
549 + if (state === "disabled") {
550 + return (
551 + <Button
552 + size="xs"
553 + variant="outline"
554 + aria-label={`Turn on: ${name}`}
555 + disabled={!canManageProviders || serverConfig === null}
556 + onClick={() => void turnOn(provider)}
557 + >
558 + Turn on
559 + </Button>
560 + );
561 + }
562 + // Settings updates a broken CLI the way it was installed, including a custom binary path.
563 + if (isBrokenVersion(provider)) return settingsAction("Update");
564 + if (serverConfig !== null && codexNeedsSetup(provider, serverConfig.settings)) {
565 + const open = codexSetupId === provider.instanceId;
566 + return (
567 + <Button
568 + size="xs"
569 + variant="outline"
570 + aria-label={`Set up: ${name}`}
571 + aria-expanded={open}
572 + onClick={() => setCodexSetupId(open ? null : provider.instanceId)}
573 + >
574 + Set up
575 + </Button>
576 + );
577 + }
578 + if (needsInstallOrSignIn(provider)) {
579 + return (
580 + <TerminalAction
581 + name={name}
582 + signIn={state === "signIn"}
583 + disabled={
584 + terminalSession?.providerInstanceId === provider.instanceId ||
585 + serverConfig === null ||
586 + !canOperateTerminal
587 + }
588 + onClick={() => openTerminal(provider)}
589 + />
590 + );
591 + }
592 + return settingsAction(
593 + state === "signIn" ? "Sign in" : state === "attention" ? "Details" : "Set up",
594 + );
595 + };
596 +
597 + const notes = [
598 + !canOperateTerminal &&
599 + [...found, ...available].some(
600 + (provider) =>
601 + needsInstallOrSignIn(provider) || codexNeedsSetup(provider, serverConfig?.settings),
602 + )
603 + ? "This connection cannot control terminals."
604 + : null,
605 + !canManageProviders &&
606 + (acpAllowed ||
607 + [...found, ...available].some(
608 + (provider) =>
609 + stateOf(provider) === "disabled" || codexNeedsSetup(provider, serverConfig?.settings),
610 + ))
611 + ? "This connection cannot manage agents."
612 + : null,
613 + ].filter((note) => note !== null);
614 +
615 + return (
616 + <WelcomeSection title="Agents">
617 + {found.map((provider) => (
618 + <AgentRow
619 + key={provider.instanceId}
620 + provider={provider}
621 + state={stateOf(provider)}
622 + action={actionFor(provider)}
623 + />
624 + ))}
625 + {checking && found.length === 0 ? (
626 + <p className="text-sm leading-10 text-muted-foreground">Checking {label}…</p>
627 + ) : null}
628 + {notes.map((note) => (
629 + <p key={note} className="pl-8 text-xs text-muted-foreground">
630 + {note}
631 + </p>
632 + ))}
633 + <Collapsible open={showMore} onOpenChange={setMoreOpen}>
634 + <CollapsibleTrigger className="group flex min-h-10 w-full items-center gap-3 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset">
635 + <RowIcon>
636 + <PlusIcon className="size-4" />
637 + </RowIcon>
638 + <span
639 + className={cn(
640 + "text-sm group-hover:text-foreground",
641 + found.length > 0 ? "text-muted-foreground" : "text-foreground",
642 + )}
643 + >
644 + {found.length > 0 ? "Add more agents" : "Set up an agent"}
645 + </span>
646 + {showMore ? null : <AgentLogoStack providers={available} acp={acpAllowed} />}
647 + <ChevronDownIcon className="ml-auto size-4 text-muted-foreground group-data-panel-open:rotate-180" />
648 + </CollapsibleTrigger>
649 + <CollapsiblePanel>
650 + <div className="grid grid-cols-1 gap-x-8 sm:grid-cols-2">
651 + {available.map((provider) => (
652 + <AgentRow
653 + key={provider.instanceId}
654 + provider={provider}
655 + state={stateOf(provider)}
656 + compact
657 + action={actionFor(provider)}
658 + />
659 + ))}
660 + </div>
661 + {acpAllowed ? (
662 + <div className="flex min-h-9 items-center gap-3">
663 + <RowIcon>
664 + <ACPRegistryIcon className="size-4" />
665 + </RowIcon>
666 + <span className="min-w-0 flex-1 text-sm text-muted-foreground">
667 + More agents in the ACP Registry
668 + </span>
669 + <Button
670 + size="xs"
671 + variant="outline"
672 + disabled={!canManageProviders}
673 + onClick={() => setAddingProvider(true)}
674 + >
675 + Browse
676 + </Button>
677 + </div>
678 + ) : null}
679 + </CollapsiblePanel>
680 + </Collapsible>
681 + {codexSetupProvider !== null && serverConfig !== null ? (
682 + <div key={codexSetupProvider.instanceId} ref={revealOnMount} className="mt-2">
683 + <OnboardingCodexSetup
684 + environmentId={environmentId}
685 + provider={codexSetupProvider}
686 + serverConfig={serverConfig}
687 + onUseCliChange={(useCli) =>
688 + setCliTerminalFor(useCli ? codexSetupProvider.instanceId : null)
689 + }
690 + />
691 + </div>
692 + ) : null}
693 + {isPrimary ? <CliPathSetup /> : null}
694 + {terminalSession !== null ? (
695 + <AgentInstallTerminal
696 + key={`${terminalSession.environmentId}:${terminalSession.providerInstanceId}:${terminalSession.driver}`}
697 + session={terminalSession}
698 + onClose={() => {
699 + setTerminalSession(null);
700 + void refreshProviders({ environmentId, input: {} });
701 + }}
702 + />
703 + ) : null}
704 + {addingProvider ? (
705 + <AddProviderInstanceDialog
706 + open
707 + environmentId={environmentId}
708 + environmentLabel={label}
709 + showMoreProviders
710 + onOpenChange={setAddingProvider}
711 + onCreated={(_instanceId, driver) => {
712 + void refreshProviders({ environmentId, input: {} });
713 + // A new Claude Code, Codex, or Pi instance can bring more history to import.
714 + if (isImportSource(driver)) onImportSourceEnabled();
715 + }}
716 + />
717 + ) : null}
718 + </WelcomeSection>
719 + );
720 +}
721 +
722 +// A quiet preview of what the fold holds; the names are inside it.
723 +function AgentLogoStack({
724 + providers,
725 + acp,
726 +}: {
727 + readonly providers: ReadonlyArray<ServerProvider>;
728 + readonly acp: boolean;
729 +}) {
730 + if (providers.length === 0 && !acp) return null;
731 + return (
732 + <span className="flex items-center gap-2 opacity-60 grayscale" aria-hidden>
733 + {providers.slice(0, 6).map((provider) => (
734 + <ProviderInstanceIcon
735 + key={provider.instanceId}
736 + driverKind={provider.driver}
737 + displayName={agentName(provider)}
738 + iconClassName="size-3.5"
739 + />
740 + ))}
741 + {acp ? <ACPRegistryIcon className="size-3.5" /> : null}
742 + </span>
743 + );
744 +}
745 +
746 +function ProjectsSection({
747 + scan,
748 + projectImport,
749 + isImporting,
750 +}: {
751 + readonly scan: ReturnType<typeof useProjectScans>[number] | undefined;
752 + readonly projectImport: ReturnType<typeof useProjectImport>;
753 + readonly isImporting: boolean;
754 +}) {
755 + const [reviewing, setReviewing] = useState(false);
756 + const {
757 + canWrite,
758 + candidates,
759 + isNew,
760 + recent,
761 + selected,
762 + selectedKeys,
763 + setSelectedKeys,
764 + visibleImportError,
765 + } = projectImport;
766 + if (scan === undefined) return null;
767 + if (scan.isPending && candidates.length === 0) {
768 + return (
769 + <WelcomeSection title="Projects">
770 + <p className="text-sm leading-10 text-muted-foreground">
771 + Looking for projects in your {IMPORT_SOURCES_LABEL} history…
772 + </p>
773 + </WelcomeSection>
774 + );
775 + }
776 + const retry = (
777 + <Button variant="ghost" size="sm" onClick={scan.refresh}>
778 + Retry
779 + </Button>
780 + );
781 + if (scan.error !== null && candidates.length === 0) {
782 + return (
783 + <WelcomeSection title="Projects">
784 + <div
785 + role="alert"
786 + className="flex min-h-10 items-center justify-between gap-3 text-sm text-muted-foreground"
787 + >
788 + <span>Could not check projects. {scan.error}</span>
789 + {retry}
790 + </div>
791 + </WelcomeSection>
792 + );
793 + }
794 + if (candidates.length === 0) {
795 + return scan.data?.truncated ? (
796 + <WelcomeSection title="Projects">
797 + <p className="text-xs leading-10 text-muted-foreground" role="status">
798 + {SCAN_LIMIT_MESSAGE}
799 + </p>
800 + </WelcomeSection>
801 + ) : null;
802 + }
803 +
804 + const allKeys = candidates.map((candidate) => candidate.key);
805 + // Checking the box picks recent new projects, else any new ones, else everything listed.
806 + const fresh = candidates.filter(isNew);
807 + const defaultKeys = (recent.length > 0 ? recent : fresh.length > 0 ? fresh : candidates).map(
808 + (candidate) => candidate.key,
809 + );
810 + const partial =
811 + selected.length > 0 &&
812 + selected.length < candidates.length &&
813 + !(selected.length === defaultKeys.length && defaultKeys.every((key) => selectedKeys.has(key)));
814 + return (
815 + <WelcomeSection title="Projects">
816 + <div className="flex min-h-10 items-center gap-3 py-1">
817 + <label className="flex min-w-0 flex-1 items-center gap-3">
818 + <RowIcon>
819 + <Checkbox
820 + checked={canWrite && selected.length > 0}
821 + indeterminate={canWrite && partial}
822 + disabled={isImporting || !canWrite}
823 + onCheckedChange={(checked) =>
824 + setSelectedKeys(new Set(checked ? defaultKeys : []), { optedOut: !checked })
825 + }
826 + />
827 + </RowIcon>
828 + <span className="min-w-0 flex-1">
829 + <span className="block text-sm font-medium text-foreground">
830 + {canWrite && selected.length > 0
831 + ? `Import ${selected.length} ${selected.length === 1 ? "project" : "projects"} and their threads`
832 + : "Import projects and their threads"}
833 + </span>
834 + <span className="block text-xs text-muted-foreground">
835 + From your {IMPORT_SOURCES_LABEL} history
836 + </span>
837 + </span>
838 + </label>
839 + {canWrite ? (
840 + <Button
841 + variant="ghost-muted"
842 + size="xs"
843 + aria-expanded={reviewing}
844 + onClick={() => setReviewing((open) => !open)}
845 + >
846 + {reviewing ? "Hide" : `Review all ${candidates.length}`}
847 + <ChevronDownIcon className={cn("size-3.5", reviewing && "rotate-180")} />
848 + </Button>
849 + ) : null}
850 + </div>
851 + {reviewing && canWrite ? (
852 + // The negative margin lines the list's checkboxes up with the one above it.
853 + <fieldset className="-mx-1.5 mt-1 min-w-0" disabled={isImporting}>
854 + <div className="flex items-center justify-between gap-3 px-2 text-xs text-muted-foreground">
855 + <span role="status">
856 + {selected.length} of {candidates.length} selected
857 + </span>
858 + <div className="flex items-center gap-1">
859 + <Button
860 + variant="ghost"
861 + size="xs"
862 + disabled={selected.length === candidates.length}
863 + onClick={() => setSelectedKeys(new Set(allKeys))}
864 + >
865 + Select all
866 + </Button>
867 + <Button
868 + variant="ghost"
869 + size="xs"
870 + disabled={selected.length === 0}
871 + onClick={() => setSelectedKeys(new Set())}
872 + >
873 + Select none
874 + </Button>
875 + </div>
876 + </div>
877 + <ScrollArea scrollFade className="mt-1 h-auto max-h-80">
878 + <div className="space-y-0.5 pr-3">
879 + <ImportCandidateList
880 + candidates={candidates}
881 + selectedKeys={selectedKeys}
882 + onSelectionChange={setSelectedKeys}
883 + />
884 + </div>
885 + </ScrollArea>
886 + </fieldset>
887 + ) : null}
888 + {scan.data?.truncated ? (
889 + <p className="pl-8 text-xs text-muted-foreground" role="status">
890 + {SCAN_LIMIT_MESSAGE}
891 + </p>
892 + ) : null}
893 + {scan.error !== null ? (
894 + <div
895 + role="alert"
896 + className="flex items-center justify-between gap-3 pl-8 text-sm text-muted-foreground"
897 + >
898 + <span>Could not check projects again. {scan.error}</span>
899 + {retry}
900 + </div>
901 + ) : null}
902 + {visibleImportError ? (
903 + <p className="pt-1 pl-8 text-sm text-destructive">{visibleImportError}</p>
904 + ) : null}
905 + </WelcomeSection>
906 + );
907 +}
908 +
909 +function PhoneSection({ environmentId }: { readonly environmentId: EnvironmentId }) {
910 + const [open, setOpen] = useState(false);
911 + return (
912 + <WelcomeSection title="Phone">
913 + <Collapsible open={open} onOpenChange={setOpen}>
914 + <div className="flex min-h-10 items-center gap-3 py-1">
915 + <RowIcon>
916 + <SmartphoneIcon className="size-4" />
917 + </RowIcon>
918 + <span className="min-w-0 flex-1 text-sm font-medium text-foreground">
919 + Use T3 Code on your phone
920 + </span>
921 + <CollapsibleTrigger render={<Button variant="ghost-muted" size="xs" />}>
922 + {open ? "Hide" : "Set up"}
923 + <ChevronDownIcon className={cn("size-3.5", open && "rotate-180")} />
924 + </CollapsibleTrigger>
925 + </div>
926 + <CollapsiblePanel>
927 + <div className="flex items-center gap-8 pt-2 pb-3 pl-8">
928 + <ol className="min-w-0 flex-1 space-y-5">
929 + <PhoneStep step={1}>
930 + <p className="text-sm text-foreground">Scan with your phone to get the app.</p>
931 + </PhoneStep>
932 + <PhoneStep step={2}>
933 + <PhoneConnectLink environmentId={environmentId} />
934 + </PhoneStep>
935 + </ol>
936 + {/* One code for both stores: the link opens the store that matches the phone. */}
937 + <div className="shrink-0 rounded-lg bg-white p-1.5">
938 + <QRCodeSvg
939 + value={MOBILE_APP_URL}
940 + size={124}
941 + level="M"
942 + marginSize={2}
943 + title="T3 Code app for iPhone and Android"
944 + />
945 + </div>
946 + </div>
947 + </CollapsiblePanel>
948 + </Collapsible>
949 + </WelcomeSection>
950 + );
951 +}
952 +
953 +function PhoneStep({ step, children }: { readonly step: number; readonly children: ReactNode }) {
954 + return (
955 + <li className="flex gap-3">
956 + <span className="w-3 shrink-0 text-sm text-muted-foreground tabular-nums">{step}</span>
957 + <div className="flex min-w-0 flex-col items-start gap-2">{children}</div>
958 + </li>
959 + );
960 +}
961 +
962 +function PhoneConnectLink({ environmentId }: { readonly environmentId: EnvironmentId }) {
963 + const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
964 + const { openAuthPrompt } = useT3ConnectAuthPrompt();
965 + const linkState = useCloudLinkState(environmentId);
966 + const refreshLinkState = useEffectEvent(linkState.refresh);
967 + // The server rechecks the tunnel every 30 s; read its latest result while this panel is open.
968 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- 30 s interval that refreshes the cloud link reachability while mounted
969 + useEffect(() => {
970 + const interval = window.setInterval(() => refreshLinkState(), 30_000);
971 + return () => window.clearInterval(interval);
972 + }, []);
973 + const link = linkState.data;
974 + // The phone reaches this computer through its tunnel; older servers leave that flag out.
975 + const shared =
976 + link !== null &&
977 + link.linked &&
978 + link.linkRevoked !== true &&
979 + link.cloudUserId === userId &&
980 + link.managedTunnelActive !== false;
981 + // The server checks the tunnel on its own; until it has, the result is unknown.
982 + const reachability = shared ? link.reachability?.status : undefined;
983 + const settingsLink = (label: string) => (
984 + <Button variant="outline" size="xs" render={<Link to="/settings/access" />}>
985 + {label}
986 + </Button>
987 + );
988 + if (isSignedIn && link === null && linkState.isPending) {
989 + return <p className="text-sm text-muted-foreground">Checking T3 Connect…</p>;
990 + }
991 + if (isSignedIn && linkState.error !== null) {
992 + return (
993 + <>
994 + <p className="text-sm text-foreground">Could not check T3 Connect.</p>
995 + {settingsLink("Check T3 Connect")}
996 + </>
997 + );
998 + }
999 + if (isSignedIn && reachability === "reachable") {
1000 + return (
1001 + <p className="flex gap-1.5 text-sm text-foreground">
1002 + <CheckIcon className="mt-0.5 size-4 shrink-0 text-success-foreground" />
1003 + Your phone can reach this computer. Sign in to the app with the same account.
1004 + </p>
1005 + );
1006 + }
1007 + if (isSignedIn && shared && reachability === undefined) {
1008 + return (
1009 + <p className="text-sm text-foreground">
1010 + T3 Connect is on for this computer. Sign in to the app with the same account.
1011 + </p>
1012 + );
1013 + }
1014 + if (isSignedIn) {
1015 + // Signing in alone does not share this computer, for example after "Not now".
1016 + return (
1017 + <>
1018 + <p className="text-sm text-foreground">
1019 + {shared
1020 + ? "T3 Connect is on, but the app cannot reach this computer."
1021 + : "Signed in. Share this computer so the app can reach it."}
1022 + </p>
1023 + {settingsLink(shared ? "Check T3 Connect" : "Set up T3 Connect")}
1024 + </>
1025 + );
1026 + }
1027 + return (
1028 + <>
1029 + <p className="text-sm text-foreground">
1030 + Sign in to T3 Connect here, then in the app with the same account.
1031 + </p>
1032 + <Button variant="outline" size="xs" disabled={!isLoaded} onClick={openAuthPrompt}>
1033 + Sign in to T3 Connect
1034 + </Button>
1035 + </>
1036 + );
1037 +}
1038 +
1039 +// The ChatGPT card and the CLI card stay one card, so either choice can be undone here.
1040 +function OnboardingCodexSetup({
1041 + environmentId,
1042 + provider,
1043 + serverConfig,
1044 + onUseCliChange,
1045 +}: {
1046 + readonly environmentId: EnvironmentId;
1047 + readonly provider: ServerProvider;
1048 + readonly serverConfig: ServerConfig;
1049 + // True asks for the CLI's install or sign-in terminal once Codex has checked the CLI.
1050 + readonly onUseCliChange: (useCli: boolean) => void;
1051 +}) {
1052 + const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
1053 + const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
1054 + const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId);
1055 + const instanceId = provider.instanceId;
1056 + const instance = serverConfig.settings.providerInstances[instanceId] ?? {
1057 + driver: provider.driver,
1058 + config: {},
1059 + };
1060 + const config =
1061 + instance.config !== null && typeof instance.config === "object" ? instance.config : {};
1062 + const mode = readCodexSetupMode(config);
1063 + const changeMode = (setupMode: "managed" | "existing") => {
1064 + // "Use existing CLI" also opens a terminal to install or sign in to the CLI.
1065 + onUseCliChange(setupMode === "existing");
1066 + const unchanged = mode === setupMode && provider.enabled;
1067 + if (unchanged || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
1068 + // One-instance upsert keeps a provider another client added in the meantime.
1069 + void persistProviderInstance({
1070 + operation: "upsert",
1071 + instanceId,
1072 + instance: { ...instance, enabled: true, config: { ...config, enabled: true, setupMode } },
1073 + }).then((result) => {
1074 + if (result._tag === "Failure") {
1075 + onUseCliChange(false);
1076 + if (!isAtomCommandInterrupted(result)) {
1077 + const cause = squashAtomCommandFailure(result);
1078 + toastManager.add({
1079 + type: "error",
1080 + title: "Could not save Codex setup",
1081 + ...(cause instanceof Error ? { description: cause.message } : {}),
1082 + });
1083 + }
1084 + }
1085 + });
1086 + };
1087 + return (
1088 + <CodexSetupSection
1089 + presentation="onboarding"
1090 + environmentId={environmentId}
1091 + instanceId={instanceId}
1092 + provider={provider}
1093 + mode={mode}
1094 + enabled={provider.enabled}
1095 + readOnly={!canManageProviders}
1096 + existingCliDisabled={!canOperateTerminal}
1097 + displayName={agentName(provider)}
1098 + onModeChange={changeMode}
1099 + />
1100 + );
1101 +}
1102 +
1103 +function TerminalAction({
1104 + name,
1105 + signIn,
1106 + disabled,
1107 + onClick,
1108 +}: {
1109 + readonly name: string;
1110 + readonly signIn: boolean;
1111 + readonly disabled: boolean;
1112 + readonly onClick: () => void;
1113 +}) {
1114 + const label = signIn ? "Sign in" : "Install";
1115 + return (
1116 + <Button
1117 + size="xs"
1118 + variant="outline"
1119 + aria-label={`${label}: ${name}`}
1120 + disabled={disabled}
1121 + onClick={onClick}
1122 + >
1123 + <TerminalIcon className="size-3.5" />
1124 + {label}
1125 + </Button>
1126 + );
1127 +}
1128 +
1129 +function AgentRow({
1130 + provider,
1131 + state,
1132 + action,
1133 + compact = false,
1134 +}: {
1135 + readonly provider: ServerProvider;
1136 + readonly state: ReturnType<typeof welcomeAgentState>;
1137 + readonly action?: ReactNode;
1138 + // A row in the "Add more agents" grid: the button carries the state, so no detail line.
1139 + readonly compact?: boolean;
1140 +}) {
1141 + const name = agentName(provider);
1142 + // Claude Code and Codex tiles show Install or Set up; other agents that are on say why not.
1143 + const brokenMessage = isBrokenVersion(provider)
1144 + ? (provider.compatibilityAdvisory?.message ?? null)
1145 + : null;
1146 + const detail =
1147 + state === "install"
1148 + ? isInstallableDriver(provider.driver)
1149 + ? null
1150 + : "Not installed"
1151 + : compact || state === "ready" || state === "checking"
1152 + ? null
1153 + : state === "attention"
1154 + ? (provider.unavailableReason ??
1155 + brokenMessage ??
1156 + provider.message ??
1157 + getProviderSummary(provider).headline)
1158 + : (brokenMessage ?? getProviderSummary(provider).headline);
1159 + return (
1160 + <div className={cn("flex items-center gap-3", compact ? "min-h-9" : "min-h-10 py-1")}>
1161 + <RowIcon>
1162 + <ProviderInstanceIcon
1163 + driverKind={provider.driver}
1164 + displayName={name}
1165 + iconClassName={compact ? "size-4" : "size-[18px]"}
1166 + />
1167 + </RowIcon>
1168 + <div className="min-w-0 flex-1">
1169 + <span className={cn("block truncate text-sm text-foreground", !compact && "font-medium")}>
1170 + {name}
1171 + </span>
1172 + {detail ? (
1173 + <p className="line-clamp-2 text-xs leading-relaxed break-words text-muted-foreground">
1174 + {detail}
1175 + </p>
1176 + ) : null}
1177 + </div>
1178 + <div className="shrink-0">
1179 + {state === "ready" ? (
1180 + <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground">
1181 + <CheckIcon className="size-3.5" />
1182 + Ready
1183 + </span>
1184 + ) : state === "checking" ? (
1185 + <span className="text-xs text-muted-foreground">Checking…</span>
1186 + ) : (
1187 + action
1188 + )}
1189 + </div>
1190 + </div>
1191 + );
1192 +}
1193 +
1194 +function AgentInstallTerminal({
1195 + session,
1196 + onClose,
1197 +}: {
1198 + readonly session: AgentTerminalSession;
1199 + readonly onClose: () => void;
1200 +}) {
1201 + const { command, cwd, driver, environmentId, keybindings, providerInstanceId } = session;
1202 + const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
1203 + const [advancedTypography] = useLocalStorage(
1204 + TYPOGRAPHY_ADVANCED_STORAGE_KEY,
1205 + false,
1206 + Schema.Boolean,
1207 + );
1208 + const openTerminal = useAtomCommand(terminalEnvironment.open, { reportFailure: false });
1209 + const writeTerminal = useAtomCommand(terminalEnvironment.write, { reportFailure: false });
1210 + const closeTerminal = useAtomCommand(terminalEnvironment.close, { reportFailure: false });
1211 + const setupQueueRef = useRef(Promise.resolve());
1212 + const setupGenerationRef = useRef(0);
1213 + const activeSetupGenerationRef = useRef<number | null>(null);
1214 + const [terminalId] = useState(() => `onboarding-${driver}-${randomUUID()}`);
1215 + const threadRef = scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID);
1216 + const [setupAttempt, setSetupAttempt] = useState(0);
1217 + const [setupState, setSetupState] = useState<
1218 + "preparing" | "ready" | "openFailed" | "writeFailed"
1219 + >("preparing");
1220 + const terminalReady = setupState === "ready" || setupState === "writeFailed";
1221 +
1222 + // StrictMode can finish a cancelled open after replacement setup; it must not close or pre-type into that
1223 + // session.
1224 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the setup PTY, types the command into it, and closes it on cleanup
1225 + useEffect(() => {
1226 + const generation = setupGenerationRef.current + 1;
1227 + setupGenerationRef.current = generation;
1228 + activeSetupGenerationRef.current = generation;
1229 + // oxlint-disable-next-line react/set-state-in-effect -- A retry or a new command reopens the terminal, which shows as preparing until the open settles.
1230 + setSetupState("preparing");
1231 +
1232 + setupQueueRef.current = setupQueueRef.current.then(async () => {
1233 + if (activeSetupGenerationRef.current !== generation) return;
1234 + if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
1235 + setSetupState("openFailed");
1236 + return;
1237 + }
1238 + const opened = await openTerminal({
1239 + environmentId,
1240 + input: {
1241 + threadId: AGENT_ONBOARDING_THREAD_ID,
1242 + terminalId,
1243 + cwd,
1244 + providerInstanceId,
1245 + },
1246 + });
1247 + if (opened._tag !== "Success") {
1248 + if (activeSetupGenerationRef.current === generation) setSetupState("openFailed");
1249 + return;
1250 + }
1251 +
1252 + if (activeSetupGenerationRef.current !== generation) return;
1253 + if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
1254 + setSetupState("writeFailed");
1255 + return;
1256 + }
1257 +
1258 + const wrote = await writeTerminal({
1259 + environmentId,
1260 + input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, data: command },
1261 + });
1262 + if (activeSetupGenerationRef.current !== generation) return;
1263 + setSetupState(wrote._tag === "Success" ? "ready" : "writeFailed");
1264 + });
1265 +
1266 + // Revocation leaves the PTY running; close only while terminal access remains.
1267 + return () => {
1268 + if (activeSetupGenerationRef.current === generation) {
1269 + activeSetupGenerationRef.current = null;
1270 + }
1271 + setupQueueRef.current = setupQueueRef.current.then(async () => {
1272 + if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) return;
1273 + await closeTerminal({
1274 + environmentId,
1275 + input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, deleteHistory: true },
1276 + });
1277 + });
1278 + };
1279 + }, [
1280 + closeTerminal,
1281 + command,
1282 + cwd,
1283 + environmentId,
1284 + openTerminal,
1285 + providerInstanceId,
1286 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry bumps setupAttempt to open the terminal again.
1287 + setupAttempt,
1288 + terminalId,
1289 + writeTerminal,
1290 + ]);
1291 +
1292 + return (
1293 + <div
1294 + data-thread-terminal-drawer
1295 + className="mt-4 overflow-hidden rounded-lg border border-border/70 bg-background text-foreground"
1296 + >
1297 + <div className="flex items-center justify-between border-b border-border/60 bg-background/60 px-3 py-1.5">
1298 + <span className="text-2xs font-medium text-muted-foreground">
1299 + {!canOperateTerminal ? (
1300 + "This connection cannot control terminals."
1301 + ) : setupState === "writeFailed" ? (
1302 + <>
1303 + Run <code className="rounded bg-muted px-1 font-mono">{command}</code> in this
1304 + terminal.
1305 + </>
1306 + ) : setupState === "ready" ? (
1307 + "Review the command, then press Enter to run it."
1308 + ) : setupState === "openFailed" ? (
1309 + "Could not open the setup terminal."
1310 + ) : (
1311 + "Preparing command..."
1312 + )}
1313 + </span>
1314 + <div className="flex items-center gap-1">
1315 + {setupState === "openFailed" ? (
1316 + <Button
1317 + size="xs"
1318 + variant="ghost"
1319 + disabled={!canOperateTerminal}
1320 + onClick={() => {
1321 + if (readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
1322 + setSetupAttempt((value) => value + 1);
1323 + }
1324 + }}
1325 + >
1326 + Retry
1327 + </Button>
1328 + ) : null}
1329 + <Button size="xs" variant="ghost-muted" onClick={onClose}>
1330 + Close
1331 + </Button>
1332 + </div>
1333 + </div>
1334 + <div className="h-64">
1335 + {terminalReady ? (
1336 + <TerminalViewport
1337 + threadRef={threadRef}
1338 + threadId={AGENT_ONBOARDING_THREAD_ID}
1339 + terminalId={terminalId}
1340 + terminalLabel={`Install ${driver}`}
1341 + cwd={cwd}
1342 + providerInstanceId={providerInstanceId}
1343 + advancedTypography={advancedTypography}
1344 + onSessionExited={onClose}
1345 + autoFocus
1346 + visible
1347 + keybindings={keybindings}
1348 + />
1349 + ) : null}
1350 + </div>
1351 + </div>
1352 + );
1353 +}
1354 +
1355 +const IMPORT_PERMISSION_MESSAGE = "This connection cannot import projects or thread history.";
1356 +
1357 +// Creates the selected projects, then imports each one's agent history. Owns retry state so a
1358 +// second Start resumes instead of recreating projects.
1359 +function useProjectImport({
1360 + scans,
1361 + importSelection,
1362 + onImportSelectionChange,
1363 + isImporting,
1364 + setIsImporting,
1365 + holdPageRef,
1366 + onDone,
1367 +}: {
1368 + readonly scans: ReturnType<typeof useProjectScans>;
1369 + readonly importSelection: WelcomeImportSelection | null;
1370 + readonly onImportSelectionChange: (next: WelcomeImportSelection) => void;
1371 + readonly isImporting: boolean;
1372 + readonly setIsImporting: (value: boolean) => void;
1373 + // Blocks leaving the page; onDone releases it before landing.
1374 + readonly holdPageRef: { current: boolean };
1375 + readonly onDone: (
1376 + projectRef?: ScopedProjectRef,
1377 + importWarning?: string,
1378 + importedThreadCount?: number,
1379 + ) => Promise<boolean>;
1380 +}) {
1381 + const writableEnvironments = useEnvironmentsWithScope(scans, AuthOrchestrationOperateScope);
1382 + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
1383 + const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false });
1384 + const importWarningRef = useRef("");
1385 + // Per project, so a retry that skips finished projects still counts their threads.
1386 + const importedThreadsRef = useRef(new Map<string, number>());
1387 + const importedProjectsRef = useRef(new Map<string, ScopedProjectRef>());
1388 + const projectsWithImportedHistoryRef = useRef(new Map<string, ScopedProjectRef>());
1389 + const lastImportSelectionRef = useRef<ReadonlyArray<string>>([]);
1390 + const projectAttemptsRef = useRef(
1391 + new Map<string, { readonly projectId: ProjectId; readonly commandId: CommandId }>(),
1392 + );
1393 + const importGenerationRef = useRef(0);
1394 +
1395 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- bumps the import generation on mount and unmount so in-flight imports drop stale results
1396 + useEffect(() => {
1397 + importGenerationRef.current += 1;
1398 + return () => {
1399 + importGenerationRef.current += 1;
1400 + };
1401 + }, []);
1402 +
1403 + const { available: candidates, recent: recentActive } = partitionOnboardingProjects(
1404 + scans.flatMap((scan) =>
1405 + (scan.data?.candidates ?? []).map((candidate) => ({
1406 + ...candidate,
1407 + environmentId: scan.environmentId,
1408 + key: onboardingProjectKey(scan.environmentId, candidate.path),
1409 + })),
1410 + ),
1411 + );
1412 + // Projects already in T3 Code stay in the list, but reopening the page does not import their
1413 + // history again unless the user picks them. The scan can be 30 s old, so the live list decides.
1414 + const projects = useProjects();
1415 + const isNewProject = isNewOnboardingProject(projects);
1416 + const isNew = (candidate: ImportCandidate) => isNewProject(candidate.environmentId, candidate);
1417 + const recent = recentActive.filter(isNew);
1418 + const recentKeys = new Set(recent.map((candidate) => candidate.key));
1419 + const knownKeys = new Set(importSelection?.knownKeys);
1420 + const pickedKeys = new Set(importSelection?.keys);
1421 + const selected = importSelection?.optedOut
1422 + ? []
1423 + : candidates.filter((candidate) =>
1424 + knownKeys.has(candidate.key)
1425 + ? pickedKeys.has(candidate.key)
1426 + : recentKeys.has(candidate.key),
1427 + );
1428 + const selectedKeys = new Set(selected.map((candidate) => candidate.key));
1429 + const setSelectedKeys = (keys: ReadonlySet<string>, { optedOut = false } = {}) =>
1430 + onImportSelectionChange({
1431 + knownKeys: candidates.map((candidate) => candidate.key),
1432 + keys: [...keys],
1433 + optedOut,
1434 + });
1435 +
1436 + const canWrite = scans.every((scan) => writableEnvironments.has(scan.environmentId));
1437 + const canImport = selected.every((candidate) =>
1438 + writableEnvironments.has(candidate.environmentId),
1439 + );
1440 + const visibleImportError = canWrite && canImport ? "" : IMPORT_PERMISSION_MESSAGE;
1441 +
1442 + const importedThreadTotal = () =>
1443 + lastImportSelectionRef.current.reduce(
1444 + (total, key) => total + (importedThreadsRef.current.get(key) ?? 0),
1445 + 0,
1446 + );
1447 +
1448 + const finishAfterImport = () => {
1449 + const projectRef = resolveOnboardingLandingProject(
1450 + lastImportSelectionRef.current,
1451 + projectsWithImportedHistoryRef.current,
1452 + importedProjectsRef.current,
1453 + );
1454 + // Busy until setup is saved, so Start cannot run the import again meanwhile.
1455 + setIsImporting(true);
1456 + if (projectRef === undefined) {
1457 + void onDone(undefined, importWarningRef.current, importedThreadTotal()).then((completed) => {
1458 + if (!completed) setIsImporting(false);
1459 + });
1460 + return;
1461 + }
1462 + holdPageRef.current = true;
1463 + const importGeneration = importGenerationRef.current;
1464 + // waitForProject gives up after its timeout, so a project that never reaches the client
1465 + // still finishes setup, just without landing in it.
1466 + void waitForProject(projectRef)
1467 + .then(
1468 + () => projectRef,
1469 + () => undefined,
1470 + )
1471 + .then(async (landing) => {
1472 + if (importGeneration !== importGenerationRef.current) {
1473 + holdPageRef.current = false;
1474 + return;
1475 + }
1476 + const completed = await onDone(landing, importWarningRef.current, importedThreadTotal());
1477 + if (!completed) setIsImporting(false);
1478 + });
1479 + };
1480 +
1481 + const runImport = async (selection: typeof candidates) => {
1482 + if (isImporting) return;
1483 + const hasAccess = () =>
1484 + selection.every((candidate) =>
1485 + readEnvironmentScope(candidate.environmentId, AuthOrchestrationOperateScope),
1486 + );
1487 + // The permission message shows from the session's scopes.
1488 + const stopForDeniedAccess = () => setIsImporting(false);
1489 + if (!hasAccess()) {
1490 + stopForDeniedAccess();
1491 + return;
1492 + }
1493 + setIsImporting(true);
1494 + importWarningRef.current = "";
1495 + lastImportSelectionRef.current = selection.map((candidate) => candidate.key);
1496 + const importGeneration = importGenerationRef.current;
1497 + const importedThreads = importedThreadsRef.current;
1498 + const importedProjects = importedProjectsRef.current;
1499 + const projectAttempts = projectAttemptsRef.current;
1500 + let importedProjectsCount =
1501 + importedProjects.size > 0
1502 + ? selection.filter((candidate) => importedProjects.has(candidate.key)).length
1503 + : 0;
1504 + let skippedThreadCount = 0;
1505 + const refreshEnvironments = new Set<EnvironmentId>();
1506 + // Resolves false when the run stopped early: a newer run, an unmount, or lost access.
1507 + const importEach = async () => {
1508 + for (const candidate of selection) {
1509 + const { environmentId } = candidate;
1510 + if (importGeneration !== importGenerationRef.current) return false;
1511 + if (!hasAccess()) {
1512 + stopForDeniedAccess();
1513 + return false;
1514 + }
1515 + if (importedProjects.has(candidate.key)) continue;
1516 + let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate);
1517 + if (projectId === null) {
1518 + let attempt = projectAttempts.get(candidate.key);
1519 + if (attempt === undefined) {
1520 + const nextProjectId = newProjectId();
1521 + attempt = {
1522 + projectId: nextProjectId,
1523 + commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`),
1524 + };
1525 + projectAttempts.set(candidate.key, attempt);
1526 + }
1527 + projectId = attempt.projectId;
1528 + const result = await createProject({
1529 + environmentId,
1530 + input: {
1531 + projectId,
1532 + commandId: attempt.commandId,
1533 + title: candidate.title,
1534 + workspaceRoot: candidate.path,
1535 + createWorkspaceRootIfMissing: false,
1536 + defaultModelSelection: null,
1537 + },
1538 + });
1539 + if (importGeneration !== importGenerationRef.current) return false;
1540 + if (result._tag !== "Success") {
1541 + if (!isAtomCommandInterrupted(result)) {
1542 + projectAttempts.delete(candidate.key);
1543 + refreshEnvironments.add(environmentId);
1544 + }
1545 + continue;
1546 + }
1547 + }
1548 +
1549 + if (!hasAccess()) {
1550 + stopForDeniedAccess();
1551 + return false;
1552 + }
1553 + const threadImportResult = await importThreads({
1554 + environmentId,
1555 + input: { projectId, expectedWorkspaceRoot: candidate.path },
1556 + });
1557 + if (importGeneration !== importGenerationRef.current) return false;
1558 + if (threadImportResult._tag === "Success") {
1559 + importedThreads.set(
1560 + candidate.key,
1561 + (importedThreads.get(candidate.key) ?? 0) + threadImportResult.value.importedCount,
1562 + );
1563 + skippedThreadCount += threadImportResult.value.skippedCount;
1564 + if (threadImportResult.value.importedCount > 0) {
1565 + projectsWithImportedHistoryRef.current.set(
1566 + candidate.key,
1567 + scopeProjectRef(environmentId, projectId),
1568 + );
1569 + }
1570 + if (threadImportResult.value.skippedCount === 0) {
1571 + importedProjectsCount += 1;
1572 + importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId));
1573 + }
1574 + } else if (!isAtomCommandInterrupted(threadImportResult)) {
1575 + projectAttempts.delete(candidate.key);
1576 + refreshEnvironments.add(environmentId);
1577 + }
1578 + }
1579 + return true;
1580 + };
1581 + holdPageRef.current = true;
1582 + const completed = await importEach().finally(() => {
1583 + holdPageRef.current = false;
1584 + });
1585 + if (!completed) return;
1586 + for (const scan of scans) {
1587 + if (refreshEnvironments.has(scan.environmentId)) scan.refresh();
1588 + }
1589 + setIsImporting(false);
1590 + const importedThreadCount = importedThreadTotal();
1591 + if (importedProjectsCount < selection.length) {
1592 + if (importedThreadCount > 0 && skippedThreadCount > 0) {
1593 + importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedThreadCount} ${skippedThreadCount === 1 ? "thread" : "threads"} could not be imported.`;
1594 + } else if (skippedThreadCount > 0) {
1595 + importWarningRef.current = `${skippedThreadCount} ${skippedThreadCount === 1 ? "thread could" : "threads could"} not be imported.`;
1596 + } else if (importedThreadCount > 0) {
1597 + importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`;
1598 + } else {
1599 + importWarningRef.current = "Could not import thread history.";
1600 + }
1601 + }
1602 + finishAfterImport();
1603 + };
1604 +
1605 + return {
1606 + canWrite,
1607 + candidates,
1608 + isNew,
1609 + recent,
1610 + selected,
1611 + selectedKeys,
1612 + setSelectedKeys,
1613 + visibleImportError,
1614 + runImport,
1615 + finishAfterImport,
1616 + };
1617 +}
1618 +
1619 +type ImportCandidate = AgentSessionProjectCandidate & {
1620 + readonly environmentId: EnvironmentId;
1621 + readonly key: string;
1622 +};
1623 +
1624 +function ImportCandidateList({
1625 + candidates,
1626 + selectedKeys,
1627 + onSelectionChange,
1628 +}: {
1629 + readonly candidates: ReadonlyArray<ImportCandidate>;
1630 + readonly selectedKeys: ReadonlySet<string>;
1631 + readonly onSelectionChange: (next: ReadonlySet<string>) => void;
1632 +}) {
1633 + const { repositories, other } = groupOnboardingProjects(candidates);
1634 + const setKeys = (keys: ReadonlyArray<string>, checked: boolean) => {
1635 + const next = new Set(selectedKeys);
1636 + for (const key of keys) {
1637 + if (checked) next.add(key);
1638 + else next.delete(key);
1639 + }
1640 + onSelectionChange(next);
1641 + };
1642 + const otherSelected = other.filter((candidate) => selectedKeys.has(candidate.key)).length;
1643 +
1644 + return (
1645 + <>
1646 + {repositories.map((group) => (
1647 + <ImportRepositoryGroup
1648 + key={group.key}
1649 + group={group}
1650 + selectedKeys={selectedKeys}
1651 + onToggle={setKeys}
1652 + />
1653 + ))}
1654 + {other.length > 0 ? (
1655 + <Collapsible>
1656 + <div className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40">
1657 + <Checkbox
1658 + checked={otherSelected === other.length}
1659 + indeterminate={otherSelected > 0 && otherSelected < other.length}
1660 + onCheckedChange={(checked) =>
1661 + setKeys(
1662 + other.map((candidate) => candidate.key),
1663 + checked === true,
1664 + )
1665 + }
1666 + />
1667 + <CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-1.5 text-left">
1668 + <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-panel-open:rotate-90" />
1669 + <span className="truncate text-sm text-muted-foreground">Other folders</span>
1670 + <span className="ml-auto shrink-0 text-xs text-muted-foreground tabular-nums">
1671 + {other.length} {other.length === 1 ? "folder" : "folders"}
1672 + </span>
1673 + </CollapsibleTrigger>
1674 + </div>
1675 + <CollapsiblePanel>
1676 + {other.map((candidate) => (
1677 + <ImportCandidateRow
1678 + key={candidate.key}
1679 + candidate={candidate}
1680 + path={candidate.path}
1681 + nested
1682 + checked={selectedKeys.has(candidate.key)}
1683 + onCheckedChange={(checked) => setKeys([candidate.key], checked)}
1684 + />
1685 + ))}
1686 + </CollapsiblePanel>
1687 + </Collapsible>
1688 + ) : null}
1689 + </>
1690 + );
1691 +}
1692 +
1693 +function ImportRepositoryGroup({
1694 + group,
1695 + selectedKeys,
1696 + onToggle,
1697 +}: {
1698 + readonly group: OnboardingProjectGroup<ImportCandidate>;
1699 + readonly selectedKeys: ReadonlySet<string>;
1700 + readonly onToggle: (keys: ReadonlyArray<string>, checked: boolean) => void;
1701 +}) {
1702 + const keys = group.candidates.map((candidate) => candidate.key);
1703 + const selectedCount = keys.filter((key) => selectedKeys.has(key)).length;
1704 + const single = group.candidates.length === 1;
1705 + const only = group.candidates[0];
1706 + if (single && only !== undefined) {
1707 + return (
1708 + <ImportCandidateRow
1709 + candidate={only}
1710 + label={group.label}
1711 + path={only.path}
1712 + checked={selectedKeys.has(only.key)}
1713 + onCheckedChange={(checked) => onToggle([only.key], checked)}
1714 + />
1715 + );
1716 + }
1717 + return (
1718 + <Collapsible defaultOpen>
1719 + <div className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40">
1720 + <Checkbox
1721 + checked={selectedCount === keys.length}
1722 + indeterminate={selectedCount > 0 && selectedCount < keys.length}
1723 + onCheckedChange={(checked) => onToggle(keys, checked === true)}
1724 + />
1725 + <CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-1.5 text-left">
1726 + <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-panel-open:rotate-90" />
1727 + <span className="truncate text-sm font-medium">{group.label}</span>
1728 + <ImportRowMeta
1729 + sources={[...new Set(group.candidates.flatMap((c) => c.sources))]}
1730 + threadCount={group.threadCount}
1731 + lastActiveAt={group.lastActiveAt}
1732 + />
1733 + </CollapsibleTrigger>
1734 + </div>
1735 + <CollapsiblePanel>
1736 + {group.candidates.map((candidate) => (
1737 + <ImportCandidateRow
1738 + key={candidate.key}
1739 + candidate={candidate}
1740 + path={candidate.path}
1741 + nested
1742 + checked={selectedKeys.has(candidate.key)}
1743 + onCheckedChange={(checked) => onToggle([candidate.key], checked)}
1744 + />
1745 + ))}
1746 + </CollapsiblePanel>
1747 + </Collapsible>
1748 + );
1749 +}
1750 +
1751 +function ProjectPathText({
1752 + path,
1753 + className,
1754 +}: {
1755 + readonly path: string;
1756 + readonly className?: string;
1757 +}) {
1758 + const { name, parent } = splitOnboardingProjectPath(path);
1759 + return (
1760 + <span className={cn("flex min-w-0 items-baseline font-mono", className)}>
1761 + {parent.length > 0 ? <span className="truncate">{parent}</span> : null}
1762 + <span className="max-w-full shrink-0 truncate">{name}</span>
1763 + </span>
1764 + );
1765 +}
1766 +
1767 +function ImportCandidateRow({
1768 + candidate,
1769 + label,
1770 + path,
1771 + nested = false,
1772 + checked,
1773 + onCheckedChange,
1774 +}: {
1775 + readonly candidate: ImportCandidate;
1776 + readonly label?: string;
1777 + readonly path?: string;
1778 + readonly nested?: boolean;
1779 + readonly checked: boolean;
1780 + readonly onCheckedChange: (checked: boolean) => void;
1781 +}) {
1782 + return (
1783 + <label
1784 + className={cn(
1785 + "flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40 has-disabled:cursor-default",
1786 + nested && "pl-8",
1787 + )}
1788 + >
1789 + <Checkbox checked={checked} onCheckedChange={(value) => onCheckedChange(value === true)} />
1790 + <Tooltip>
1791 + <TooltipTrigger
1792 + render={<span className="flex min-w-0 flex-1 items-baseline gap-2 truncate" />}
1793 + >
1794 + {label !== undefined ? (
1795 + <span className="truncate text-sm font-medium">{label}</span>
1796 + ) : null}
1797 + {path !== undefined ? (
1798 + <ProjectPathText
1799 + path={path}
1800 + className={label === undefined ? "text-xs" : "text-2xs text-muted-foreground"}
1801 + />
1802 + ) : null}
1803 + </TooltipTrigger>
1804 + <TooltipPopup variant="code">{candidate.path}</TooltipPopup>
1805 + </Tooltip>
1806 + <ImportRowMeta
1807 + sources={nested ? null : candidate.sources}
1808 + threadCount={candidate.threadCount}
1809 + lastActiveAt={candidate.lastActiveAt}
1810 + />
1811 + </label>
1812 + );
1813 +}
1814 +
1815 +const IMPORT_SOURCE_NAMES: Record<AgentSessionSource, string> = {
1816 + claudeAgent: "Claude Code",
1817 + codex: "Codex",
1818 + pi: "Pi",
1819 +};
1820 +const IMPORT_SOURCES_LABEL = new Intl.ListFormat("en", { type: "conjunction" }).format(
1821 + AgentSessionSource.literals.map((source) => IMPORT_SOURCE_NAMES[source]),
1822 +);
1823 +
1824 +function ImportRowMeta({
1825 + sources,
1826 + threadCount,
1827 + lastActiveAt,
1828 +}: {
1829 + readonly sources: ReadonlyArray<AgentSessionSource> | null;
1830 + readonly threadCount: number;
1831 + readonly lastActiveAt: string | null;
1832 +}) {
1833 + const relative = lastActiveAt === null ? null : formatRelativeTime(lastActiveAt);
1834 + const age = relative === null ? "" : relative.suffix === null ? "now" : relative.value;
1835 + return (
1836 + <span className="ml-auto grid shrink-0 grid-cols-[1rem_1rem_1rem_2.5rem_2.25rem] items-center gap-x-1 text-xs text-muted-foreground tabular-nums">
1837 + {AgentSessionSource.literals.map((source) => (
1838 + <span key={source} className="flex size-4 items-center justify-center">
1839 + {sources?.includes(source) ? (
1840 + <span role="img" aria-label={IMPORT_SOURCE_NAMES[source]}>
1841 + <ProviderInstanceIcon
1842 + driverKind={ProviderDriverKind.make(source)}
1843 + displayName={IMPORT_SOURCE_NAMES[source]}
1844 + iconClassName="size-3"
1845 + />
1846 + </span>
1847 + ) : null}
1848 + </span>
1849 + ))}
1850 + <span className="text-right">{threadCount}</span>
1851 + <span className="text-right whitespace-nowrap">{age}</span>
1852 + </span>
1853 + );
1854 +}
1855 +
1856 +/** The desktop app links `t3` on a fresh install; this puts its folder on PATH when it is not. */
1857 +function CliPathSetup() {
1858 + const { state, busy, run } = useDesktopCliCommand();
1859 + const setup = state?.pathSetup;
1860 + if (!setup) return null;
1861 + return (
1862 + <div className="flex min-h-10 items-center gap-3">
1863 + <RowIcon>
1864 + <TerminalIcon className="size-4" />
1865 + </RowIcon>
1866 + <p className="min-w-0 flex-1 text-sm text-muted-foreground">
1867 + {setup.added ? (
1868 + <>
1869 + Added to {setup.file}. Open a new terminal to use <code className="font-mono">t3</code>.
1870 + </>
1871 + ) : (
1872 + <>
1873 + Use <code className="font-mono">t3</code> from any terminal. Adds one line to{" "}
1874 + {setup.file}.
1875 + </>
1876 + )}
1877 + </p>
1878 + {setup.added ? null : (
1879 + <Button size="xs" variant="outline" disabled={busy} onClick={() => run("addToPath")}>
1880 + Add to PATH
1881 + </Button>
1882 + )}
1883 + </div>
1884 + );
1885 +}
apps/web/src/components/onboarding/WelcomeWizard.import.browser.test.tsx deleted
-388
@@ -1,388 +0,0 @@
1 -import { RegistryContext } from "@effect/atom-react";
2 -import {
3 - AuthOrchestrationOperateScope,
4 - AuthOrchestrationReadScope,
5 - EnvironmentId,
6 - ProjectId,
7 - type AgentSessionProjectCandidate,
8 - type AuthEnvironmentScope,
9 - type AuthSessionState,
10 -} from "@t3tools/contracts";
11 -import { AsyncResult, Atom } from "effect/reactivity";
12 -import { expect, it, vi } from "vite-plus/test";
13 -
14 -import "~/index.css";
15 -import { act, render } from "../../../test/render";
16 -
17 -type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
18 -type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
19 -type CreateProjectInput = {
20 - environmentId: EnvironmentId;
21 - input: { projectId: ProjectId; workspaceRoot: string };
22 -};
23 -const 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 -
42 -vi.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 -});
52 -vi.mock(import("../../cloud/publicConfig"), async (original) => ({
53 - ...(await original()),
54 - hasCloudPublicConfig: () => false,
55 -}));
56 -vi.mock(import("../../onboarding/firstRun"), async (original) => ({
57 - ...(await original()),
58 - completeOnboarding: state.completeOnboarding,
59 -}));
60 -vi.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 -});
76 -vi.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 -});
88 -vi.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 -});
97 -vi.mock(import("../../state/projects"), async (original) => ({
98 - ...(await original()),
99 - projectEnvironment: { create: "createProject" } as never,
100 -}));
101 -vi.mock(import("../../state/agentSessions"), async (original) => ({
102 - ...(await original()),
103 - agentSessionImport: "importThreads" as never,
104 -}));
105 -vi.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 -}));
119 -vi.mock(import("../../connection/onboarding"), async (original) => ({
120 - ...(await original()),
121 - connectPairing: "connectPairing" as never,
122 -}));
123 -vi.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 -}));
129 -vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
130 - ...(await original()),
131 - ChatGptWelcomeCoordinator: () => <></>,
132 -}));
133 -
134 -import { appAtomRegistry } from "../../rpc/atomRegistry";
135 -import { WelcomeWizard } from "./WelcomeWizard";
136 -
137 -const primaryId = EnvironmentId.make("primary");
138 -const remoteId = EnvironmentId.make("remote");
139 -const permissionMessage = "This connection cannot import projects or thread history.";
140 -
141 -function 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 - };
152 -}
153 -
154 -function sessionAtom(environmentId: EnvironmentId) {
155 - return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
156 -}
157 -
158 -function projectsAtom() {
159 - return state.projects as Atom.Writable<ReadonlyArray<Project>>;
160 -}
161 -
162 -function setGrant(environmentId: EnvironmentId, allowed: boolean) {
163 - appAtomRegistry.set(
164 - sessionAtom(environmentId),
165 - AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
166 - );
167 -}
168 -
169 -// Default selection only picks recently active projects, so pin "now".
170 -const NOW = Date.parse("2026-01-01T00:00:00.000Z");
171 -
172 -function 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 - };
181 -}
182 -
183 -function 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);
189 -}
190 -
191 -// Resolves once the project reaches the mocked projects atom; the real helper's timeout is
192 -// replaced per test with a rejection.
193 -function 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 - });
210 -}
211 -
212 -function deferred<T>() {
213 - let resolve!: (value: T) => void;
214 - const promise = new Promise<T>((complete) => {
215 - resolve = complete;
216 - });
217 - return { promise, resolve };
218 -}
219 -
220 -function pageText() {
221 - return document.body.textContent ?? "";
222 -}
223 -
224 -function 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;
230 -}
231 -
232 -async function click(label: string) {
233 - const target = button(label);
234 - expect(target.disabled).toBe(false);
235 - await act(async () => target.click());
236 -}
237 -
238 -async 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());
242 -}
243 -
244 -async 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;
259 -}
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.
263 -function 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;
293 -}
294 -
295 -it("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 -
307 -it("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 -
323 -it("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 -
350 -it("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 -
370 -it("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 -});
apps/web/src/components/onboarding/WelcomeWizard.tsx deleted
-1845
@@ -1,1845 +0,0 @@
1 -import { useAuth } from "@clerk/react";
2 -import { useAtomValue } from "@effect/atom-react";
3 -import type {
4 - AgentSessionProjectCandidate,
5 - EnvironmentId,
6 - ProjectId,
7 - ProviderInstanceId,
8 - ScopedProjectRef,
9 - ServerConfig,
10 - ServerProvider,
11 -} from "@t3tools/contracts";
12 -import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
13 -import {
14 - isAtomCommandInterrupted,
15 - squashAtomCommandFailure,
16 -} from "@t3tools/client-runtime/state/runtime";
17 -import {
18 - AgentSessionSource,
19 - AuthTerminalOperateScope,
20 - CommandId,
21 - defaultInstanceIdForDriver,
22 - AuthOrchestrationOperateScope,
23 - isManagedDriverAllowed,
24 - ProviderDriverKind,
25 - ThreadId,
26 -} from "@t3tools/contracts";
27 -import * as Schema from "effect/Schema";
28 -import {
29 - ArrowRightIcon,
30 - CheckIcon,
31 - ChevronRightIcon,
32 - CloudIcon,
33 - LinkIcon,
34 - MonitorIcon,
35 - TerminalIcon,
36 -} from "lucide-react";
37 -import { useEffect, useRef, useState } from "react";
38 -
39 -import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";
40 -import { useLocalStorage } from "../../hooks/useLocalStorage";
41 -import { hasCloudPublicConfig } from "../../cloud/publicConfig";
42 -import { PRIVACY_POLICY_URL } from "../../legalLinks";
43 -import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
44 -import { completeOnboarding } from "../../onboarding/firstRun";
45 -import {
46 - groupOnboardingProjects,
47 - partitionOnboardingProjects,
48 - onboardingProjectKey,
49 - resolveOnboardingLandingProject,
50 - resolveOnboardingProjectId,
51 - type OnboardingProjectGroup,
52 - splitOnboardingProjectPath,
53 -} from "../../onboarding/projectImport.logic";
54 -import {
55 - getOnboardingProviderState,
56 - resolveOnboardingProviderInstallCommand,
57 - resolveOnboardingProviderLoginCommand,
58 - selectOnboardingProvidersByDriver,
59 -} from "../../onboarding/providerReadiness.logic";
60 -import { newProjectId, randomUUID } from "../../lib/utils";
61 -import { agentSessionImport } from "../../state/agentSessions";
62 -import { readProjects, waitForProject } from "../../state/entities";
63 -import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
64 -import {
65 - managedInstanceLocks,
66 - managedTelemetryOffMessage,
67 - usePrimaryManagedPolicy,
68 -} from "../../state/managedPolicy";
69 -import {
70 - isOnboardingRelayEnvironment,
71 - resolveOnboardingSetup,
72 -} from "../../onboarding/targetEnvironment.logic";
73 -import { useProjectScans } from "../../onboarding/useProjectScans";
74 -import { projectEnvironment } from "../../state/projects";
75 -import { serverEnvironment } from "../../state/server";
76 -import {
77 - readEnvironmentScope,
78 - useEnvironmentScope,
79 - useEnvironmentsWithScope,
80 -} from "../../state/session";
81 -import { terminalEnvironment } from "../../state/terminal";
82 -import { useAtomCommand } from "../../state/use-atom-command";
83 -import { connectPairing } from "../../connection/onboarding";
84 -import { getProviderSummary } from "../settings/providerStatus";
85 -import { providerClients } from "../settings/providerDriverMeta";
86 -import { ChatGptWelcomeCoordinator } from "../settings/ChatGptWelcomeCoordinator";
87 -import { useDesktopCliCommand } from "../settings/CliCommandSettingsRow";
88 -import { AddManagedCodexAccountDialog, CodexSetupSection } from "../settings/CodexSetupSection";
89 -import { readCodexSetupMode } from "../settings/CodexSetupSection.logic";
90 -import { buildProviderInstanceUpdatePatch } from "../settings/SettingsPanels.logic";
91 -import { TerminalViewport } from "../ThreadTerminalDrawer";
92 -import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
93 -import { presentSavedCloudEnvironmentConnection } from "../cloud/cloudEnvironmentConnectionPresentation";
94 -import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
95 -import { T3Wordmark } from "../T3Wordmark";
96 -import { Alert, AlertDescription } from "../ui/alert";
97 -import { Button } from "../ui/button";
98 -import { InstallT3Commands } from "../InstallT3Commands";
99 -import { Checkbox } from "../ui/checkbox";
100 -import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
101 -import { Input } from "../ui/input";
102 -import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
103 -import { ScrollArea } from "../ui/scroll-area";
104 -import { Spinner } from "../ui/spinner";
105 -import { WizardPanel, WizardSteps, WizardPopup, WizardHeader } from "../ui/wizard";
106 -import { Dialog } from "../ui/dialog";
107 -import { toastManager } from "../ui/toast";
108 -import { cn } from "../../lib/utils";
109 -import { formatRelativeTime } from "../../timestampFormat";
110 -
111 -type WizardStep = "connection" | "agents" | "import";
112 -const NO_ENVIRONMENTS: readonly EnvironmentId[] = [];
113 -
114 -const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup");
115 -const ONBOARDING_STAGES = ["Connect", "Agents", "Projects"] as const;
116 -const SCAN_LIMIT_MESSAGE = "Scan limit reached. Some projects or conversations may be missing.";
117 -
118 -export function WelcomeWizard({
119 - localAvailable,
120 - onDone,
121 - resumeEnvironmentId,
122 -}: {
123 - readonly localAvailable: boolean;
124 - readonly resumeEnvironmentId?: EnvironmentId | undefined;
125 - readonly onDone: (projectRef?: ScopedProjectRef) => void | Promise<void>;
126 -}) {
127 - const [step, setStep] = useState<WizardStep>(resumeEnvironmentId ? "agents" : "connection");
128 - const { environments } = useEnvironments();
129 - const [selection, setSelection] = useState<ReadonlySet<EnvironmentId> | null>(null);
130 - // Share the registry for the wizard's lifetime so unchecked computers are not auto-selected again.
131 - const [autoSelectedComputers] = useState(() => new Set<EnvironmentId>());
132 - const [setupIds, setSetupIds] = useState<readonly EnvironmentId[]>(
133 - resumeEnvironmentId ? [resumeEnvironmentId] : [],
134 - );
135 - const [importSelection, setImportSelection] = useState<ImportSelection | null>(null);
136 - const [isImporting, setIsImporting] = useState(false);
137 - const finishingPromiseRef = useRef<Promise<boolean> | null>(null);
138 - const completionErrorToastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
139 - const primaryEnvironment = usePrimaryEnvironment();
140 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- marks newly listed computers in the shared auto-select registry once and selects the enabled ones
141 - useEffect(() => {
142 - const newComputers = environments.filter(
143 - (environment) => !autoSelectedComputers.has(environment.environmentId),
144 - );
145 - if (newComputers.length === 0) return;
146 - for (const environment of newComputers) {
147 - autoSelectedComputers.add(environment.environmentId);
148 - }
149 - const enabledComputers = newComputers.filter((environment) => environment.entry.enabled);
150 - if (enabledComputers.length === 0) return;
151 - // oxlint-disable-next-line react/set-state-in-effect -- The registry marks each computer once, and only after commit; render must not mutate it.
152 - setSelection(
153 - (current) =>
154 - new Set([
155 - ...(current ?? []),
156 - ...enabledComputers.map((environment) => environment.environmentId),
157 - ]),
158 - );
159 - }, [autoSelectedComputers, environments]);
160 - const selectedIds =
161 - selection ?? new Set(primaryEnvironment ? [primaryEnvironment.environmentId] : []);
162 - const scans = useProjectScans(step === "import" ? setupIds : NO_ENVIRONMENTS);
163 - const isLoadingProjects =
164 - step === "import" &&
165 - scans.every((scan) => scan.data === null) &&
166 - scans.some((scan) => scan.isPending);
167 - const startSetup = (ids: readonly EnvironmentId[]) => {
168 - if (ids.length === 0) return;
169 - setSetupIds(ids);
170 - setStep("agents");
171 - };
172 - const stageIndex = step === "agents" ? 1 : step === "import" ? 2 : 0;
173 - const finish = (
174 - projectRef?: ScopedProjectRef,
175 - importWarning?: string,
176 - importedThreadCount = 0,
177 - ) => {
178 - if (finishingPromiseRef.current !== null) return finishingPromiseRef.current;
179 - if (completionErrorToastIdRef.current !== null) {
180 - toastManager.close(completionErrorToastIdRef.current);
181 - completionErrorToastIdRef.current = null;
182 - }
183 -
184 - const completion = completeOnboarding()
185 - .then(async () => {
186 - if (completionErrorToastIdRef.current !== null) {
187 - toastManager.close(completionErrorToastIdRef.current);
188 - completionErrorToastIdRef.current = null;
189 - }
190 - await onDone(projectRef);
191 - if (importWarning) {
192 - toastManager.add({
193 - type: "warning",
194 - title: "Some history was not imported",
195 - description: importWarning,
196 - timeout: 0,
197 - });
198 - } else if (importedThreadCount > 0) {
199 - toastManager.add({
200 - type: "success",
201 - title: `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}`,
202 - });
203 - }
204 - return true;
205 - })
206 - .catch(() => {
207 - const errorToast = {
208 - type: "error",
209 - title: "Could not finish setup",
210 - description: "Your settings could not be saved. Try again.",
211 - } as const;
212 - if (completionErrorToastIdRef.current === null) {
213 - completionErrorToastIdRef.current = toastManager.add(errorToast);
214 - } else {
215 - toastManager.update(completionErrorToastIdRef.current, errorToast);
216 - }
217 - return false;
218 - })
219 - .finally(() => {
220 - if (finishingPromiseRef.current === completion) {
221 - finishingPromiseRef.current = null;
222 - }
223 - });
224 - finishingPromiseRef.current = completion;
225 - return completion;
226 - };
227 -
228 - return (
229 - <Dialog
230 - open
231 - disablePointerDismissal
232 - onOpenChange={(_, event) => {
233 - event.cancel();
234 - if (event.reason === "close-press" && !isImporting) void finish();
235 - }}
236 - >
237 - <WizardPopup
238 - size="wide"
239 - bottomStickOnMobile={false}
240 - initialFocus={() => document.getElementById("onboarding-pairing-url") ?? true}
241 - >
242 - <WizardHeader
243 - title="Set up T3 Code"
244 - identity={
245 - <div className="flex items-baseline gap-1.5" role="img" aria-label="T3 Code">
246 - <T3Wordmark className="h-4 w-auto shrink-0" aria-hidden />
247 - <span className="text-2xl font-medium tracking-tight text-muted-foreground">
248 - Code
249 - </span>
250 - </div>
251 - }
252 - >
253 - <WizardSteps
254 - steps={ONBOARDING_STAGES}
255 - currentStep={stageIndex}
256 - isStepDisabled={(index) => isImporting || index >= stageIndex}
257 - onStepChange={(index) => {
258 - if (isImporting || index > stageIndex) return;
259 - setStep(index === 0 ? "connection" : "agents");
260 - }}
261 - />
262 - </WizardHeader>
263 -
264 - <WizardPanel holdHeight={isLoadingProjects}>
265 - {step === "connection" ? (
266 - <ConnectionStep
267 - expandPairingInitially={!localAvailable && !hasCloudPublicConfig()}
268 - selectedIds={selectedIds}
269 - autoSelectedComputers={autoSelectedComputers}
270 - onSelectionChange={setSelection}
271 - onToggleEnvironment={(environmentId, checked) =>
272 - setSelection((current) => {
273 - const next = new Set(current ?? selectedIds);
274 - if (checked) next.add(environmentId);
275 - else next.delete(environmentId);
276 - return next;
277 - })
278 - }
279 - onContinue={() =>
280 - startSetup(resolveOnboardingSetup(environments, selectedIds).environmentIds)
281 - }
282 - onPaired={(environmentId) => {
283 - setSelection(new Set([...selectedIds, environmentId]));
284 - }}
285 - />
286 - ) : step === "agents" ? (
287 - <AgentsStep environmentIds={setupIds} onContinue={() => setStep("import")} />
288 - ) : (
289 - <ImportStep
290 - scans={scans}
291 - importSelection={importSelection}
292 - onImportSelectionChange={setImportSelection}
293 - isImporting={isImporting}
294 - setIsImporting={setIsImporting}
295 - onDone={finish}
296 - />
297 - )}
298 - </WizardPanel>
299 - </WizardPopup>
300 - <ChatGptWelcomeCoordinator />
301 - </Dialog>
302 - );
303 -}
304 -
305 -function ConnectionStep({
306 - autoSelectedComputers,
307 - expandPairingInitially,
308 - selectedIds,
309 - onSelectionChange,
310 - onToggleEnvironment,
311 - onContinue,
312 - onPaired,
313 -}: {
314 - readonly autoSelectedComputers: Set<EnvironmentId>;
315 - readonly expandPairingInitially: boolean;
316 - readonly selectedIds: ReadonlySet<EnvironmentId>;
317 - readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId>) => void;
318 - readonly onToggleEnvironment: (environmentId: EnvironmentId, checked: boolean) => void;
319 - readonly onContinue: () => void;
320 - readonly onPaired: (environmentId: EnvironmentId) => void;
321 -}) {
322 - const { environments } = useEnvironments();
323 - const telemetryOff = managedTelemetryOffMessage(usePrimaryManagedPolicy());
324 - const cloudEnabled = hasCloudPublicConfig();
325 - const directEnvironments = environments.filter(
326 - (environment) => !cloudEnabled || !isOnboardingRelayEnvironment(environment),
327 - );
328 - const [pairingOpen, setPairingOpen] = useState(expandPairingInitially);
329 - const [isPairing, setIsPairing] = useState(false);
330 - const { ready, skippedIds } = resolveOnboardingSetup(environments, selectedIds);
331 - const skippedLabels = environments
332 - .filter((environment) => skippedIds.includes(environment.environmentId))
333 - .map((environment) => environment.label);
334 - const continueRef = useRef<HTMLButtonElement>(null);
335 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves DOM focus to the Continue button once setup is ready and nothing else holds focus
336 - useEffect(() => {
337 - if (
338 - ready &&
339 - (document.activeElement === document.body ||
340 - document.activeElement?.getAttribute("role") === "dialog")
341 - ) {
342 - continueRef.current?.focus();
343 - }
344 - }, [ready]);
345 - return (
346 - <>
347 - <h1 className="text-2xl font-semibold tracking-tight text-foreground">
348 - Connect your computers
349 - </h1>
350 - <p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">
351 - Choose one or more computers. We’ll set up agents and projects on each.
352 - </p>
353 - {directEnvironments.length > 0 ? (
354 - <fieldset className="mt-5 space-y-2">
355 - <legend className="sr-only">Computers to set up</legend>
356 - {directEnvironments.map((environment) => (
357 - <label
358 - key={environment.environmentId}
359 - className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-3"
360 - >
361 - <Checkbox
362 - checked={selectedIds.has(environment.environmentId)}
363 - onCheckedChange={(checked) => {
364 - const next = new Set(selectedIds);
365 - if (checked) next.add(environment.environmentId);
366 - else next.delete(environment.environmentId);
367 - onSelectionChange(next);
368 - }}
369 - />
370 - <MonitorIcon className="size-4 shrink-0 text-muted-foreground" />
371 - <span className="min-w-0 flex-1">
372 - <span className="flex items-baseline justify-between gap-3">
373 - <span className="min-w-0 text-sm font-medium break-words">
374 - {environment.label}
375 - </span>
376 - <span className="shrink-0 text-xs text-muted-foreground">
377 - {!environment.entry.enabled && environment.connection.phase !== "unsupported"
378 - ? "Off"
379 - : presentSavedCloudEnvironmentConnection(environment.connection).buttonLabel}
380 - </span>
381 - </span>
382 - {environment.displayUrl ? (
383 - <span className="mt-0.5 block text-xs break-all text-muted-foreground">
384 - {environment.displayUrl}
385 - </span>
386 - ) : null}
387 - {environment.connection.phase === "unsupported" && environment.connection.error ? (
388 - <span className="mt-0.5 block text-xs text-muted-foreground">
389 - {environment.connection.error}
390 - </span>
391 - ) : null}
392 - </span>
393 - </label>
394 - ))}
395 - </fieldset>
396 - ) : null}
397 - <div className="mt-4 space-y-2">
398 - {cloudEnabled ? (
399 - <ConnectAccountOption
400 - autoSelectedComputers={autoSelectedComputers}
401 - disabled={isPairing}
402 - selectedIds={selectedIds}
403 - onToggleEnvironment={onToggleEnvironment}
404 - />
405 - ) : null}
406 - <div className="rounded-lg border border-border bg-background">
407 - <Collapsible open={pairingOpen} onOpenChange={setPairingOpen}>
408 - <CollapsibleTrigger
409 - disabled={isPairing}
410 - render={
411 - <Button
412 - variant="ghost"
413 - size="sm-multiline"
414 - className="min-h-14 w-full justify-start"
415 - />
416 - }
417 - >
418 - <LinkIcon className="size-4 text-muted-foreground" />
419 - <span className="flex-1 text-left">Add a computer</span>
420 - <ChevronRightIcon
421 - className={cn("size-4 text-muted-foreground", pairingOpen && "rotate-90")}
422 - />
423 - </CollapsibleTrigger>
424 - <CollapsiblePanel>
425 - <div className="px-3 pb-3">
426 - <PairingForm
427 - isPairing={isPairing}
428 - setIsPairing={setIsPairing}
429 - onPaired={(environmentId) => {
430 - setPairingOpen(false);
431 - onPaired(environmentId);
432 - requestAnimationFrame(() => continueRef.current?.focus());
433 - }}
434 - />
435 - </div>
436 - </CollapsiblePanel>
437 - </Collapsible>
438 - </div>
439 - </div>
440 - {skippedLabels.length > 0 ? (
441 - <p className="mt-4 text-xs text-muted-foreground">
442 - Not connected, so setup skips {skippedLabels.join(", ")}. You can set{" "}
443 - {skippedLabels.length === 1 ? "it" : "them"} up later from Settings.
444 - </p>
445 - ) : null}
446 - <div className="mt-6 flex flex-col-reverse gap-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
447 - <p className="min-w-0 text-xs leading-relaxed text-muted-foreground">
448 - {telemetryOff ?? "T3 Code collects anonymous usage data to help us improve it."} To read
449 - more about how your data is used{telemetryOff === undefined ? " and how to opt out" : ""},
450 - see our{" "}
451 - <a
452 - className="underline underline-offset-2 hover:text-foreground"
453 - href={PRIVACY_POLICY_URL}
454 - target="_blank"
455 - rel="noreferrer noopener"
456 - >
457 - privacy policy
458 - </a>
459 - .
460 - </p>
461 - <Button
462 - className="shrink-0 self-end"
463 - ref={continueRef}
464 - autoFocus={!expandPairingInitially}
465 - disabled={!ready || isPairing}
466 - onClick={onContinue}
467 - >
468 - Continue
469 - <ArrowRightIcon className="size-3.5" />
470 - </Button>
471 - </div>
472 - </>
473 - );
474 -}
475 -
476 -function ConnectAccountOption({
477 - autoSelectedComputers,
478 - disabled,
479 - selectedIds,
480 - onToggleEnvironment,
481 -}: {
482 - readonly autoSelectedComputers: Set<EnvironmentId>;
483 - readonly disabled: boolean;
484 - readonly selectedIds: ReadonlySet<EnvironmentId>;
485 - readonly onToggleEnvironment: (environmentId: EnvironmentId, checked: boolean) => void;
486 -}) {
487 - const { environments } = useEnvironments();
488 - const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
489 - const { openAuthPrompt } = useT3ConnectAuthPrompt();
490 - const [expanded, setExpanded] = useState(true);
491 - const [discoveryReady, setDiscoveryReady] = useState(false);
492 - const onDiscoveryReady = () => setDiscoveryReady(true);
493 -
494 - return (
495 - <div className="rounded-lg border border-border bg-background">
496 - <Collapsible open={expanded && !!isSignedIn && discoveryReady} onOpenChange={setExpanded}>
497 - <CollapsibleTrigger
498 - disabled={disabled || !isLoaded}
499 - onClick={(event) => {
500 - if (!isSignedIn) {
501 - event.preventDefault();
502 - setExpanded(true);
503 - openAuthPrompt();
504 - }
505 - }}
506 - render={
507 - <Button variant="ghost" size="sm-multiline" className="min-h-14 w-full justify-start" />
508 - }
509 - >
510 - <CloudIcon className="size-4 text-muted-foreground" />
511 - <span className="flex-1 text-left">T3 Connect</span>
512 - <span className="text-xs text-muted-foreground">
513 - {!isLoaded
514 - ? "Loading sign-in…"
515 - : !isSignedIn
516 - ? "Sign in"
517 - : !discoveryReady
518 - ? "Loading computers…"
519 - : null}
520 - </span>
521 - <ChevronRightIcon
522 - className={cn("size-4 text-muted-foreground", expanded && isSignedIn && "rotate-90")}
523 - />
524 - </CollapsibleTrigger>
525 - <CollapsiblePanel keepMounted>
526 - <div className="px-3 pb-3">
527 - <div className="mb-3 space-y-1.5">
528 - {isSignedIn ? (
529 - <CloudEnvironmentConnectRows
530 - primaryEnvironmentId={null}
531 - savedEnvironments={environments}
532 - showSavedEnvironments
533 - onDiscoveryReady={onDiscoveryReady}
534 - selection={{ selectedIds, onChange: onToggleEnvironment, autoSelectedComputers }}
535 - refreshWhileEmpty
536 - empty={
537 - <p className="py-3 text-sm text-muted-foreground">No computers linked yet.</p>
538 - }
539 - />
540 - ) : null}
541 - </div>
542 - <p className="text-sm text-muted-foreground">
543 - Run this on each computer you want to connect.
544 - </p>
545 - <InstallT3Commands command="t3 connect" className="mt-3" />
546 - <p className="mt-3 text-xs text-muted-foreground">
547 - Keep T3 Code running. Select the computers you want to set up above.
548 - </p>
549 - </div>
550 - </CollapsiblePanel>
551 - </Collapsible>
552 - </div>
553 - );
554 -}
555 -
556 -function PairingForm({
557 - isPairing,
558 - setIsPairing,
559 - onPaired,
560 -}: {
561 - readonly isPairing: boolean;
562 - readonly setIsPairing: (value: boolean) => void;
563 - readonly onPaired: (environmentId: EnvironmentId) => void;
564 -}) {
565 - const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false });
566 - const [pairingUrl, setPairingUrl] = useState("");
567 - const [errorMessage, setErrorMessage] = useState("");
568 - const mountedRef = useRef(true);
569 -
570 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tracks mount so a pairing request that settles after unmount does not set state
571 - useEffect(() => {
572 - mountedRef.current = true;
573 - return () => {
574 - mountedRef.current = false;
575 - };
576 - }, []);
577 -
578 - const submit = async () => {
579 - if (isPairing || pairingUrl.trim().length === 0) return;
580 - setIsPairing(true);
581 - setErrorMessage("");
582 - const result = await connectPairingEnvironment({ pairingUrl: pairingUrl.trim() });
583 - if (!mountedRef.current) return;
584 - setIsPairing(false);
585 - if (result._tag === "Success") {
586 - onPaired(result.value);
587 - return;
588 - }
589 - if (isAtomCommandInterrupted(result)) return;
590 - const cause = squashAtomCommandFailure(result);
591 - setErrorMessage(cause instanceof Error ? cause.message : "Pairing failed.");
592 - };
593 -
594 - return (
595 - <>
596 - <form
597 - className="space-y-3"
598 - onSubmit={(event) => {
599 - event.preventDefault();
600 - void submit();
601 - }}
602 - >
603 - <div>
604 - <label className="block text-sm text-muted-foreground" htmlFor="onboarding-pairing-url">
605 - Pairing link
606 - </label>
607 - <Input
608 - id="onboarding-pairing-url"
609 - autoFocus
610 - aria-invalid={errorMessage.length > 0}
611 - aria-describedby={errorMessage ? "onboarding-pairing-error" : undefined}
612 - className="mt-2"
613 - size="lg"
614 - autoCapitalize="none"
615 - autoComplete="off"
616 - autoCorrect="off"
617 - spellCheck={false}
618 - nativeInput
619 - readOnly={isPairing}
620 - placeholder="https://your-server:5230/pair#token=…"
621 - value={pairingUrl}
622 - onChange={(event) => setPairingUrl(event.currentTarget.value)}
623 - onKeyDown={(event) => {
624 - if (
625 - event.key === "Enter" &&
626 - (event.nativeEvent.isComposing || event.keyCode === 229)
627 - ) {
628 - event.preventDefault();
629 - }
630 - }}
631 - />
632 - </div>
633 - {errorMessage ? (
634 - <Alert id="onboarding-pairing-error" variant="error">
635 - <AlertDescription>{errorMessage}</AlertDescription>
636 - </Alert>
637 - ) : null}
638 - <Collapsible>
639 - <div className="flex items-center justify-between gap-3">
640 - <CollapsibleTrigger
641 - type="button"
642 - className="group flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
643 - >
644 - <ChevronRightIcon className="size-3.5 group-data-panel-open:rotate-90" />
645 - Need a pairing link?
646 - </CollapsibleTrigger>
647 - <Button type="submit" disabled={isPairing || pairingUrl.trim().length === 0}>
648 - {isPairing ? "Pairing..." : "Pair"}
649 - </Button>
650 - </div>
651 - <CollapsiblePanel>
652 - <p className="pt-3 text-sm text-muted-foreground">On the computer with your code:</p>
653 - <InstallT3Commands command="t3 pair" className="mt-2" />
654 - <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
655 - Start T3 Code or run <code className="font-mono">t3 serve</code> there before{" "}
656 - <code className="font-mono">t3 pair</code>. On a tailnet, run{" "}
657 - <code className="font-mono">t3 pair --tailscale</code> instead.
658 - </p>
659 - </CollapsiblePanel>
660 - </Collapsible>
661 - </form>
662 - </>
663 - );
664 -}
665 -
666 -const PRIMARY_AGENT_DRIVERS = ["codex", "claudeAgent"] as const;
667 -type OnboardingAgentDriver = (typeof PRIMARY_AGENT_DRIVERS)[number];
668 -
669 -interface AgentTerminalSession {
670 - readonly environmentId: EnvironmentId;
671 - readonly driver: OnboardingAgentDriver;
672 - readonly providerInstanceId: ServerProvider["instanceId"];
673 - readonly cwd: string;
674 - readonly command: string;
675 - readonly keybindings: ServerConfig["keybindings"];
676 -}
677 -
678 -function AgentsStep({
679 - environmentIds,
680 - onContinue,
681 -}: {
682 - readonly environmentIds: readonly EnvironmentId[];
683 - readonly onContinue: () => void;
684 -}) {
685 - const { environments } = useEnvironments();
686 - return (
687 - <StepShell
688 - title="Connect your agents"
689 - description="Choose an agent to start coding. You can add more later."
690 - >
691 - <ScrollArea scrollFade className="mt-5 h-auto max-h-[min(32rem,55dvh)]">
692 - <div className="space-y-5 pr-3">
693 - {environmentIds.map((environmentId) => (
694 - <ConnectedAgentsStep
695 - key={environmentId}
696 - environmentId={environmentId}
697 - machineLabel={
698 - environments.find((environment) => environment.environmentId === environmentId)
699 - ?.label ?? "Computer"
700 - }
701 - />
702 - ))}
703 - </div>
704 - </ScrollArea>
705 - <CliPathSetup />
706 - <div className="mt-6 flex justify-end">
707 - <Button autoFocus onClick={onContinue}>
708 - Continue
709 - <ArrowRightIcon className="size-3.5" />
710 - </Button>
711 - </div>
712 - </StepShell>
713 - );
714 -}
715 -
716 -function ConnectedAgentsStep({
717 - environmentId,
718 - machineLabel,
719 -}: {
720 - readonly environmentId: EnvironmentId;
721 - readonly machineLabel: string;
722 -}) {
723 - const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));
724 - const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
725 - reportFailure: false,
726 - });
727 - const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
728 - const [terminalSession, setTerminalSession] = useState<AgentTerminalSession | null>(null);
729 - const [addingAccount, setAddingAccount] = useState(false);
730 - const [createdAccount, setCreatedAccount] = useState<{
731 - instanceId: ProviderInstanceId;
732 - displayName: string;
733 - autoStart: boolean;
734 - } | null>(null);
735 - const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
736 -
737 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the environment to refresh its provider list when the environment changes
738 - useEffect(() => {
739 - void refreshProviders({ environmentId, input: {} });
740 - }, [environmentId, refreshProviders]);
741 -
742 - const byDriver = selectOnboardingProvidersByDriver(providers);
743 - const managedPolicy = serverConfig?.managedPolicy;
744 - // A policy that owns Codex's launch settings also rules out ChatGPT's own runtime.
745 - const chatGptAllowed =
746 - managedInstanceLocks(managedPolicy, ProviderDriverKind.make("codex"))?.configKeys.has(
747 - "setupMode",
748 - ) !== true;
749 -
750 - const primaryAgents = PRIMARY_AGENT_DRIVERS.filter((driver) =>
751 - isManagedDriverAllowed(managedPolicy, ProviderDriverKind.make(driver)),
752 - ).flatMap((driver) => {
753 - const instances =
754 - driver === "codex" ? providers?.filter((provider) => provider.driver === driver) : undefined;
755 - return instances?.length
756 - ? instances.map((provider) => ({ driver, provider, instanceId: provider.instanceId }))
757 - : [{ driver, provider: byDriver.get(driver), instanceId: byDriver.get(driver)?.instanceId }];
758 - });
759 - if (createdAccount) {
760 - const index = primaryAgents.findIndex(
761 - (agent) => agent.instanceId === createdAccount.instanceId,
762 - );
763 - const [existing] = index >= 0 ? primaryAgents.splice(index, 1) : [];
764 - primaryAgents.unshift(
765 - existing ?? {
766 - driver: "codex",
767 - provider: undefined,
768 - instanceId: createdAccount.instanceId,
769 - },
770 - );
771 - }
772 - return (
773 - <section>
774 - <h2 className="mb-2 text-sm font-medium">{machineLabel}</h2>
775 - {!canOperateTerminal ? (
776 - <p className="mb-2 text-sm text-muted-foreground">
777 - This connection cannot control terminals.
778 - </p>
779 - ) : null}
780 - <div className="space-y-1.5">
781 - {primaryAgents.map(({ driver, provider, instanceId }) =>
782 - driver === "codex" && serverConfig !== null ? (
783 - <OnboardingCodexSetup
784 - key={instanceId ?? driver}
785 - environmentId={environmentId}
786 - provider={provider}
787 - serverConfig={serverConfig}
788 - createdAccount={instanceId === createdAccount?.instanceId ? createdAccount : null}
789 - onAutoStartConsumed={() =>
790 - setCreatedAccount((account) => (account ? { ...account, autoStart: false } : null))
791 - }
792 - terminalOpen={terminalSession?.driver === driver}
793 - onOpenTerminal={() => {
794 - if (
795 - provider === undefined ||
796 - !readEnvironmentScope(environmentId, AuthTerminalOperateScope)
797 - )
798 - return;
799 - setTerminalSession({
800 - environmentId,
801 - driver,
802 - providerInstanceId: provider.instanceId,
803 - cwd: serverConfig.cwd,
804 - command: provider.installed
805 - ? resolveOnboardingProviderLoginCommand(
806 - provider,
807 - serverConfig.settings,
808 - serverConfig.environment.platform.os,
809 - )
810 - : resolveOnboardingProviderInstallCommand(
811 - driver,
812 - serverConfig.environment.platform.os,
813 - ),
814 - keybindings: serverConfig.keybindings,
815 - });
816 - }}
817 - />
818 - ) : (
819 - <AgentCard
820 - key={driver}
821 - driver={driver}
822 - provider={provider}
823 - terminalOpen={terminalSession?.driver === driver}
824 - terminalAvailable={serverConfig !== null && canOperateTerminal}
825 - onOpenTerminal={() => {
826 - if (
827 - provider === undefined ||
828 - serverConfig === null ||
829 - !readEnvironmentScope(environmentId, AuthTerminalOperateScope)
830 - )
831 - return;
832 - setTerminalSession({
833 - environmentId,
834 - driver,
835 - providerInstanceId: provider.instanceId,
836 - cwd: serverConfig.cwd,
837 - command: provider.installed
838 - ? resolveOnboardingProviderLoginCommand(
839 - provider,
840 - serverConfig.settings,
841 - serverConfig.environment.platform.os,
842 - )
843 - : resolveOnboardingProviderInstallCommand(
844 - driver,
845 - serverConfig.environment.platform.os,
846 - ),
847 - keybindings: serverConfig.keybindings,
848 - });
849 - }}
850 - />
851 - ),
852 - )}
853 - </div>
854 - {chatGptAllowed &&
855 - providers?.some(
856 - (provider) =>
857 - provider.driver === "codex" && getOnboardingProviderState(provider) === "ready",
858 - ) ? (
859 - <div className="mt-3">
860 - <Button size="xs" variant="ghost-muted" onClick={() => setAddingAccount(true)}>
861 - Connect another ChatGPT account
862 - </Button>
863 - </div>
864 - ) : null}
865 - {addingAccount ? (
866 - <AddManagedCodexAccountDialog
867 - environmentId={environmentId}
868 - onClose={() => setAddingAccount(false)}
869 - onAccountCreated={(instanceId, displayName) =>
870 - setCreatedAccount({ instanceId, displayName, autoStart: true })
871 - }
872 - />
873 - ) : null}
874 - {terminalSession !== null ? (
875 - <AgentInstallTerminal
876 - key={`${terminalSession.environmentId}:${terminalSession.providerInstanceId}:${terminalSession.driver}`}
877 - session={terminalSession}
878 - onClose={() => {
879 - setTerminalSession(null);
880 - void refreshProviders({ environmentId, input: {} });
881 - }}
882 - />
883 - ) : null}
884 - </section>
885 - );
886 -}
887 -
888 -function OnboardingCodexSetup({
889 - createdAccount,
890 - onAutoStartConsumed,
891 - environmentId,
892 - provider,
893 - serverConfig,
894 - terminalOpen,
895 - onOpenTerminal,
896 -}: {
897 - readonly environmentId: EnvironmentId;
898 - readonly provider: ServerProvider | undefined;
899 - readonly serverConfig: ServerConfig;
900 - readonly terminalOpen: boolean;
901 - readonly onOpenTerminal: () => void;
902 - readonly createdAccount: {
903 - instanceId: ProviderInstanceId;
904 - displayName: string;
905 - autoStart: boolean;
906 - } | null;
907 - readonly onAutoStartConsumed: () => void;
908 -}) {
909 - const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
910 - const update = useAtomCommand(serverEnvironment.updateSettings, "Codex setup settings");
911 - const instanceId =
912 - createdAccount?.instanceId ??
913 - provider?.instanceId ??
914 - defaultInstanceIdForDriver(ProviderDriverKind.make("codex"));
915 - const settings = serverConfig.settings;
916 - const instance = settings.providerInstances[instanceId] ?? {
917 - driver: ProviderDriverKind.make("codex"),
918 - config: createdAccount ? { enabled: true, setupMode: "managed" } : {},
919 - };
920 - const mode = readCodexSetupMode(instance.config);
921 - const existingChosen =
922 - mode === "existing" &&
923 - instance.config !== null &&
924 - typeof instance.config === "object" &&
925 - "setupMode" in instance.config &&
926 - instance.config.setupMode === "existing";
927 - const changeMode = (setupMode: "managed" | "existing") => {
928 - void update({
929 - environmentId,
930 - input: {
931 - patch: buildProviderInstanceUpdatePatch({
932 - settings,
933 - instanceId,
934 - instance: {
935 - ...instance,
936 - enabled: true,
937 - config: {
938 - ...(instance.config !== null && typeof instance.config === "object"
939 - ? instance.config
940 - : {}),
941 - enabled: true,
942 - setupMode,
943 - },
944 - },
945 - }),
946 - },
947 - });
948 - };
949 - return existingChosen ? (
950 - <AgentCard
951 - driver="codex"
952 - provider={provider}
953 - terminalOpen={terminalOpen}
954 - terminalAvailable={canOperateTerminal}
955 - onOpenTerminal={onOpenTerminal}
956 - />
957 - ) : (
958 - <CodexSetupSection
959 - presentation="onboarding"
960 - autoStart={createdAccount?.autoStart === true}
961 - displayName={createdAccount?.displayName}
962 - onAutoStartConsumed={onAutoStartConsumed}
963 - environmentId={environmentId}
964 - instanceId={instanceId}
965 - provider={provider}
966 - mode={mode}
967 - enabled={provider?.enabled ?? true}
968 - onModeChange={changeMode}
969 - />
970 - );
971 -}
972 -
973 -function AgentCard({
974 - driver,
975 - provider,
976 - terminalOpen,
977 - terminalAvailable,
978 - onOpenTerminal,
979 -}: {
980 - readonly driver: OnboardingAgentDriver;
981 - readonly provider: ServerProvider | undefined;
982 - readonly terminalOpen: boolean;
983 - readonly terminalAvailable: boolean;
984 - readonly onOpenTerminal: () => void;
985 -}) {
986 - const meta = providerClients.get(ProviderDriverKind.make(driver));
987 - const displayName =
988 - provider?.displayName || (driver === "claudeAgent" ? "Claude Code" : (meta?.label ?? driver));
989 - const summary = getProviderSummary(provider);
990 - const providerState = getOnboardingProviderState(provider);
991 -
992 - return (
993 - <div className="flex items-center gap-3 rounded-lg border border-border bg-background px-4 py-4">
994 - <ProviderInstanceIcon
995 - driverKind={ProviderDriverKind.make(driver)}
996 - displayName={displayName}
997 - iconClassName="size-5"
998 - />
999 - <div className="min-w-0 flex-1">
1000 - <span className="block text-sm font-medium text-foreground">{displayName}</span>
1001 - <p className="mt-0.5 text-xs leading-relaxed break-words whitespace-pre-wrap text-muted-foreground">
1002 - {providerState === "ready" ? "Ready to code." : summary.headline}
1003 - {providerState !== "ready" && summary.detail ? ` · ${summary.detail}` : ""}
1004 - </p>
1005 - </div>
1006 - <div className="shrink-0">
1007 - {providerState === "ready" ? (
1008 - <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground">
1009 - <CheckIcon className="size-3.5" />
1010 - Ready
1011 - </span>
1012 - ) : providerState === "checking" ? (
1013 - <span className="text-xs text-muted-foreground">Checking...</span>
1014 - ) : providerState === "disabled" ? (
1015 - <span className="text-xs text-muted-foreground">Disabled</span>
1016 - ) : providerState === "attention" ? (
1017 - <span className="text-xs text-muted-foreground">{summary.headline}</span>
1018 - ) : (
1019 - <Button
1020 - size="xs"
1021 - variant="ghost"
1022 - onClick={onOpenTerminal}
1023 - disabled={terminalOpen || !terminalAvailable}
1024 - >
1025 - <TerminalIcon className="size-3.5" />
1026 - {providerState === "signIn" ? "Sign in" : "Install"}
1027 - </Button>
1028 - )}
1029 - </div>
1030 - </div>
1031 - );
1032 -}
1033 -
1034 -function AgentInstallTerminal({
1035 - session,
1036 - onClose,
1037 -}: {
1038 - readonly session: AgentTerminalSession;
1039 - readonly onClose: () => void;
1040 -}) {
1041 - const { command, cwd, driver, environmentId, keybindings, providerInstanceId } = session;
1042 - const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
1043 - const [advancedTypography] = useLocalStorage(
1044 - TYPOGRAPHY_ADVANCED_STORAGE_KEY,
1045 - false,
1046 - Schema.Boolean,
1047 - );
1048 - const openTerminal = useAtomCommand(terminalEnvironment.open, { reportFailure: false });
1049 - const writeTerminal = useAtomCommand(terminalEnvironment.write, { reportFailure: false });
1050 - const closeTerminal = useAtomCommand(terminalEnvironment.close, { reportFailure: false });
1051 - const setupQueueRef = useRef(Promise.resolve());
1052 - const setupGenerationRef = useRef(0);
1053 - const activeSetupGenerationRef = useRef<number | null>(null);
1054 - const [terminalId] = useState(() => `onboarding-${driver}-${randomUUID()}`);
1055 - const threadRef = scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID);
1056 - const [setupAttempt, setSetupAttempt] = useState(0);
1057 - const [setupState, setSetupState] = useState<
1058 - "preparing" | "ready" | "openFailed" | "writeFailed"
1059 - >("preparing");
1060 - const terminalReady = setupState === "ready" || setupState === "writeFailed";
1061 -
1062 - // StrictMode can finish a cancelled open after replacement setup; it must not close or pre-type into that
1063 - // session.
1064 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the setup PTY, types the command into it, and closes it on cleanup
1065 - useEffect(() => {
1066 - const generation = setupGenerationRef.current + 1;
1067 - setupGenerationRef.current = generation;
1068 - activeSetupGenerationRef.current = generation;
1069 - // oxlint-disable-next-line react/set-state-in-effect -- A retry or a new command reopens the terminal, which shows as preparing until the open settles.
1070 - setSetupState("preparing");
1071 -
1072 - setupQueueRef.current = setupQueueRef.current.then(async () => {
1073 - if (activeSetupGenerationRef.current !== generation) return;
1074 - if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
1075 - setSetupState("openFailed");
1076 - return;
1077 - }
1078 - const opened = await openTerminal({
1079 - environmentId,
1080 - input: {
1081 - threadId: AGENT_ONBOARDING_THREAD_ID,
1082 - terminalId,
1083 - cwd,
1084 - providerInstanceId,
1085 - },
1086 - });
1087 - if (opened._tag !== "Success") {
1088 - if (activeSetupGenerationRef.current === generation) setSetupState("openFailed");
1089 - return;
1090 - }
1091 -
1092 - if (activeSetupGenerationRef.current !== generation) return;
1093 - if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
1094 - setSetupState("writeFailed");
1095 - return;
1096 - }
1097 -
1098 - const wrote = await writeTerminal({
1099 - environmentId,
1100 - input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, data: command },
1101 - });
1102 - if (activeSetupGenerationRef.current !== generation) return;
1103 - setSetupState(wrote._tag === "Success" ? "ready" : "writeFailed");
1104 - });
1105 -
1106 - // Revocation leaves the PTY running; close only while terminal access remains.
1107 - return () => {
1108 - if (activeSetupGenerationRef.current === generation) {
1109 - activeSetupGenerationRef.current = null;
1110 - }
1111 - setupQueueRef.current = setupQueueRef.current.then(async () => {
1112 - if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) return;
1113 - await closeTerminal({
1114 - environmentId,
1115 - input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, deleteHistory: true },
1116 - });
1117 - });
1118 - };
1119 - }, [
1120 - closeTerminal,
1121 - command,
1122 - cwd,
1123 - environmentId,
1124 - openTerminal,
1125 - providerInstanceId,
1126 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry bumps setupAttempt to open the terminal again.
1127 - setupAttempt,
1128 - terminalId,
1129 - writeTerminal,
1130 - ]);
1131 -
1132 - return (
1133 - <div
1134 - data-thread-terminal-drawer
1135 - className="mt-4 overflow-hidden rounded-lg border border-border/70 bg-background text-foreground"
1136 - >
1137 - <div className="flex items-center justify-between border-b border-border/60 bg-background/60 px-3 py-1.5">
1138 - <span className="text-2xs font-medium text-muted-foreground">
1139 - {!canOperateTerminal ? (
1140 - "This connection cannot control terminals."
1141 - ) : setupState === "writeFailed" ? (
1142 - <>
1143 - Run <code className="rounded bg-muted px-1 font-mono">{command}</code> in this
1144 - terminal.
1145 - </>
1146 - ) : setupState === "ready" ? (
1147 - "Review the command, then press Enter to run it."
1148 - ) : setupState === "openFailed" ? (
1149 - "Could not open the setup terminal."
1150 - ) : (
1151 - "Preparing command..."
1152 - )}
1153 - </span>
1154 - <div className="flex items-center gap-1">
1155 - {setupState === "openFailed" ? (
1156 - <Button
1157 - size="xs"
1158 - variant="ghost"
1159 - disabled={!canOperateTerminal}
1160 - onClick={() => {
1161 - if (readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
1162 - setSetupAttempt((value) => value + 1);
1163 - }
1164 - }}
1165 - >
1166 - Retry
1167 - </Button>
1168 - ) : null}
1169 - <Button size="xs" variant="ghost-muted" onClick={onClose}>
1170 - Close
1171 - </Button>
1172 - </div>
1173 - </div>
1174 - <div className="h-64">
1175 - {terminalReady ? (
1176 - <TerminalViewport
1177 - threadRef={threadRef}
1178 - threadId={AGENT_ONBOARDING_THREAD_ID}
1179 - terminalId={terminalId}
1180 - terminalLabel={`Install ${driver}`}
1181 - cwd={cwd}
1182 - providerInstanceId={providerInstanceId}
1183 - advancedTypography={advancedTypography}
1184 - onSessionExited={onClose}
1185 - autoFocus
1186 - visible
1187 - keybindings={keybindings}
1188 - />
1189 - ) : null}
1190 - </div>
1191 - </div>
1192 - );
1193 -}
1194 -
1195 -const IMPORT_PERMISSION_MESSAGE = "This connection cannot import projects or thread history.";
1196 -
1197 -interface ImportSelection {
1198 - // Computers whose projects were listed when the selection changed; later ones get the defaults.
1199 - readonly environmentIds: ReadonlySet<EnvironmentId>;
1200 - readonly keys: ReadonlySet<string>;
1201 -}
1202 -
1203 -function ImportStep({
1204 - scans,
1205 - importSelection,
1206 - onImportSelectionChange,
1207 - isImporting,
1208 - setIsImporting,
1209 - onDone,
1210 -}: {
1211 - readonly scans: ReturnType<typeof useProjectScans>;
1212 - readonly importSelection: ImportSelection | null;
1213 - readonly onImportSelectionChange: (next: ImportSelection) => void;
1214 - readonly isImporting: boolean;
1215 - readonly setIsImporting: (value: boolean) => void;
1216 - readonly onDone: (
1217 - projectRef?: ScopedProjectRef,
1218 - importWarning?: string,
1219 - importedThreadCount?: number,
1220 - ) => Promise<boolean>;
1221 -}) {
1222 - const { environments } = useEnvironments();
1223 - const writableEnvironments = useEnvironmentsWithScope(scans, AuthOrchestrationOperateScope);
1224 - const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
1225 - const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false });
1226 - const importWarningRef = useRef("");
1227 - const importedThreadCountRef = useRef(0);
1228 - const importedProjectsRef = useRef(new Map<string, ScopedProjectRef>());
1229 - const projectsWithImportedHistoryRef = useRef(new Map<string, ScopedProjectRef>());
1230 - const lastImportSelectionRef = useRef<ReadonlyArray<string>>([]);
1231 - const projectAttemptsRef = useRef(
1232 - new Map<string, { readonly projectId: ProjectId; readonly commandId: CommandId }>(),
1233 - );
1234 - const importGenerationRef = useRef(0);
1235 -
1236 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- bumps the import generation on mount and unmount so in-flight imports drop stale results
1237 - useEffect(() => {
1238 - importGenerationRef.current += 1;
1239 - return () => {
1240 - importGenerationRef.current += 1;
1241 - };
1242 - }, []);
1243 -
1244 - const { available: candidates, recent } = partitionOnboardingProjects(
1245 - scans.flatMap((scan) =>
1246 - (scan.data?.candidates ?? []).map((candidate) => ({
1247 - ...candidate,
1248 - environmentId: scan.environmentId,
1249 - key: onboardingProjectKey(scan.environmentId, candidate.path),
1250 - })),
1251 - ),
1252 - );
1253 - const recentKeys = new Set(recent.map((candidate) => candidate.key));
1254 - const selected = candidates.filter((candidate) =>
1255 - importSelection?.environmentIds.has(candidate.environmentId)
1256 - ? importSelection.keys.has(candidate.key)
1257 - : recentKeys.has(candidate.key),
1258 - );
1259 - const selectedKeys = new Set(selected.map((candidate) => candidate.key));
1260 - const setSelectedKeys = (keys: ReadonlySet<string>) =>
1261 - onImportSelectionChange({
1262 - environmentIds: new Set(
1263 - scans.flatMap((scan) => (scan.data === null ? [] : [scan.environmentId])),
1264 - ),
1265 - keys,
1266 - });
1267 -
1268 - const canImport = selected.every((candidate) =>
1269 - writableEnvironments.has(candidate.environmentId),
1270 - );
1271 - const [importError, setImportError] = useState("");
1272 - const visibleImportError = !canImport
1273 - ? IMPORT_PERMISSION_MESSAGE
1274 - : importError === IMPORT_PERMISSION_MESSAGE
1275 - ? ""
1276 - : importError;
1277 -
1278 - const finishAfterImport = () => {
1279 - const projectRef = resolveOnboardingLandingProject(
1280 - lastImportSelectionRef.current,
1281 - projectsWithImportedHistoryRef.current,
1282 - importedProjectsRef.current,
1283 - );
1284 - if (projectRef === undefined) {
1285 - void onDone(undefined, importWarningRef.current, importedThreadCountRef.current);
1286 - return;
1287 - }
1288 - setIsImporting(true);
1289 - const importGeneration = importGenerationRef.current;
1290 - // waitForProject gives up after its timeout, so a project that never reaches the client
1291 - // still finishes setup, just without landing in it.
1292 - void waitForProject(projectRef)
1293 - .then(
1294 - () => projectRef,
1295 - () => undefined,
1296 - )
1297 - .then(async (landing) => {
1298 - if (importGeneration !== importGenerationRef.current) return;
1299 - const completed = await onDone(
1300 - landing,
1301 - importWarningRef.current,
1302 - importedThreadCountRef.current,
1303 - );
1304 - if (!completed) setIsImporting(false);
1305 - });
1306 - };
1307 -
1308 - const runImport = async (selection: typeof candidates) => {
1309 - if (isImporting) return;
1310 - const hasAccess = () =>
1311 - selection.every((candidate) =>
1312 - readEnvironmentScope(candidate.environmentId, AuthOrchestrationOperateScope),
1313 - );
1314 - const stopForDeniedAccess = () => {
1315 - setIsImporting(false);
1316 - setImportError(IMPORT_PERMISSION_MESSAGE);
1317 - };
1318 - if (!hasAccess()) {
1319 - stopForDeniedAccess();
1320 - return;
1321 - }
1322 - if (selection.length === 0) {
1323 - void onDone();
1324 - return;
1325 - }
1326 - setIsImporting(true);
1327 - importWarningRef.current = "";
1328 - importedThreadCountRef.current = 0;
1329 - lastImportSelectionRef.current = selection.map((candidate) => candidate.key);
1330 - const importGeneration = importGenerationRef.current;
1331 - const importedProjects = importedProjectsRef.current;
1332 - const projectAttempts = projectAttemptsRef.current;
1333 - let importedProjectsCount =
1334 - importedProjects.size > 0
1335 - ? selection.filter((candidate) => importedProjects.has(candidate.key)).length
1336 - : 0;
1337 - let importedThreadCount = 0;
1338 - let skippedThreadCount = 0;
1339 - const refreshEnvironments = new Set<EnvironmentId>();
1340 - for (const candidate of selection) {
1341 - const { environmentId } = candidate;
1342 - if (
1343 - importGeneration !== importGenerationRef.current ||
1344 - importedProjects !== importedProjectsRef.current
1345 - ) {
1346 - return;
1347 - }
1348 - if (!hasAccess()) {
1349 - stopForDeniedAccess();
1350 - return;
1351 - }
1352 - if (importedProjects.has(candidate.key)) continue;
1353 - let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate);
1354 - if (projectId === null) {
1355 - let attempt = projectAttempts.get(candidate.key);
1356 - if (attempt === undefined) {
1357 - const nextProjectId = newProjectId();
1358 - attempt = {
1359 - projectId: nextProjectId,
1360 - commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`),
1361 - };
1362 - projectAttempts.set(candidate.key, attempt);
1363 - }
1364 - projectId = attempt.projectId;
1365 - const result = await createProject({
1366 - environmentId,
1367 - input: {
1368 - projectId,
1369 - commandId: attempt.commandId,
1370 - title: candidate.title,
1371 - workspaceRoot: candidate.path,
1372 - createWorkspaceRootIfMissing: false,
1373 - defaultModelSelection: null,
1374 - },
1375 - });
1376 - if (
1377 - importGeneration !== importGenerationRef.current ||
1378 - importedProjects !== importedProjectsRef.current
1379 - ) {
1380 - return;
1381 - }
1382 - if (result._tag !== "Success") {
1383 - if (!isAtomCommandInterrupted(result)) {
1384 - projectAttempts.delete(candidate.key);
1385 - refreshEnvironments.add(environmentId);
1386 - }
1387 - continue;
1388 - }
1389 - }
1390 -
1391 - if (!hasAccess()) {
1392 - stopForDeniedAccess();
1393 - return;
1394 - }
1395 - const threadImportResult = await importThreads({
1396 - environmentId,
1397 - input: { projectId, expectedWorkspaceRoot: candidate.path },
1398 - });
1399 - if (
1400 - importGeneration !== importGenerationRef.current ||
1401 - importedProjects !== importedProjectsRef.current
1402 - ) {
1403 - return;
1404 - }
1405 - if (threadImportResult._tag === "Success") {
1406 - importedThreadCount += threadImportResult.value.importedCount;
1407 - skippedThreadCount += threadImportResult.value.skippedCount;
1408 - if (threadImportResult.value.importedCount > 0) {
1409 - projectsWithImportedHistoryRef.current.set(
1410 - candidate.key,
1411 - scopeProjectRef(environmentId, projectId),
1412 - );
1413 - }
1414 - if (threadImportResult.value.skippedCount === 0) {
1415 - importedProjectsCount += 1;
1416 - importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId));
1417 - }
1418 - } else if (!isAtomCommandInterrupted(threadImportResult)) {
1419 - projectAttempts.delete(candidate.key);
1420 - refreshEnvironments.add(environmentId);
1421 - }
1422 - }
1423 - for (const scan of scans) {
1424 - if (refreshEnvironments.has(scan.environmentId)) scan.refresh();
1425 - }
1426 - setIsImporting(false);
1427 - importedThreadCountRef.current = importedThreadCount;
1428 - if (importedProjectsCount < selection.length) {
1429 - if (importedThreadCount > 0 && skippedThreadCount > 0) {
1430 - importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedThreadCount} ${skippedThreadCount === 1 ? "thread" : "threads"} could not be imported.`;
1431 - } else if (skippedThreadCount > 0) {
1432 - importWarningRef.current = `${skippedThreadCount} ${skippedThreadCount === 1 ? "thread could" : "threads could"} not be imported.`;
1433 - } else if (importedThreadCount > 0) {
1434 - importWarningRef.current = `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`;
1435 - } else {
1436 - importWarningRef.current = "Could not import thread history.";
1437 - }
1438 - }
1439 - finishAfterImport();
1440 - };
1441 -
1442 - if (scans.every((scan) => scan.data === null) && scans.some((scan) => scan.isPending)) {
1443 - return (
1444 - <div className="flex h-full min-h-40 flex-col">
1445 - <h1 className="text-2xl font-semibold tracking-tight text-foreground">Your projects</h1>
1446 - <div className="flex flex-1 flex-col items-center justify-center gap-3 py-6">
1447 - <Spinner size="lg" tone="muted" />
1448 - <p className="text-center text-sm text-muted-foreground">
1449 - Looking for projects from Claude Code and Codex…
1450 - </p>
1451 - </div>
1452 - <div className="flex justify-end">
1453 - <Button variant="ghost-muted" onClick={() => void onDone()}>
1454 - Do not import projects
1455 - </Button>
1456 - </div>
1457 - </div>
1458 - );
1459 - }
1460 -
1461 - return (
1462 - <StepShell
1463 - title="Import your projects"
1464 - description="Import projects and conversations from Claude Code and Codex on your selected computers."
1465 - >
1466 - {candidates.length > 0 ? (
1467 - <div className="mt-5 flex items-center justify-between gap-3 text-xs text-muted-foreground">
1468 - <span role="status">
1469 - {selected.length} of {candidates.length} selected
1470 - </span>
1471 - <div className="flex items-center gap-1">
1472 - <Button
1473 - variant="ghost"
1474 - size="xs"
1475 - disabled={isImporting || selected.length === candidates.length}
1476 - onClick={() => setSelectedKeys(new Set(candidates.map((item) => item.key)))}
1477 - >
1478 - Select all
1479 - </Button>
1480 - <Button
1481 - variant="ghost"
1482 - size="xs"
1483 - disabled={isImporting || selected.length === 0}
1484 - onClick={() => setSelectedKeys(new Set())}
1485 - >
1486 - Select none
1487 - </Button>
1488 - </div>
1489 - </div>
1490 - ) : null}
1491 - <ScrollArea scrollFade className="mt-2 h-auto max-h-80">
1492 - <div className="space-y-5 pr-3">
1493 - {scans.map((scan) => {
1494 - const scanCandidates = candidates.filter(
1495 - (candidate) => candidate.environmentId === scan.environmentId,
1496 - );
1497 - const label =
1498 - environments.find((environment) => environment.environmentId === scan.environmentId)
1499 - ?.label ?? "Computer";
1500 - return (
1501 - <fieldset
1502 - key={scan.environmentId}
1503 - className="min-w-0 space-y-0.5"
1504 - disabled={isImporting}
1505 - >
1506 - {scans.length > 1 ? (
1507 - <legend className="mb-2 text-sm font-medium">{label}</legend>
1508 - ) : null}
1509 - {scan.isPending && scan.data === null ? (
1510 - <div className="flex items-center gap-2 py-3 text-sm text-muted-foreground">
1511 - <Spinner size="md" />
1512 - Looking for projects…
1513 - </div>
1514 - ) : scan.error !== null ? (
1515 - <div
1516 - role="alert"
1517 - className="flex items-center justify-between gap-3 text-sm text-muted-foreground"
1518 - >
1519 - <span>Could not check projects. {scan.error}</span>
1520 - <Button variant="ghost" size="sm" onClick={scan.refresh}>
1521 - Retry
1522 - </Button>
1523 - </div>
1524 - ) : scanCandidates.length === 0 ? (
1525 - <p className="py-2 text-sm text-muted-foreground">
1526 - No existing Claude Code or Codex projects found.
1527 - </p>
1528 - ) : null}
1529 - {scan.data?.truncated ? (
1530 - <p className="text-xs text-muted-foreground" role="status">
1531 - {SCAN_LIMIT_MESSAGE}
1532 - </p>
1533 - ) : null}
1534 - <ImportCandidateList
1535 - candidates={scanCandidates}
1536 - selectedKeys={selectedKeys}
1537 - onSelectionChange={setSelectedKeys}
1538 - />
1539 - </fieldset>
1540 - );
1541 - })}
1542 - </div>
1543 - </ScrollArea>
1544 - {visibleImportError ? (
1545 - <p className="mt-3 text-sm text-destructive">{visibleImportError}</p>
1546 - ) : null}
1547 - <div className="mt-6 flex flex-wrap items-center justify-end gap-3">
1548 - <Button variant="ghost-muted" disabled={isImporting} onClick={finishAfterImport}>
1549 - Do not import projects
1550 - </Button>
1551 - <Button
1552 - autoFocus
1553 - disabled={!canImport || isImporting || selected.length === 0}
1554 - onClick={() => void runImport(selected)}
1555 - >
1556 - {isImporting
1557 - ? "Importing…"
1558 - : `Import ${selected.length} ${selected.length === 1 ? "project" : "projects"}`}
1559 - </Button>
1560 - </div>
1561 - </StepShell>
1562 - );
1563 -}
1564 -
1565 -type ImportCandidate = AgentSessionProjectCandidate & {
1566 - readonly environmentId: EnvironmentId;
1567 - readonly key: string;
1568 -};
1569 -
1570 -function ImportCandidateList({
1571 - candidates,
1572 - selectedKeys,
1573 - onSelectionChange,
1574 -}: {
1575 - readonly candidates: ReadonlyArray<ImportCandidate>;
1576 - readonly selectedKeys: ReadonlySet<string>;
1577 - readonly onSelectionChange: (next: ReadonlySet<string>) => void;
1578 -}) {
1579 - const { repositories, other } = groupOnboardingProjects(candidates);
1580 - const setKeys = (keys: ReadonlyArray<string>, checked: boolean) => {
1581 - const next = new Set(selectedKeys);
1582 - for (const key of keys) {
1583 - if (checked) next.add(key);
1584 - else next.delete(key);
1585 - }
1586 - onSelectionChange(next);
1587 - };
1588 - const otherSelected = other.filter((candidate) => selectedKeys.has(candidate.key)).length;
1589 -
1590 - return (
1591 - <>
1592 - {repositories.map((group) => (
1593 - <ImportRepositoryGroup
1594 - key={group.key}
1595 - group={group}
1596 - selectedKeys={selectedKeys}
1597 - onToggle={setKeys}
1598 - />
1599 - ))}
1600 - {other.length > 0 ? (
1601 - <Collapsible>
1602 - <div className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40">
1603 - <Checkbox
1604 - checked={otherSelected === other.length}
1605 - indeterminate={otherSelected > 0 && otherSelected < other.length}
1606 - onCheckedChange={(checked) =>
1607 - setKeys(
1608 - other.map((candidate) => candidate.key),
1609 - checked === true,
1610 - )
1611 - }
1612 - />
1613 - <CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-1.5 text-left">
1614 - <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-panel-open:rotate-90" />
1615 - <span className="truncate text-sm text-muted-foreground">Other folders</span>
1616 - <span className="ml-auto shrink-0 text-xs text-muted-foreground tabular-nums">
1617 - {other.length} {other.length === 1 ? "folder" : "folders"}
1618 - </span>
1619 - </CollapsibleTrigger>
1620 - </div>
1621 - <CollapsiblePanel>
1622 - {other.map((candidate) => (
1623 - <ImportCandidateRow
1624 - key={candidate.key}
1625 - candidate={candidate}
1626 - path={candidate.path}
1627 - nested
1628 - checked={selectedKeys.has(candidate.key)}
1629 - onCheckedChange={(checked) => setKeys([candidate.key], checked)}
1630 - />
1631 - ))}
1632 - </CollapsiblePanel>
1633 - </Collapsible>
1634 - ) : null}
1635 - </>
1636 - );
1637 -}
1638 -
1639 -function ImportRepositoryGroup({
1640 - group,
1641 - selectedKeys,
1642 - onToggle,
1643 -}: {
1644 - readonly group: OnboardingProjectGroup<ImportCandidate>;
1645 - readonly selectedKeys: ReadonlySet<string>;
1646 - readonly onToggle: (keys: ReadonlyArray<string>, checked: boolean) => void;
1647 -}) {
1648 - const keys = group.candidates.map((candidate) => candidate.key);
1649 - const selectedCount = keys.filter((key) => selectedKeys.has(key)).length;
1650 - const single = group.candidates.length === 1;
1651 - const only = group.candidates[0];
1652 - if (single && only !== undefined) {
1653 - return (
1654 - <ImportCandidateRow
1655 - candidate={only}
1656 - label={group.label}
1657 - path={only.path}
1658 - checked={selectedKeys.has(only.key)}
1659 - onCheckedChange={(checked) => onToggle([only.key], checked)}
1660 - />
1661 - );
1662 - }
1663 - return (
1664 - <Collapsible defaultOpen>
1665 - <div className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40">
1666 - <Checkbox
1667 - checked={selectedCount === keys.length}
1668 - indeterminate={selectedCount > 0 && selectedCount < keys.length}
1669 - onCheckedChange={(checked) => onToggle(keys, checked === true)}
1670 - />
1671 - <CollapsibleTrigger className="group flex min-w-0 flex-1 items-center gap-1.5 text-left">
1672 - <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-panel-open:rotate-90" />
1673 - <span className="truncate text-sm font-medium">{group.label}</span>
1674 - <ImportRowMeta
1675 - sources={[...new Set(group.candidates.flatMap((c) => c.sources))]}
1676 - threadCount={group.threadCount}
1677 - lastActiveAt={group.lastActiveAt}
1678 - />
1679 - </CollapsibleTrigger>
1680 - </div>
1681 - <CollapsiblePanel>
1682 - {group.candidates.map((candidate) => (
1683 - <ImportCandidateRow
1684 - key={candidate.key}
1685 - candidate={candidate}
1686 - path={candidate.path}
1687 - nested
1688 - checked={selectedKeys.has(candidate.key)}
1689 - onCheckedChange={(checked) => onToggle([candidate.key], checked)}
1690 - />
1691 - ))}
1692 - </CollapsiblePanel>
1693 - </Collapsible>
1694 - );
1695 -}
1696 -
1697 -function ProjectPathText({
1698 - path,
1699 - className,
1700 -}: {
1701 - readonly path: string;
1702 - readonly className?: string;
1703 -}) {
1704 - const { name, parent } = splitOnboardingProjectPath(path);
1705 - return (
1706 - <span className={cn("flex min-w-0 items-baseline font-mono", className)}>
1707 - {parent.length > 0 ? <span className="truncate">{parent}</span> : null}
1708 - <span className="max-w-full shrink-0 truncate">{name}</span>
1709 - </span>
1710 - );
1711 -}
1712 -
1713 -function ImportCandidateRow({
1714 - candidate,
1715 - label,
1716 - path,
1717 - nested = false,
1718 - checked,
1719 - onCheckedChange,
1720 -}: {
1721 - readonly candidate: ImportCandidate;
1722 - readonly label?: string;
1723 - readonly path?: string;
1724 - readonly nested?: boolean;
1725 - readonly checked: boolean;
1726 - readonly onCheckedChange: (checked: boolean) => void;
1727 -}) {
1728 - return (
1729 - <label
1730 - className={cn(
1731 - "flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/40 has-disabled:cursor-default",
1732 - nested && "pl-8",
1733 - )}
1734 - >
1735 - <Checkbox checked={checked} onCheckedChange={(value) => onCheckedChange(value === true)} />
1736 - <Tooltip>
1737 - <TooltipTrigger
1738 - render={<span className="flex min-w-0 flex-1 items-baseline gap-2 truncate" />}
1739 - >
1740 - {label !== undefined ? (
1741 - <span className="truncate text-sm font-medium">{label}</span>
1742 - ) : null}
1743 - {path !== undefined ? (
1744 - <ProjectPathText
1745 - path={path}
1746 - className={label === undefined ? "text-xs" : "text-2xs text-muted-foreground"}
1747 - />
1748 - ) : null}
1749 - </TooltipTrigger>
1750 - <TooltipPopup variant="code">{candidate.path}</TooltipPopup>
1751 - </Tooltip>
1752 - <ImportRowMeta
1753 - sources={nested ? null : candidate.sources}
1754 - threadCount={candidate.threadCount}
1755 - lastActiveAt={candidate.lastActiveAt}
1756 - />
1757 - </label>
1758 - );
1759 -}
1760 -
1761 -const IMPORT_SOURCE_NAMES: Record<AgentSessionSource, string> = {
1762 - claudeAgent: "Claude Code",
1763 - codex: "Codex",
1764 - pi: "Pi",
1765 -};
1766 -
1767 -function ImportRowMeta({
1768 - sources,
1769 - threadCount,
1770 - lastActiveAt,
1771 -}: {
1772 - readonly sources: ReadonlyArray<AgentSessionSource> | null;
1773 - readonly threadCount: number;
1774 - readonly lastActiveAt: string | null;
1775 -}) {
1776 - const relative = lastActiveAt === null ? null : formatRelativeTime(lastActiveAt);
1777 - const age = relative === null ? "" : relative.suffix === null ? "now" : relative.value;
1778 - return (
1779 - <span className="ml-auto grid shrink-0 grid-cols-[1rem_1rem_1rem_2.5rem_2.25rem] items-center gap-x-1 text-xs text-muted-foreground tabular-nums">
1780 - {AgentSessionSource.literals.map((source) => (
1781 - <span key={source} className="flex size-4 items-center justify-center">
1782 - {sources?.includes(source) ? (
1783 - <span role="img" aria-label={IMPORT_SOURCE_NAMES[source]}>
1784 - <ProviderInstanceIcon
1785 - driverKind={ProviderDriverKind.make(source)}
1786 - displayName={IMPORT_SOURCE_NAMES[source]}
1787 - iconClassName="size-3"
1788 - />
1789 - </span>
1790 - ) : null}
1791 - </span>
1792 - ))}
1793 - <span className="text-right">{threadCount}</span>
1794 - <span className="text-right whitespace-nowrap">{age}</span>
1795 - </span>
1796 - );
1797 -}
1798 -
1799 -/** The desktop app links `t3` on a fresh install; this puts its folder on PATH when it is not. */
1800 -function CliPathSetup() {
1801 - const { state, busy, run } = useDesktopCliCommand();
1802 - const setup = state?.pathSetup;
1803 - if (!setup) return null;
1804 - return (
1805 - <div className="mt-5 flex items-center justify-between gap-3">
1806 - <p className="text-sm text-muted-foreground">
1807 - {setup.added ? (
1808 - <>
1809 - Added to {setup.file}. Open a new terminal to use <code className="font-mono">t3</code>.
1810 - </>
1811 - ) : (
1812 - <>
1813 - Use <code className="font-mono">t3</code> from any terminal. Adds one line to{" "}
1814 - {setup.file}.
1815 - </>
1816 - )}
1817 - </p>
1818 - {setup.added ? null : (
1819 - <Button size="sm" variant="outline" disabled={busy} onClick={() => run("addToPath")}>
1820 - Add to PATH
1821 - </Button>
1822 - )}
1823 - </div>
1824 - );
1825 -}
1826 -
1827 -function StepShell({
1828 - title,
1829 - description,
1830 - children,
1831 -}: {
1832 - readonly title: string;
1833 - readonly description?: string;
1834 - readonly children?: React.ReactNode;
1835 -}) {
1836 - return (
1837 - <>
1838 - <h1 className="text-2xl font-semibold tracking-tight text-foreground">{title}</h1>
1839 - {description ? (
1840 - <p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">{description}</p>
1841 - ) : null}
1842 - {children}
1843 - </>
1844 - );
1845 -}
apps/web/src/components/settings/AddCodexAccountDialog.browser.test.tsx
+11 -2
@@ -74,7 +74,13 @@ function createdInstanceId(): ProviderInstanceId {
74 return ProviderInstanceId.make(Object.keys(call[0].input.patch.providerInstances)[0]!);
75 }
76
77 -function Owner({ onClose }: { readonly onClose: () => void }) {
77 +function Owner({
78 + onClose,
79 + onAccountCreated,
80 +}: {
81 + readonly onClose: () => void;
82 + readonly onAccountCreated: (instanceId: ProviderInstanceId) => void;
83 +}) {
84 const [shown, setShown] = useState(true);
85 return shown ? (
86 <AddCodexAccountDialog
@@ -83,6 +89,7 @@ function Owner({ onClose }: { readonly onClose: () => void }) {
89 onClose();
90 setShown(false);
91 }}
92 + onAccountCreated={onAccountCreated}
93 renderSetup={() => <p>Sign in to ChatGPT</p>}
94 />
95 ) : null;
@@ -93,6 +100,7 @@ describe("AddCodexAccountDialog", () => {
100 const atom = Atom.make<ReadonlyArray<ServerProvider> | null>([]).pipe(Atom.keepAlive);
101 providersAtom.current = atom;
102 const onClose = vi.fn();
103 + const onAccountCreated = vi.fn();
104 // A long exit transition that the test finishes by hand, so the close is
105 // observable mid-animation without waiting on real time.
106 const style = document.createElement("style");
@@ -102,13 +110,14 @@ describe("AddCodexAccountDialog", () => {
110 using _style = { [Symbol.dispose]: () => style.remove() };
111 await using _screen = await render(
112 <AppAtomRegistryProvider>
105 - <Owner onClose={onClose} />
113 + <Owner onClose={onClose} onAccountCreated={onAccountCreated} />
114 </AppAtomRegistryProvider>,
115 );
116
117 await userEvent.click(page.getByRole("button", { name: "Continue" }));
118 const instanceId = createdInstanceId();
119 await act(() => registry.set(atom, [codexProvider(instanceId, { status: "unauthenticated" })]));
120 + // Telling the owner about the account does not skip the dialog's own sign-in.
121 await expect.element(page.getByText("Sign in to ChatGPT")).toBeVisible();
122
123 await act(() =>
apps/web/src/components/settings/AddCodexAccountDialog.tsx
+3 -6
@@ -31,6 +31,7 @@ export function AddCodexAccountDialog({
31 }: {
32 readonly environmentId: EnvironmentId;
33 readonly onClose: () => void;
34 + // Told when the account is created; the dialog then runs its own sign-in.
35 readonly onAccountCreated?:
36 | ((instanceId: ProviderInstanceId, displayName: string) => void)
37 | undefined;
@@ -71,12 +72,8 @@ export function AddCodexAccountDialog({
72 },
73 });
74 if (result._tag === "Success") {
74 - if (onAccountCreated) {
75 - onAccountCreated(id, displayName);
76 - onClose();
77 - } else {
78 - setInstanceId(id);
79 - }
75 + onAccountCreated?.(id, displayName);
76 + setInstanceId(id);
77 }
78 setPending(false);
79 };
apps/web/src/components/settings/AddProviderInstanceDialog.tsx
+7 -3
@@ -140,7 +140,9 @@ interface AddProviderInstanceDialogProps {
140 readonly environmentId: EnvironmentId;
141 readonly environmentLabel: string;
142 readonly onOpenChange: (open: boolean) => void;
143 - readonly onCreated?: (instanceId: ProviderInstanceId) => void;
143 + readonly onCreated?: (instanceId: ProviderInstanceId, driver: ProviderDriverKind) => void;
144 + /** Opens with "Show more" expanded, so the ACP Registry search is in view. */
145 + readonly showMoreProviders?: boolean;
146 }
147
148 export function AddProviderInstanceDialog({
@@ -149,6 +151,7 @@ export function AddProviderInstanceDialog({
151 environmentLabel,
152 onOpenChange,
153 onCreated,
154 + showMoreProviders: initialShowMoreProviders = false,
155 }: AddProviderInstanceDialogProps) {
156 const settings = useEnvironmentSettings(environmentId);
157 const secretSources = useSecretSources(environmentId);
@@ -179,7 +182,7 @@ export function AddProviderInstanceDialog({
182 ReadonlyArray<ProviderInstanceEnvironmentVariable>
183 >([]);
184 const [isManualAcpConfiguration, setIsManualAcpConfiguration] = useState(false);
182 - const [showMoreProviders, setShowMoreProviders] = useState(false);
185 + const [showMoreProviders, setShowMoreProviders] = useState(initialShowMoreProviders);
186 const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
187 const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
188 const [isSaving, setIsSaving] = useState(false);
@@ -405,7 +408,7 @@ export function AddProviderInstanceDialog({
408 });
409 return;
410 }
408 - onCreated?.(brandedId);
411 + onCreated?.(brandedId, driver);
412 if (isAcpRegistry && !isLocalAcp) {
413 setCreatedInstanceId(brandedId);
414 setIsSaving(false);
@@ -425,6 +428,7 @@ export function AddProviderInstanceDialog({
428 <AddManagedCodexAccountDialog
429 environmentId={environmentId}
430 onClose={() => onOpenChange(false)}
431 + onAccountCreated={(instanceId) => onCreated?.(instanceId, ProviderDriverKind.make("codex"))}
432 />
433 );
434 }
apps/web/src/components/settings/CodexSetupSection.tsx
+10 -2
@@ -95,6 +95,8 @@ interface CodexSetupSectionProps {
95 readonly mode: "managed" | "existing";
96 readonly enabled: boolean;
97 readonly readOnly?: boolean;
98 + // Onboarding's "Use existing CLI" opens a terminal, which this session may not be allowed.
99 + readonly existingCliDisabled?: boolean;
100 readonly presentation?: "settings" | "onboarding";
101 readonly onModeChange: (mode: "managed" | "existing") => void;
102 readonly autoStart?: boolean;
@@ -172,7 +174,12 @@ export function CodexSetupSection(props: CodexSetupSectionProps) {
174 }
175 secondaryControl={
176 !existingAuthenticated && !existingReady && !existingChecking ? (
175 - <Button size="sm" variant="ghost-muted" onClick={() => props.onModeChange("existing")}>
177 + <Button
178 + size="sm"
179 + variant="ghost-muted"
180 + disabled={props.existingCliDisabled}
181 + onClick={() => props.onModeChange("existing")}
182 + >
183 Use existing CLI
184 </Button>
185 ) : null
@@ -258,6 +265,7 @@ function ManagedCodexSetup({
265 autoStart,
266 onAutoStartConsumed,
267 allowExistingCli = true,
268 + existingCliDisabled,
269 presentation,
270 displayName,
271 onSignInCancelled,
@@ -909,7 +917,7 @@ function ManagedCodexSetup({
917 <Button
918 size="sm"
919 variant="ghost-muted"
912 - disabled={readOnly || busy}
920 + disabled={readOnly || busy || existingCliDisabled}
921 onClick={() => onModeChange("existing")}
922 >
923 Use existing CLI
apps/web/src/components/settings/SettingsPanels.tsx
+18 -1
@@ -72,7 +72,11 @@ import {
72 import { useTextGenerationTargets } from "../../textGenerators";
73 import { ensureLocalApi, readLocalApi } from "../../localApi";
74 import { isMacPlatform } from "../../lib/utils";
75 -import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
75 +import {
76 + useEnvironmentProviders,
77 + useEnvironments,
78 + usePrimaryEnvironmentId,
79 +} from "../../state/environments";
80 import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
81 import { Button } from "../ui/button";
82 import { DraftInput } from "../ui/draft-input";
@@ -2050,6 +2054,8 @@ export function MaintenanceSettingsPanel() {
2054
2055 export function AboutSettingsPanel() {
2056 const primaryPolicy = usePrimaryManagedPolicy();
2057 + // The Welcome page sets up this computer, so it needs one.
2058 + const primaryEnvironmentId = usePrimaryEnvironmentId();
2059 const telemetryOff = managedTelemetryOffMessage(primaryPolicy);
2060 return (
2061 <SettingsPageContainer>
@@ -2085,6 +2091,17 @@ export function AboutSettingsPanel() {
2091 </>
2092 )}
2093 <MobileAppSettingsRow />
2094 + {primaryEnvironmentId === null ? null : (
2095 + <SettingsRow
2096 + {...searchableSetting("welcome-page")}
2097 + description="See your agents, import projects, and set up your phone."
2098 + control={
2099 + <Button size="sm" variant="outline" render={<Link to="/welcome" />}>
2100 + Open
2101 + </Button>
2102 + }
2103 + />
2104 + )}
2105 </SettingsSection>
2106
2107 <SettingsSection id="legal" title="Legal">
apps/web/src/components/settings/settingsSearch.test.ts
+19
@@ -168,6 +168,25 @@ describe("searchSettings", () => {
168 );
169 });
170
171 + it("finds the Welcome page only where a primary computer can open it", () => {
172 + const availability = {
173 + hasCloudPublicConfig: true,
174 + hasEnvironment: true,
175 + hasProviderSettingsEnvironment: true,
176 + canManageLocalBackend: false,
177 + isWslSettingsRowVisible: false,
178 + hasThreadAutoSettlement: false,
179 + };
180 + const ids = (hasPrimaryEnvironment: boolean) =>
181 + searchSettings(
182 + "welcome page",
183 + filterAvailableSettingsSearchItems({ ...availability, hasPrimaryEnvironment }),
184 + ).map((item) => item.id);
185 + // Hosted web reaches remote computers but has no primary one to set up.
186 + expect(ids(false)).not.toContain("welcome-page");
187 + expect(ids(true)).toContain("welcome-page");
188 + });
189 +
190 it("finds keybinding commands by label, command id, and default key", () => {
191 expect(searchSettings("toggle sidebar")[0]?.id).toBe("keybinding-sidebar.toggle");
192 expect(searchSettings("sidebar.toggle")[0]?.id).toBe("keybinding-sidebar.toggle");
apps/web/src/components/settings/settingsSearch.ts
+10
@@ -65,6 +65,7 @@ export interface SettingsSearchItem {
65 readonly providerSettingsOnly?: boolean;
66 readonly localBackendManagementOnly?: boolean;
67 readonly localEnvironmentOnly?: boolean;
68 + readonly primaryEnvironmentOnly?: boolean;
69 readonly wslAvailableOnly?: boolean;
70 readonly managedTunnelOnly?: boolean;
71 readonly peerLinksOnly?: boolean;
@@ -87,6 +88,7 @@ export interface SettingsSearchAvailability {
88 readonly hasFastWorktreeCheckoutEnvironment?: boolean;
89 /** An environment without a provider allow-list, which hides text generators. */
90 readonly hasTextGeneratorsEnvironment?: boolean;
91 + readonly hasPrimaryEnvironment?: boolean;
92 }
93
94 export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
@@ -856,6 +858,13 @@ export const SETTINGS_SEARCH_ITEMS = [
858 to: "/settings/about",
859 searchTerms: ["phone tablet iPhone iPad iOS Android App Store Google Play QR"],
860 },
861 + {
862 + id: "welcome-page",
863 + title: "Welcome page",
864 + to: "/settings/about",
865 + primaryEnvironmentOnly: true,
866 + searchTerms: ["onboarding setup first run getting started agents import projects"],
867 + },
868 {
869 id: "privacy-policy",
870 title: "Privacy policy",
@@ -1460,6 +1469,7 @@ export function filterAvailableSettingsSearchItems(
1469 (!item.providerSettingsOnly || availability.hasProviderSettingsEnvironment) &&
1470 (!item.localBackendManagementOnly || availability.canManageLocalBackend) &&
1471 (!item.localEnvironmentOnly || !availability.localEnvironmentDisabled) &&
1472 + (!item.primaryEnvironmentOnly || availability.hasPrimaryEnvironment === true) &&
1473 (!item.wslAvailableOnly || availability.isWslSettingsRowVisible) &&
1474 (!item.requiresThreadAutoSettlement || availability.hasThreadAutoSettlement) &&
1475 (!item.managedTunnelOnly || availability.managedTunnelActive === true) &&
apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
+1
@@ -72,5 +72,6 @@ export function useAvailableSettingsSearchItems() {
72 hasPeerLinkHost,
73 hasFastWorktreeCheckoutEnvironment,
74 hasTextGeneratorsEnvironment,
75 + hasPrimaryEnvironment: primaryEnvironmentId !== null,
76 });
77 }
apps/web/src/onboarding/projectImport.logic.test.ts
+31 -28
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
3
4 import {
5 groupOnboardingProjects,
6 + isNewOnboardingProject,
7 partitionOnboardingProjects,
8 onboardingProjectKey,
9 resolveOnboardingLandingProject,
@@ -141,6 +142,7 @@ describe("resolveOnboardingProjectId", () => {
142 const localProjectId = ProjectId.make("local-project");
143
144 it("uses the scanned project ID when the client still has an older project at that root", () => {
145 + const scanned = candidate("/projects/repo", { projectId: localProjectId });
146 expect(
147 resolveOnboardingProjectId(
148 [
@@ -151,46 +153,47 @@ describe("resolveOnboardingProjectId", () => {
153 },
154 ],
155 localEnvironmentId,
154 - candidate("/projects/repo", { projectId: localProjectId }),
156 + scanned,
157 ),
158 ).toBe(localProjectId);
159 + expect(isNewOnboardingProject([])(localEnvironmentId, scanned)).toBe(false);
160 });
161
162 it("finds an existing project by normalized root in the target environment", () => {
163 + const projects = [
164 + {
165 + id: ProjectId.make("remote-project"),
166 + environmentId: remoteEnvironmentId,
167 + workspaceRoot: "C:\\Work\\Repo",
168 + },
169 + {
170 + id: localProjectId,
171 + environmentId: localEnvironmentId,
172 + workspaceRoot: "C:\\Work\\Repo\\",
173 + },
174 + ];
175 expect(
161 - resolveOnboardingProjectId(
162 - [
163 - {
164 - id: ProjectId.make("remote-project"),
165 - environmentId: remoteEnvironmentId,
166 - workspaceRoot: "C:\\Work\\Repo",
167 - },
168 - {
169 - id: localProjectId,
170 - environmentId: localEnvironmentId,
171 - workspaceRoot: "C:\\Work\\Repo\\",
172 - },
173 - ],
174 - localEnvironmentId,
175 - candidate("c:/work/repo"),
176 - ),
176 + resolveOnboardingProjectId(projects, localEnvironmentId, candidate("c:/work/repo")),
177 ).toBe(localProjectId);
178 + expect(isNewOnboardingProject(projects)(localEnvironmentId, candidate("c:/work/repo"))).toBe(
179 + false,
180 + );
181 });
182
183 it("does not reuse a project from another environment", () => {
184 + const projects = [
185 + {
186 + id: ProjectId.make("remote-project"),
187 + environmentId: remoteEnvironmentId,
188 + workspaceRoot: "/projects/repo",
189 + },
190 + ];
191 expect(
182 - resolveOnboardingProjectId(
183 - [
184 - {
185 - id: ProjectId.make("remote-project"),
186 - environmentId: remoteEnvironmentId,
187 - workspaceRoot: "/projects/repo",
188 - },
189 - ],
190 - localEnvironmentId,
191 - candidate("/projects/repo"),
192 - ),
192 + resolveOnboardingProjectId(projects, localEnvironmentId, candidate("/projects/repo")),
193 ).toBeNull();
194 + expect(isNewOnboardingProject(projects)(localEnvironmentId, candidate("/projects/repo"))).toBe(
195 + true,
196 + );
197 });
198 });
199
apps/web/src/onboarding/projectImport.logic.ts
+30 -1
@@ -1,4 +1,7 @@
1 -import { findProjectByPath } from "@t3tools/client-runtime/state/projects";
1 +import {
2 + findProjectByPath,
3 + normalizeProjectPathForComparison,
4 +} from "@t3tools/client-runtime/state/projects";
5 import type { AgentSessionProjectCandidate, EnvironmentId, ProjectId } from "@t3tools/contracts";
6
7 const RECENT_PROJECT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
@@ -101,6 +104,32 @@ export function resolveOnboardingProjectId(
104 return null;
105 }
106
107 +/**
108 + * Whether a candidate is not a project yet, by the same rules as `resolveOnboardingProjectId`.
109 + * It reads the project list once, so a long candidate list costs one pass, not one per candidate.
110 + */
111 +export function isNewOnboardingProject(
112 + projects: ReadonlyArray<{
113 + readonly environmentId: EnvironmentId;
114 + readonly workspaceRoot: string;
115 + }>,
116 +) {
117 + const roots = new Set(
118 + projects.map(
119 + (project) =>
120 + `${project.environmentId}\u0000${normalizeProjectPathForComparison(project.workspaceRoot)}`,
121 + ),
122 + );
123 + return (
124 + environmentId: EnvironmentId,
125 + candidate: Pick<AgentSessionProjectCandidate, "path" | "projectId">,
126 + ) => {
127 + if (candidate.projectId !== undefined) return false;
128 + const path = normalizeProjectPathForComparison(candidate.path);
129 + return path.length === 0 || !roots.has(`${environmentId}\u0000${path}`);
130 + };
131 +}
132 +
133 export function resolveOnboardingLandingProject<T>(
134 selection: ReadonlyArray<string>,
135 projectsWithImportedHistory: ReadonlyMap<string, T>,
apps/web/src/onboarding/providerReadiness.logic.test.ts
-44
@@ -9,7 +9,6 @@ import { describe, expect, it } from "vite-plus/test";
9 import {
10 getOnboardingProviderState,
11 resolveOnboardingProviderLoginCommand,
12 - selectOnboardingProvidersByDriver,
12 } from "./providerReadiness.logic";
13
14 const readyCodex: ServerProvider = {
@@ -73,49 +72,6 @@ describe("getOnboardingProviderState", () => {
72 });
73 });
74
76 -describe("selectOnboardingProvidersByDriver", () => {
77 - it("prefers a ready instance with unknown authentication to an unauthenticated instance", () => {
78 - const signedOutCodex: ServerProvider = {
79 - ...readyCodex,
80 - instanceId: ProviderInstanceId.make("codex_work"),
81 - status: "error",
82 - auth: { status: "unauthenticated" },
83 - };
84 -
85 - expect(selectOnboardingProvidersByDriver([signedOutCodex, readyCodex]).get("codex")).toBe(
86 - readyCodex,
87 - );
88 - });
89 -
90 - it("prefers a provider with an actionable sign-in over a failed provider", () => {
91 - const failedCodex: ServerProvider = { ...readyCodex, status: "error" };
92 - const signedOutCodex: ServerProvider = {
93 - ...readyCodex,
94 - instanceId: ProviderInstanceId.make("codex_work"),
95 - status: "error",
96 - auth: { status: "unauthenticated" },
97 - };
98 -
99 - expect(selectOnboardingProvidersByDriver([failedCodex, signedOutCodex]).get("codex")).toBe(
100 - signedOutCodex,
101 - );
102 - });
103 -
104 - it("prefers installed providers over missing or disabled instances", () => {
105 - const disabledCodex: ServerProvider = { ...readyCodex, enabled: false };
106 - const missingCodex: ServerProvider = {
107 - ...readyCodex,
108 - instanceId: ProviderInstanceId.make("codex_work"),
109 - installed: false,
110 - status: "error",
111 - };
112 -
113 - expect(
114 - selectOnboardingProvidersByDriver([disabledCodex, missingCodex, readyCodex]).get("codex"),
115 - ).toBe(readyCodex);
116 - });
117 -});
118 -
75 describe("resolveOnboardingProviderLoginCommand", () => {
76 it("uses the selected Codex account binary", () => {
77 const provider = { ...readyCodex, instanceId: ProviderInstanceId.make("codex_work") };
apps/web/src/onboarding/providerReadiness.logic.ts
-28
@@ -44,34 +44,6 @@ export function getOnboardingProviderState(provider: ServerProvider | undefined)
44 return "attention";
45 }
46
47 -const PROVIDER_STATE_PRIORITY = {
48 - checking: 0,
49 - disabled: 1,
50 - install: 2,
51 - attention: 3,
52 - signIn: 4,
53 - ready: 5,
54 -} as const;
55 -
56 -export function selectOnboardingProvidersByDriver(
57 - providers: ReadonlyArray<ServerProvider> | null | undefined,
58 -) {
59 - const providersByDriver = new Map<string, ServerProvider>();
60 -
61 - for (const provider of providers ?? []) {
62 - const existing = providersByDriver.get(provider.driver);
63 - if (
64 - existing === undefined ||
65 - PROVIDER_STATE_PRIORITY[getOnboardingProviderState(provider)] >
66 - PROVIDER_STATE_PRIORITY[getOnboardingProviderState(existing)]
67 - ) {
68 - providersByDriver.set(provider.driver, provider);
69 - }
70 - }
71 -
72 - return providersByDriver;
73 -}
74 -
47 // These need no Node/npm and install where provider maintenance recognizes native binaries.
48 const NATIVE_INSTALL_COMMANDS = {
49 claudeAgent: {
apps/web/src/onboarding/targetEnvironment.logic.test.ts deleted
-51
@@ -1,51 +0,0 @@
1 -import { EnvironmentId } from "@t3tools/contracts";
2 -import { describe, expect, it } from "vite-plus/test";
3 -
4 -import { resolveOnboardingSetup } from "./targetEnvironment.logic";
5 -
6 -describe("resolveOnboardingSetup", () => {
7 - const computer = (id: string, phase: string) => ({
8 - environmentId: EnvironmentId.make(id),
9 - connection: { phase },
10 - });
11 - const local = computer("local", "connected");
12 -
13 - it("skips selected computers that will not connect on their own", () => {
14 - const environments = [
15 - local,
16 - computer("switched-off", "available"),
17 - computer("offline", "offline"),
18 - computer("failing", "reconnecting"),
19 - computer("old-client", "unsupported"),
20 - ];
21 - expect(
22 - resolveOnboardingSetup(
23 - environments,
24 - new Set(environments.map((environment) => environment.environmentId)),
25 - ),
26 - ).toEqual({
27 - ready: true,
28 - environmentIds: [local.environmentId],
29 - skippedIds: environments.slice(1).map((environment) => environment.environmentId),
30 - });
31 - });
32 -
33 - it("waits for a first connection attempt to settle", () => {
34 - const connecting = computer("new", "connecting");
35 - expect(
36 - resolveOnboardingSetup(
37 - [local, connecting],
38 - new Set([local.environmentId, connecting.environmentId]),
39 - ).ready,
40 - ).toBe(false);
41 - });
42 -
43 - // regression: #16887 onboarding Continue locked up on computers that won't connect
44 - it("is not ready without a connected selection", () => {
45 - expect(resolveOnboardingSetup([local], new Set()).ready).toBe(false);
46 - expect(
47 - resolveOnboardingSetup([computer("off", "available")], new Set([EnvironmentId.make("off")]))
48 - .ready,
49 - ).toBe(false);
50 - });
51 -});
apps/web/src/onboarding/targetEnvironment.logic.ts deleted
-37
@@ -1,37 +0,0 @@
1 -import { type ConnectionCatalogEntry, hasRelayRoute } from "@t3tools/client-runtime/connection";
2 -import type { EnvironmentId } from "@t3tools/contracts";
3 -
4 -interface OnboardingEnvironment {
5 - readonly environmentId: EnvironmentId;
6 - readonly connection: { readonly phase: string };
7 - readonly entry: Pick<ConnectionCatalogEntry, "target" | "alternateRoutes">;
8 -}
9 -
10 -export function isOnboardingRelayEnvironment(
11 - environment: Pick<OnboardingEnvironment, "entry">,
12 -): boolean {
13 - return hasRelayRoute(environment.entry);
14 -}
15 -
16 -/** Waits only for first connection attempts; offline, failing, or unsupported computers cannot block setup. */
17 -export function resolveOnboardingSetup(
18 - environments: ReadonlyArray<Pick<OnboardingEnvironment, "environmentId" | "connection">>,
19 - selectedIds: ReadonlySet<EnvironmentId>,
20 -): {
21 - readonly ready: boolean;
22 - readonly environmentIds: ReadonlyArray<EnvironmentId>;
23 - readonly skippedIds: ReadonlyArray<EnvironmentId>;
24 -} {
25 - const selected = environments.filter((environment) => selectedIds.has(environment.environmentId));
26 - const idsInPhase = (keep: (phase: string) => boolean) =>
27 - selected
28 - .filter((environment) => keep(environment.connection.phase))
29 - .map((environment) => environment.environmentId);
30 - const environmentIds = idsInPhase((phase) => phase === "connected");
31 - const settling = selected.some((environment) => environment.connection.phase === "connecting");
32 - return {
33 - ready: environmentIds.length > 0 && !settling,
34 - environmentIds,
35 - skippedIds: idsInPhase((phase) => phase !== "connected" && phase !== "connecting"),
36 - };
37 -}
apps/web/src/onboarding/welcomePage.logic.test.ts new
+265
@@ -0,0 +1,265 @@
1 +import {
2 + type ManagedPolicySummary,
3 + ProjectId,
4 + resolveProviderInstanceEnabled,
5 + ProviderDriverKind,
6 + ProviderInstanceId,
7 + type ServerProvider,
8 + type ServerSettings,
9 +} from "@t3tools/contracts";
10 +import { describe, expect, it } from "vite-plus/test";
11 +
12 +import {
13 + cliTerminalStep,
14 + codexCardProvider,
15 + codexNeedsSetup,
16 + groupWelcomeAgents,
17 + turnedOnInstance,
18 + welcomeOffersPhone,
19 +} from "./welcomePage.logic";
20 +
21 +function provider(name: string, overrides: Partial<ServerProvider> = {}): ServerProvider {
22 + return {
23 + instanceId: ProviderInstanceId.make(name.toLowerCase()),
24 + driver: ProviderDriverKind.make(name.toLowerCase()),
25 + displayName: name,
26 + enabled: true,
27 + installed: true,
28 + version: "1.0.0",
29 + status: "ready",
30 + auth: { status: "authenticated" },
31 + checkedAt: "2026-08-23T00:00:00.000Z",
32 + models: [],
33 + slashCommands: [],
34 + skills: [],
35 + ...overrides,
36 + };
37 +}
38 +
39 +const nameOf = (entry: ServerProvider) => entry.displayName ?? entry.driver;
40 +const names = (entries: ReadonlyArray<ServerProvider>) => entries.map(nameOf);
41 +const allowAll = () => true;
42 +
43 +describe("groupWelcomeAgents", () => {
44 + it("lists agents on the computer by state, then name, and everything else by name", () => {
45 + const groups = groupWelcomeAgents(
46 + [
47 + provider("Zeta", { auth: { status: "unauthenticated" }, status: "error" }),
48 + provider("Codex"),
49 + provider("Pi", { enabled: false, status: "disabled" }),
50 + provider("Grok", { installed: false, status: "error", auth: { status: "unknown" } }),
51 + provider("Claude"),
52 + provider("Cursor", { installed: false, status: "warning", auth: { status: "unknown" } }),
53 + ],
54 + undefined,
55 + nameOf,
56 + allowAll,
57 + );
58 +
59 + expect(names(groups.found)).toEqual(["Claude", "Codex", "Zeta"]);
60 + // Cursor is still being checked; it stays listed instead of disappearing.
61 + expect(names(groups.available)).toEqual(["Cursor", "Grok", "Pi"]);
62 + expect(groups.checking).toBe(true);
63 + expect(groups.readyCount).toBe(2);
64 + });
65 +
66 + it("uses this computer's settings and keeps agents that failed to load with the found ones", () => {
67 + const acpRegistry = ProviderDriverKind.make("acpRegistry");
68 + const settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides"> = {
69 + providerInstances: {
70 + [ProviderInstanceId.make("pi")]: { driver: ProviderDriverKind.make("pi") },
71 + [ProviderInstanceId.make("registry")]: { driver: acpRegistry },
72 + },
73 + projectSettingsOverrides: {
74 + [ProjectId.make("project-a")]: {
75 + providerInstances: { [ProviderInstanceId.make("pi")]: { enabled: true } },
76 + },
77 + },
78 + };
79 + const groups = groupWelcomeAgents(
80 + [
81 + // The server checks Pi because project A turns it on; new projects still cannot use it.
82 + provider("Pi"),
83 + provider("Broken", {
84 + enabled: false,
85 + installed: false,
86 + status: "error",
87 + availability: "unavailable",
88 + unavailableReason: "Invalid config for instance 'broken'.",
89 + }),
90 + // Signed in and healthy, but the server knows this CLI version is broken.
91 + provider("Codex", {
92 + compatibilityAdvisory: {
93 + status: "broken",
94 + message: "Update Codex to 0.170 or later.",
95 + recommendedVersion: "0.170.0",
96 + recommendedRange: null,
97 + },
98 + }),
99 + // An ACP agent that is not prepared looks like one still being checked.
100 + provider("Registry", {
101 + driver: acpRegistry,
102 + installed: false,
103 + status: "warning",
104 + auth: { status: "unknown" },
105 + }),
106 + ],
107 + settings,
108 + nameOf,
109 + allowAll,
110 + );
111 +
112 + expect(names(groups.found)).toEqual(["Broken", "Codex", "Registry"]);
113 + expect(names(groups.available)).toEqual(["Pi"]);
114 + expect(groups.readyCount).toBe(0);
115 + expect(groups.checking).toBe(false);
116 + });
117 +
118 + it("leaves out agents the computer's policy does not allow, ready or not", () => {
119 + const groups = groupWelcomeAgents(
120 + [provider("Codex"), provider("Blocked")],
121 + undefined,
122 + nameOf,
123 + (entry) => entry.driver !== "blocked",
124 + );
125 +
126 + expect(names(groups.found)).toEqual(["Codex"]);
127 + expect(groups.readyCount).toBe(1);
128 + });
129 +
130 + it("reports checking before the computer has sent its providers", () => {
131 + expect(groupWelcomeAgents(undefined, undefined, nameOf, allowAll)).toEqual({
132 + checking: true,
133 + readyCount: 0,
134 + found: [],
135 + available: [],
136 + });
137 + });
138 +});
139 +
140 +describe("cliTerminalStep", () => {
141 + it("waits for the CLI's own check, then opens its terminal unless Codex is ready", () => {
142 + const codex = (overrides: Partial<ServerProvider> = {}) => provider("Codex", overrides);
143 + const step = (overrides?: Partial<ServerProvider>) =>
144 + cliTerminalStep(codex(overrides), undefined);
145 +
146 + // Still the ChatGPT sign-in runtime, before the switch to the CLI lands.
147 + expect(
148 + step({
149 + setup: { canAuthenticate: true, canInstall: true },
150 + auth: { status: "unauthenticated" },
151 + }),
152 + ).toBe("wait");
153 + expect(step({ installed: false, status: "warning", auth: { status: "unknown" } })).toBe("wait");
154 + expect(step({ installed: false, status: "error", auth: { status: "unknown" } })).toBe("open");
155 + expect(step({ auth: { status: "unauthenticated" } })).toBe("open");
156 + // A check that timed out still gets the sign-in command.
157 + expect(step({ status: "error", auth: { status: "unknown" } })).toBe("open");
158 + // A broken version is updated from its row in Settings, signed in, signed out, or unchecked.
159 + const broken = {
160 + status: "broken",
161 + message: "Update Codex.",
162 + recommendedVersion: null,
163 + recommendedRange: null,
164 + } as const;
165 + expect(step({ compatibilityAdvisory: broken })).toBe("done");
166 + expect(step({ compatibilityAdvisory: broken, auth: { status: "unauthenticated" } })).toBe(
167 + "done",
168 + );
169 + expect(
170 + step({ compatibilityAdvisory: broken, status: "error", auth: { status: "unknown" } }),
171 + ).toBe("done");
172 + // Signed in but needing a look for another reason: a sign-in would not help.
173 + expect(step({ status: "warning" })).toBe("done");
174 + // Signed in from its home files with the binary gone: the installer.
175 + expect(step({ installed: false, status: "error" })).toBe("open");
176 + expect(step()).toBe("done");
177 + });
178 +});
179 +
180 +describe("turnedOnInstance", () => {
181 + it("turns an agent on even when older settings keep it off inside its config", () => {
182 + const pi = ProviderDriverKind.make("pi");
183 + expect(resolveProviderInstanceEnabled(turnedOnInstance({ driver: pi }))).toBe(true);
184 + const migrated = turnedOnInstance({ driver: pi, config: { enabled: false, binaryPath: "pi" } });
185 + expect(resolveProviderInstanceEnabled(migrated)).toBe(true);
186 + expect(migrated.config).toEqual({ enabled: true, binaryPath: "pi" });
187 + });
188 +});
189 +
190 +describe("codexNeedsSetup", () => {
191 + it("opens the setup card only while Codex is not signed in", () => {
192 + const setup = (overrides: Partial<ServerProvider>) =>
193 + codexNeedsSetup(provider("Codex", overrides), undefined);
194 +
195 + expect(setup({ installed: false, status: "error", auth: { status: "unknown" } })).toBe(true);
196 + expect(setup({ auth: { status: "unauthenticated" } })).toBe(true);
197 + // A check that timed out can still sign in with ChatGPT.
198 + expect(setup({ status: "error", auth: { status: "unknown" } })).toBe(true);
199 + // Signed in from its home files but the binary is gone: Install, not the card.
200 + expect(setup({ installed: false, status: "error" })).toBe(false);
201 + // A broken version gets Update on its row.
202 + expect(
203 + setup({
204 + auth: { status: "unauthenticated" },
205 + compatibilityAdvisory: {
206 + status: "broken",
207 + message: null,
208 + recommendedVersion: null,
209 + recommendedRange: null,
210 + },
211 + }),
212 + ).toBe(false);
213 + expect(setup({})).toBe(false);
214 + const claude = provider("Claude", { auth: { status: "unauthenticated" } });
215 + expect(codexNeedsSetup(claude, undefined)).toBe(false);
216 + });
217 +});
218 +
219 +describe("codexCardProvider", () => {
220 + it("keeps the card on Codex's last status while a rebuild drops it, and closes once signed in", () => {
221 + const signedOut = provider("Codex", { auth: { status: "unauthenticated" } });
222 + const card = (providers: ReadonlyArray<ServerProvider>, last: ServerProvider | null = null) =>
223 + codexCardProvider({ providers, instanceId: signedOut.instanceId, last, settings: undefined });
224 +
225 + expect(card([signedOut])).toBe(signedOut);
226 + // The instance is missing for one update while it is rebuilt.
227 + expect(card([], signedOut)).toBe(signedOut);
228 + expect(card([], provider("Other"))).toBeNull();
229 + expect(card([provider("Codex")])).toBeNull();
230 + expect(
231 + codexCardProvider({
232 + providers: [signedOut],
233 + instanceId: null,
234 + last: null,
235 + settings: undefined,
236 + }),
237 + ).toBeNull();
238 + });
239 +});
240 +
241 +describe("welcomeOffersPhone", () => {
242 + it("offers the phone only through T3 Connect on the primary computer, and only when allowed", () => {
243 + const policy = (limits: ManagedPolicySummary["limits"]): ManagedPolicySummary => ({
244 + organization: "Acme",
245 + lockedSettings: [],
246 + ...(limits === undefined ? {} : { limits }),
247 + });
248 + const offers = (input: Partial<Parameters<typeof welcomeOffersPhone>[0]>) =>
249 + welcomeOffersPhone({
250 + isPrimary: true,
251 + cloud: true,
252 + canShare: true,
253 + policy: undefined,
254 + ...input,
255 + });
256 +
257 + expect(offers({})).toBe(true);
258 + // There is no pairing-code fallback; without T3 Connect the page leaves the phone out.
259 + expect(offers({ cloud: false })).toBe(false);
260 + expect(offers({ canShare: false })).toBe(false);
261 + expect(offers({ policy: policy({ connect: false }) })).toBe(false);
262 + expect(offers({ policy: policy({ clients: ["desktop"] }) })).toBe(false);
263 + expect(offers({ isPrimary: false })).toBe(false);
264 + });
265 +});
apps/web/src/onboarding/welcomePage.logic.ts new
+180
@@ -0,0 +1,180 @@
1 +import {
2 + isProviderAvailable,
3 + managedCapabilityDenial,
4 + type ManagedPolicySummary,
5 + type ProviderInstanceConfig,
6 + ProviderDriverKind,
7 + type ProviderInstanceId,
8 + resolveProjectProviderInstanceEnabled,
9 + type ServerProvider,
10 + type ServerSettings,
11 +} from "@t3tools/contracts";
12 +
13 +import { getOnboardingProviderState } from "./providerReadiness.logic";
14 +
15 +type ComputerSettings = Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">;
16 +
17 +// Ready agents first, then ones that need a sign-in or a look. Never ranked by vendor.
18 +const FOUND_ORDER = { ready: 0, signIn: 1, attention: 2 } as const;
19 +type FoundState = keyof typeof FOUND_ORDER;
20 +
21 +const isFoundState = (state: string): state is FoundState => state in FOUND_ORDER;
22 +
23 +const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry");
24 +
25 +/**
26 + * An agent's state for new threads on this computer. The server also lists agents that only some
27 + * projects turn on, lists an agent it could not load as off, which Turn on cannot fix, and can pass
28 + * a CLI whose version it knows is broken.
29 + */
30 +export function welcomeAgentState(
31 + provider: ServerProvider,
32 + settings: ComputerSettings | null | undefined,
33 +) {
34 + if (!isProviderAvailable(provider)) return "attention";
35 + if (settings && !resolveProjectProviderInstanceEnabled(settings, null, provider.instanceId)) {
36 + return "disabled";
37 + }
38 + const state = getOnboardingProviderState(provider);
39 + if (state === "ready" && provider.compatibilityAdvisory?.status === "broken") return "attention";
40 + // An ACP agent that is not prepared reports the same fields as one still being checked.
41 + return state === "checking" && provider.driver === ACP_REGISTRY_DRIVER ? "attention" : state;
42 +}
43 +
44 +/**
45 + * Splits a computer's allowed providers into agents already on it and agents the user can add.
46 + * Order inside each group is by state, then by the name the user sees. Agents still being
47 + * checked are listed with the ones to add, so a slow check never drops an agent.
48 + */
49 +export function groupWelcomeAgents(
50 + providers: ReadonlyArray<ServerProvider> | null | undefined,
51 + settings: ComputerSettings | null | undefined,
52 + nameOf: (provider: ServerProvider) => string,
53 + isAllowed: (provider: ServerProvider) => boolean,
54 +) {
55 + const found: Array<{ readonly provider: ServerProvider; readonly state: FoundState }> = [];
56 + const available: ServerProvider[] = [];
57 + let checking = providers == null;
58 + let readyCount = 0;
59 + for (const provider of providers ?? []) {
60 + if (!isAllowed(provider)) continue;
61 + const state = welcomeAgentState(provider, settings);
62 + if (state === "ready") readyCount += 1;
63 + if (state === "checking") checking = true;
64 + if (isFoundState(state)) found.push({ provider, state });
65 + else available.push(provider);
66 + }
67 + const byName = (a: ServerProvider, b: ServerProvider) => nameOf(a).localeCompare(nameOf(b));
68 + found.sort(
69 + (a, b) => FOUND_ORDER[a.state] - FOUND_ORDER[b.state] || byName(a.provider, b.provider),
70 + );
71 + available.sort(byName);
72 + return { checking, readyCount, found: found.map((entry) => entry.provider), available };
73 +}
74 +
75 +/** Older settings can also keep `enabled: false` inside `config`, which still turns the agent off. */
76 +export function turnedOnInstance(instance: ProviderInstanceConfig): ProviderInstanceConfig {
77 + const { config } = instance;
78 + const configOff =
79 + typeof config === "object" &&
80 + config !== null &&
81 + "enabled" in config &&
82 + config.enabled === false;
83 + return {
84 + ...instance,
85 + enabled: true,
86 + ...(configOff ? { config: { ...config, enabled: true } } : {}),
87 + };
88 +}
89 +
90 +/** A CLI the server knows is too old or otherwise broken for T3 Code; Settings updates it. */
91 +export function isBrokenVersion(provider: ServerProvider) {
92 + return provider.installed && provider.compatibilityAdvisory?.status === "broken";
93 +}
94 +
95 +/**
96 + * What "Use existing CLI" does next for Codex: wait for the CLI's own check, open its terminal,
97 + * or stop. Only the ChatGPT sign-in runtime reports `setup.canAuthenticate`.
98 + */
99 +export function cliTerminalStep(
100 + provider: ServerProvider,
101 + settings: ComputerSettings | null | undefined,
102 +) {
103 + if (provider.setup?.canAuthenticate === true) return "wait";
104 + const state = welcomeAgentState(provider, settings);
105 + if (state === "checking") return "wait";
106 + // A broken version is updated from its row, and an installed, signed-in CLI needs no terminal.
107 + if (isBrokenVersion(provider)) return "done";
108 + if (provider.installed && provider.auth.status === "authenticated") return "done";
109 + // The terminal shows the command first, so it also helps a CLI whose check failed.
110 + const fixable =
111 + state === "install" ||
112 + state === "signIn" ||
113 + (state === "attention" && isProviderAvailable(provider));
114 + return fixable ? "open" : "done";
115 +}
116 +
117 +/**
118 + * Whether Codex's row opens its setup card, which offers ChatGPT sign-in or the CLI. A signed-in
119 + * or broken Codex gets its plain row action instead, since the card has nothing left for it.
120 + */
121 +export function codexNeedsSetup(
122 + provider: ServerProvider,
123 + settings: ComputerSettings | null | undefined,
124 +) {
125 + if (
126 + provider.driver !== "codex" ||
127 + provider.auth.status === "authenticated" ||
128 + isBrokenVersion(provider)
129 + ) {
130 + return false;
131 + }
132 + const state = welcomeAgentState(provider, settings);
133 + return (
134 + state === "install" ||
135 + state === "signIn" ||
136 + (state === "attention" && isProviderAvailable(provider))
137 + );
138 +}
139 +
140 +/**
141 + * The phone joins by signing in to T3 Connect, which shares the primary computer. Another
142 + * computer, a build without T3 Connect, or a policy that turns it off gets no Phone section.
143 + */
144 +export function welcomeOffersPhone(input: {
145 + readonly isPrimary: boolean;
146 + readonly cloud: boolean;
147 + // Relay read and write access, which sharing this computer through T3 Connect needs.
148 + readonly canShare: boolean;
149 + readonly policy: ManagedPolicySummary | undefined;
150 +}) {
151 + return (
152 + input.isPrimary &&
153 + input.cloud &&
154 + input.canShare &&
155 + managedCapabilityDenial(input.policy, "remoteClients") === undefined &&
156 + managedCapabilityDenial(input.policy, "connect") === undefined
157 + );
158 +}
159 +
160 +/**
161 + * The Codex instance the setup card shows, or null when the card is closed. A rebuild briefly
162 + * drops an instance from the list, so the card keeps its last status meanwhile instead of
163 + * unmounting and losing a sign-in in progress.
164 + */
165 +export function codexCardProvider(input: {
166 + readonly providers: ReadonlyArray<ServerProvider> | null | undefined;
167 + readonly instanceId: ProviderInstanceId | null;
168 + readonly last: ServerProvider | null;
169 + readonly settings: ComputerSettings | null | undefined;
170 +}) {
171 + if (input.instanceId === null) return null;
172 + const provider =
173 + input.providers?.find((candidate) => candidate.instanceId === input.instanceId) ??
174 + (input.last?.instanceId === input.instanceId ? input.last : undefined);
175 + if (provider === undefined) return null;
176 + const open =
177 + codexNeedsSetup(provider, input.settings) ||
178 + welcomeAgentState(provider, input.settings) === "checking";
179 + return open ? provider : null;
180 +}
apps/web/src/onboarding/welcomeState.ts new
+20
@@ -0,0 +1,20 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import * as Schema from "effect/Schema";
3 +
4 +/**
5 + * A computer's project choices on the Welcome page. They are stored until setup finishes, so a
6 + * visit to Settings or an app restart during setup keeps them.
7 + */
8 +export const WelcomeImportSelection = Schema.Struct({
9 + // Projects listed when the selection changed; projects found later get the defaults.
10 + knownKeys: Schema.Array(Schema.String),
11 + keys: Schema.Array(Schema.String),
12 + // Unchecking the main box also leaves out projects found later, until it is checked again.
13 + optedOut: Schema.Boolean,
14 +});
15 +export type WelcomeImportSelection = typeof WelcomeImportSelection.Type;
16 +
17 +export const StoredWelcomeImportSelection = Schema.NullOr(WelcomeImportSelection);
18 +
19 +export const welcomeImportSelectionKey = (environmentId: EnvironmentId) =>
20 + `t3code:welcome-import-selection:${environmentId}`;
apps/web/src/routes/__root.tsx
+45 -45
@@ -165,29 +165,38 @@ function RootRouteBranch() {
165 return hostedPromptLinkLanding;
166 }
167
168 - if (pathname === "/welcome") {
169 - return (
170 - <>
171 - <CustomSnoozeDialogHost />
172 - <GuestShareDialogHost />
173 - <UseInAnotherAppDialogHost />
174 - <RelayClientInstallDialog />
175 - <CommandPalette>
176 - <AppSidebarLayout>
177 - <Outlet />
178 - </AppSidebarLayout>
179 - </CommandPalette>
180 - </>
181 - );
182 - }
183 -
168 + const isWelcome = pathname === "/welcome";
169 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
170 return <Outlet />;
171 }
172
173 + // Settings can reopen /welcome mid-session, so it mounts everything the app does except the
174 + // first-run gate and the event router, whose first navigation would leave the page.
175 + const appHosts = (
176 + <>
177 + {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
178 + {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? (
179 + <DesktopWebLinkCoordinator />
180 + ) : null}
181 + {isElectron ? <RunningThreadKeepAlive /> : null}
182 + <RelayClientInstallDialog />
183 + <ConnectOnboardingDialog />
184 + <SshPasswordPromptDialog />
185 + <SnapShotCoordinator />
186 + <ReopenClosedViewShortcut />
187 + <ConfirmDialogHost />
188 + <CustomSnoozeDialogHost />
189 + <GuestShareDialogHost />
190 + <ProjectCloneToastCoordinator />
191 + <AddProjectToMachineDialogHost />
192 + <UseInAnotherAppDialogHost />
193 + {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
194 + </>
195 + );
196 const appShell = (
197 <CommandPalette>
190 - <AppSidebarLayout>
198 + {/* Setup starts with an empty workspace, so the Welcome page has no thread list. */}
199 + <AppSidebarLayout showSidebar={!isWelcome}>
200 <Outlet />
201 </AppSidebarLayout>
202 </CommandPalette>
@@ -196,34 +205,25 @@ function RootRouteBranch() {
205 return (
206 <>
207 <ChatGptWelcomeCoordinator />
199 - <FirstRunGate
200 - enabled={primaryEnvironmentAuthenticated}
201 - hostedStatic={authGateState.status === "hosted-static"}
202 - >
203 - {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
204 - {primaryEnvironmentAuthenticated || localEnvironmentDisabled ? (
205 - <DesktopWebLinkCoordinator />
206 - ) : null}
207 - {isElectron ? <RunningThreadKeepAlive /> : null}
208 - <RelayClientInstallDialog />
209 - <ConnectOnboardingDialog />
210 - <SshPasswordPromptDialog />
211 - <SnapShotCoordinator />
212 - <ReopenClosedViewShortcut />
213 - <ConfirmDialogHost />
214 - <CustomSnoozeDialogHost />
215 - <GuestShareDialogHost />
216 - <ProjectCloneToastCoordinator />
217 - <AddProjectToMachineDialogHost />
218 - <UseInAnotherAppDialogHost />
219 - {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
220 - {primaryEnvironmentAuthenticated ? (
221 - <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
222 - ) : null}
223 - {appShell}
224 - {/* Keep the theme editor above the router so drafts survive navigation. */}
225 - <ThemeEditorHost />
226 - </FirstRunGate>
208 + {isWelcome ? (
209 + <>
210 + {appHosts}
211 + {appShell}
212 + </>
213 + ) : (
214 + <FirstRunGate
215 + enabled={primaryEnvironmentAuthenticated}
216 + hostedStatic={authGateState.status === "hosted-static"}
217 + >
218 + {appHosts}
219 + {primaryEnvironmentAuthenticated ? (
220 + <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
221 + ) : null}
222 + {appShell}
223 + </FirstRunGate>
224 + )}
225 + {/* Above both shells and the router, so drafts survive navigation, including to /welcome. */}
226 + <ThemeEditorHost />
227 </>
228 );
229 }
apps/web/src/routes/welcome.tsx
+28 -22
@@ -5,8 +5,9 @@ import * as Schema from "effect/Schema";
5 import * as Option from "effect/Option";
6
7 import { NoProjectsHero } from "../components/NoProjectsHero";
8 -import { WelcomeWizard } from "../components/onboarding/WelcomeWizard";
8 +import { WelcomePage } from "../components/onboarding/WelcomePage";
9 import { useNewThreadHandler } from "../hooks/useHandleNewThread";
10 +import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
11
12 const decodeEnvironmentId = Schema.decodeOption(EnvironmentId);
13
@@ -21,36 +22,41 @@ export const Route = createFileRoute("/welcome")({
22 });
23
24 function WelcomeRouteView() {
24 - const { authGateState } = Route.useRouteContext();
25 const navigate = useNavigate();
26 const hash = useLocation({ select: (location) => location.hash });
27 + // A ChatGPT sign-in returns here with the computer it set up.
28 const resumeEnvironmentId = hash.startsWith("agents:")
29 ? Option.getOrUndefined(decodeEnvironmentId(hash.slice("agents:".length)))
30 : undefined;
31 + const primaryEnvironmentId = usePrimaryEnvironmentId();
32 + const { environments, isReady } = useEnvironments();
33 + // Trust the id only once the catalog has it; an unknown computer falls back to this one.
34 + const waitingForCatalog =
35 + !isReady && (resumeEnvironmentId !== undefined || primaryEnvironmentId === null);
36 + const resumeKnown =
37 + resumeEnvironmentId !== undefined &&
38 + environments.some((environment) => environment.environmentId === resumeEnvironmentId);
39 + const environmentId = (resumeKnown ? resumeEnvironmentId : undefined) ?? primaryEnvironmentId;
40 // The root can remount this pending outlet after navigation; do not reopen setup.
41 const isWelcomeRoute = useLocation({ select: (location) => location.pathname === "/welcome" });
42 const [dismissed, setDismissed] = useState(false);
43 const openNewThread = useNewThreadHandler();
34 - const localAvailable = authGateState.status === "authenticated";
44 + if (waitingForCatalog) return null;
45 + if (environmentId === null || !isWelcomeRoute || dismissed) return <NoProjectsHero />;
46 return (
36 - <>
37 - <NoProjectsHero />
38 - {isWelcomeRoute && !dismissed ? (
39 - <WelcomeWizard
40 - localAvailable={localAvailable}
41 - resumeEnvironmentId={resumeEnvironmentId}
42 - onDone={async (projectRef) => {
43 - setDismissed(true);
44 - if (projectRef !== undefined) {
45 - await openNewThread(projectRef, { replace: true }).catch(() =>
46 - navigate({ to: "/", replace: true }),
47 - );
48 - return;
49 - }
50 - await navigate({ to: "/", replace: true });
51 - }}
52 - />
53 - ) : null}
54 - </>
47 + <WelcomePage
48 + key={environmentId}
49 + environmentId={environmentId}
50 + onDone={async (projectRef) => {
51 + setDismissed(true);
52 + if (projectRef !== undefined) {
53 + await openNewThread(projectRef, { replace: true }).catch(() =>
54 + navigate({ to: "/", replace: true }),
55 + );
56 + return;
57 + }
58 + await navigate({ to: "/", replace: true });
59 + }}
60 + />
61 );
62 }
docs/user/install.md
+1 -1
@@ -134,7 +134,7 @@ on first launch; after an update, or any time, choose **Install** next to
134 **t3 command** in **Settings → About**. On macOS and Linux it adds a `t3` link
135 in `~/.local/bin` (or `~/bin`); on Windows it adds the app's command folder to
136 your `PATH`. Open a new terminal afterwards. If the folder is not on your
137 -`PATH`, **Add to PATH** in the welcome setup or **Settings → About** adds one
137 +`PATH`, **Add to PATH** on the Welcome page or in **Settings → About** adds one
138 line to your shell's startup file. **Remove** takes it off, and the app does not
139 add it again. If you already have another `t3`, it stays as it is.
140
docs/user/welcome-page.md new
+111
@@ -0,0 +1,111 @@
1 +# Welcome page
2 +
3 +T3 Code shows a Welcome page when you open a new installation. Existing
4 +workspaces skip it. It shows what T3 Code found on the computer you are using,
5 +on one page: your agents, projects from your Claude Code, Codex, and Pi history,
6 +and the phone app. Only an agent is needed to start chatting.
7 +
8 +To see the page again, go to **Settings → About → Welcome page** and select
9 +**Open**. Direct links, such as Settings, open normally before setup is done.
10 +
11 +The hosted app at app.t3.codes does not open the page. With no computer connected,
12 +it asks you to sign in to T3 Connect, then to install T3 Code and run
13 +`t3 connect` on your computer. From home, it adds compatible computers linked to your account and
14 +opens the app. To add more computers later, use **Settings → Environments**.
15 +
16 +If T3 Code cannot confirm the workspace during startup, it shows
17 +**Still connecting** instead of opening the app. Select **Reload** to try again.
18 +
19 +If T3 Code cannot read your saved settings, it shows **Could not read settings**.
20 +Select **Retry** after storage becomes available. Setup does not replace
21 +unreadable settings with defaults.
22 +
23 +## Agents
24 +
25 +T3 Code lists the agents it found on the computer first, ready ones on top.
26 +**Add more agents** lists every other agent T3 Code supports, A to Z. When no agent
27 +is found, it reads **Set up an agent** and opens by itself:
28 +
29 +- **Turn on** enables an agent that is off on this computer, including one only
30 + some projects use. T3 Code then checks whether it is installed and signed in.
31 +- For Claude Code, **Install** or **Sign in** opens a terminal with the correct
32 + command ready to run. Install uses the vendor's own installer, which keeps
33 + **Update now** working in Settings.
34 +- For Codex, **Set up** offers sign-in with your ChatGPT account or your own
35 + Codex CLI. **Use existing CLI** opens the terminal to install or sign in, and
36 + **Continue with ChatGPT** stays available until Codex is signed in.
37 +- When T3 Code knows an installed version does not work with it, **Update** opens
38 + the agent in **Settings → Providers**, which shows the version to use and updates it
39 + when it can.
40 +- Other agents, and agents that could not load, open their page in
41 + **Settings → Providers**.
42 +- **Browse** opens the ACP Registry for more agents.
43 +
44 +On the desktop app, when the folder of the `t3` command is not on your `PATH`,
45 +**Add to PATH** adds one line to your shell's startup file.
46 +
47 +The setup terminal uses the home directory and environment configured for the
48 +provider instance. Sensitive values remain redacted in Settings and
49 +terminal metadata while the terminal process can use them.
50 +
51 +**Start** waits for one ready agent. Select **Start without an agent** to finish
52 +without one. Checked projects are still imported.
53 +
54 +## Phone
55 +
56 +Select **Set up** and scan the code with your phone. It opens the App Store on an
57 +iPhone and Google Play on Android. Then select **Sign in to T3 Connect** and allow
58 +this computer when T3 Code asks, so the app can reach it. Sign in to the app with
59 +the same account. If you are signed in but this computer is not shared yet, select
60 +**Set up T3 Connect**. If T3 Connect is on but the app cannot reach this computer,
61 +select **Check T3 Connect** to see why. The page leaves the phone out on builds
62 +without T3 Connect, or when your organization turns it off. You can still pair the
63 +app with a code from **Settings → Sharing & access**.
64 +
65 +## Projects
66 +
67 +T3 Code finds directories that Claude Code, Codex or Pi has used. Git repositories
68 +are listed first, newest activity on top. When the remote is on GitHub, the
69 +group shows the repository as `owner/name`. Clones with the same remote share
70 +one group. Directories that are not git repositories sit under "Other folders".
71 +
72 +The page offers git repositories active within the last 30 days with at least
73 +three conversations, already checked. Projects already in T3 Code are not checked
74 +again. Uncheck the box to start without them, or
75 +select **Review all** to pick from everything found, with "Select all" and
76 +"Select none". Linked worktrees of bare repositories
77 +can be offered as separate projects. Other linked git worktrees, Codex scratch
78 +directories under `Documents/Codex`, and anything under `Downloads` are not
79 +offered.
80 +
81 +A large or malformed history can reach the scan limit. T3 Code keeps the
82 +projects it found and warns when projects or conversations may be missing.
83 +
84 +Imported projects include Claude, Codex and Pi conversations active within the last
85 +30 days. You can continue those conversations in T3 Code. Pi is off by default:
86 +open **Add more agents** and select **Turn on** next to Pi, and the page looks for
87 +its sessions too. Pi sessions
88 +are read from each enabled Pi provider's session directory, which follows
89 +`PI_CODING_AGENT_SESSION_DIR` and `PI_CODING_AGENT_DIR` in its environment. A
90 +Pi conversation imports its active branch, the one Pi reopens.
91 +
92 +Conversation import is best effort. T3 Code keeps the first user prompt and the
93 +newest remaining visible user and assistant messages, with 200 messages total.
94 +It omits tool activity and attachments. For Codex, it omits generated setup
95 +context only when a canonical user event and a valid shared turn ID identify the
96 +same user turn. Ambiguous legacy or response-only context stays in the imported
97 +conversation so T3 Code does not remove user text. It reads one conversation at
98 +a time and skips files larger than 4 GiB. It also skips a conversation when the
99 +message text and metadata it keeps need more than 32 MiB of memory. Tool output
100 +does not count toward that limit. It skips a conversation with more than 100,000
101 +records every time, so opening the page again does not import it. It ignores
102 +malformed records and skips unreadable or unparseable conversations.
103 +
104 +Each import attempt reads up to 100 conversation files and 4 GiB per project. To
105 +continue a large batch, open the Welcome page again and pick the project in
106 +**Review all**. Completed conversations are not imported again. You can continue
107 +without the remaining history.
108 +
109 +You can start without importing. While an import runs, T3 Code stays on the
110 +Welcome page. If you quit, open the Welcome page again from **Settings → About**; the
111 +projects you started stay checked.
docs/user/welcome-wizard.md deleted
-101
@@ -1,101 +0,0 @@
1 -# Welcome wizard
2 -
3 -T3 Code shows a setup flow when you open a new installation. Existing
4 -workspaces skip this flow.
5 -
6 -The hosted app at app.t3.codes does not open setup. With no computer connected,
7 -it asks you to sign in to T3 Connect, then to install T3 Code and run
8 -`t3 connect` on your computer. From home, it adds compatible computers linked to your account and
9 -opens the app.
10 -
11 -Close setup while no import is running to go straight to the app. You can connect
12 -computers and agents later from Settings, or open `/welcome` to run setup again.
13 -Direct links, such as Settings, open normally before setup is done.
14 -
15 -## Connect your computers
16 -
17 -Select one or more computers to set up. If you opened T3 Code directly from a
18 -server or the desktop app, that computer is already connected and selected.
19 -It is identified by its name, which may differ from the device running your
20 -browser.
21 -
22 -You can add more computers before continuing:
23 -
24 -- **T3 Connect** connects computers that are signed in to your account.
25 - [Install the CLI](./install.md#command-line) and run `t3 connect` on each
26 - computer you want to add, then start T3 Code or run `t3 serve` so the
27 - computer stays available.
28 -- **Add a computer** connects directly to a server on your network or tailnet.
29 - Start the server with `t3 serve`, then run `t3 pair --tailscale` and paste
30 - the pairing link. You can also run `t3 serve --host <address>` and use
31 - `t3 pair` when the server is already reachable on your network.
32 -
33 -A computer marked **Client not supported** runs a T3 Code version that cannot
34 -talk to this app. The message under its name says which side to update.
35 -
36 -Saved computers and computers discovered through T3 Connect are selected by
37 -default. Uncheck any you do not want to set up; this does not disconnect them.
38 -Continue when your selected computers are connected. Setup checks
39 -agents across the selected computers, then offers project import grouped by computer.
40 -
41 -If T3 Code cannot confirm the workspace during startup, the setup flow shows
42 -**Still connecting** instead of opening the app. Select **Reload** to try again.
43 -
44 -If T3 Code cannot read your saved settings, it shows **Could not read settings**.
45 -Select **Retry** after storage becomes available. Setup does not replace
46 -unreadable settings with defaults.
47 -
48 -## Check your agents
49 -
50 -T3 Code checks each selected computer for Claude Code and Codex. If an agent is
51 -not installed or signed in, select its action to open a terminal with the
52 -correct command ready to run. Install uses the vendor's own installer, which
53 -keeps **Update now** working in Settings. Other providers can be enabled in
54 -Settings.
55 -
56 -The setup terminal uses the home directory and environment configured for the
57 -selected provider instance. Sensitive values remain redacted in Settings and
58 -terminal metadata while the terminal process can use them.
59 -
60 -## Import your projects
61 -
62 -T3 Code finds directories that Claude Code, Codex or Pi has used. Git repositories
63 -are listed first, newest activity on top. When the remote is on GitHub, the
64 -group shows the repository as `owner/name`. Clones with the same remote share
65 -one group. Directories that are not git repositories sit under "Other folders".
66 -
67 -The default selection includes git repositories active within the last 30 days
68 -with at least three conversations. Use the checkboxes, or "Select all" and
69 -"Select none", to change the selection. Linked worktrees of bare repositories
70 -can be offered as separate projects. Other linked git worktrees, Codex scratch
71 -directories under `Documents/Codex`, and anything under `Downloads` are not
72 -offered.
73 -
74 -A large or malformed history can reach the scan limit. T3 Code keeps the
75 -projects it found and warns when projects or conversations may be missing.
76 -
77 -Imported projects include Claude, Codex and Pi conversations active within the last
78 -30 days. You can continue those conversations in T3 Code. Pi is off by default:
79 -enable it in Settings, then open `/welcome` to import its sessions. Pi sessions
80 -are read from each enabled Pi provider's session directory, which follows
81 -`PI_CODING_AGENT_SESSION_DIR` and `PI_CODING_AGENT_DIR` in its environment. A
82 -Pi conversation imports its active branch, the one Pi reopens.
83 -
84 -Conversation import is best effort. T3 Code keeps the first user prompt and the
85 -newest remaining visible user and assistant messages, with 200 messages total.
86 -It omits tool activity and attachments. For Codex, it omits generated setup
87 -context only when a canonical user event and a valid shared turn ID identify the
88 -same user turn. Ambiguous legacy or response-only context stays in the imported
89 -conversation so T3 Code does not remove user text. It reads one conversation at
90 -a time and skips files larger than 4 GiB. It also skips a conversation when the
91 -message text and metadata it keeps need more than 32 MiB of memory. Tool output
92 -does not count toward that limit. It ignores malformed records and skips
93 -unreadable or unparseable conversations.
94 -
95 -Each import attempt reads up to 100 conversation files and 4 GiB per project,
96 -with up to 100,000 input records. Run import again to continue a large batch.
97 -Completed conversations are not imported again. You can continue without the
98 -remaining history.
99 -
100 -You can continue without configuring agents or importing projects, or return to an earlier step
101 -using the setup progress bar. Navigation pauses while an import is running.