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

WelcomeWizard.tsx

1,340 lines49.2 KB

1import { useAuth } from "@clerk/react";
2import { useAtomValue } from "@effect/atom-react";
3import type {
4 EnvironmentId,
5 ProjectId,
6 ScopedProjectRef,
7 ServerConfig,
8 ServerProvider,
9} from "@t3tools/contracts";
10import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
11import {
12 isAtomCommandInterrupted,
13 squashAtomCommandFailure,
14} from "@t3tools/client-runtime/state/runtime";
15import { CommandId, ProviderDriverKind, ThreadId } from "@t3tools/contracts";
16import * as Schema from "effect/Schema";
17import {
18 ArrowRightIcon,
19 CheckIcon,
20 ChevronRightIcon,
21 CloudIcon,
22 CopyIcon,
23 LinkIcon,
24 MonitorIcon,
25 TerminalIcon,
26} from "lucide-react";
27import { useCallback, useEffect, useMemo, useRef, useState } from "react";
28​
29import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";
30import { useLocalStorage } from "../../hooks/useLocalStorage";
31import { hasCloudPublicConfig } from "../../cloud/publicConfig";
32import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
33import { useCompleteOnboarding } from "../../onboarding/firstRun";
34import {
35 partitionOnboardingProjects,
36 onboardingProjectKey,
37 resolveOnboardingLandingProject,
38 resolveOnboardingProjectId,
39} from "../../onboarding/projectImport.logic";
40import {
41 getOnboardingProviderState,
42 resolveOnboardingProviderInstallCommand,
43 resolveOnboardingProviderLoginCommand,
44 selectOnboardingProvidersByDriver,
45} from "../../onboarding/providerReadiness.logic";
46import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
47import { newProjectId, randomUUID } from "../../lib/utils";
48import { agentSessionImport } from "../../state/agentSessions";
49import { readProjects, useProjects } from "../../state/entities";
50import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
51import { isOnboardingRelayEnvironment } from "../../onboarding/targetEnvironment.logic";
52import { useProjectScans } from "../../onboarding/useProjectScans";
53import { projectEnvironment } from "../../state/projects";
54import { serverEnvironment } from "../../state/server";
55import { terminalEnvironment } from "../../state/terminal";
56import { useAtomCommand } from "../../state/use-atom-command";
57import { connectPairing } from "../../connection/onboarding";
58import { getProviderSummary } from "../settings/providerStatus";
59import { getDriverOption } from "../settings/providerDriverMeta";
60import { TerminalViewport } from "../ThreadTerminalDrawer";
61import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
62import { T3Wordmark } from "../T3Wordmark";
63import { Button } from "../ui/button";
64import { Checkbox } from "../ui/checkbox";
65import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
66import { Input } from "../ui/input";
67import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
68import { ScrollArea } from "../ui/scroll-area";
69import { Spinner } from "../ui/spinner";
70import { WizardPanel, WizardSteps } from "../ui/wizard";
71import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog";
72import { toastManager } from "../ui/toast";
73import { cn } from "../../lib/utils";
74​
75/**
76 * First-run welcome wizard. Rendered over the workspace at `/welcome` on a
77 * fresh install (no completed-onboarding flag, empty workspace). Flow per the
78 * onboarding overhaul spec: connection choice → sign-in/pair (remote paths) →
79 * agent setup with inline install terminal → project import → main screen.
80 * Every step past the connection gate is skippable; the whole wizard is
81 * re-runnable by clearing the flag.
82 */
83​
84type WizardStep = "connection" | "agents" | "import";
85const NO_ENVIRONMENTS: readonly EnvironmentId[] = [];
86​
87const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup");
88const ONBOARDING_STAGES = ["Connect", "Agents", "Projects"] as const;
89const SCAN_LIMIT_MESSAGE = "Scan limit reached. Some projects or conversations may be missing.";
90​
91export function WelcomeWizard({
92 localAvailable,
93 onDone,
94}: {
95 /** Whether this client is authenticated to the server serving the app. */
96 readonly localAvailable: boolean;
97 readonly onDone: (projectRef?: ScopedProjectRef) => void;
98}) {
99 const completeOnboarding = useCompleteOnboarding();
100 const [step, setStep] = useState<WizardStep>("connection");
101 const { environments } = useEnvironments();
102 const [selection, setSelection] = useState<ReadonlySet<EnvironmentId> | null>(null);
103 const autoSelectedComputers = useRef(new Set<EnvironmentId>());
104 const [setupIds, setSetupIds] = useState<readonly EnvironmentId[]>([]);
105 const [isImporting, setIsImporting] = useState(false);
106 const finishingPromiseRef = useRef<Promise<boolean> | null>(null);
107 const completionErrorToastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
108 const primaryEnvironment = usePrimaryEnvironment();
109 useEffect(() => {
110 const newComputers = environments.filter(
111 (environment) => !autoSelectedComputers.current.has(environment.environmentId),
112 );
113 if (newComputers.length === 0) return;
114 for (const environment of newComputers) {
115 autoSelectedComputers.current.add(environment.environmentId);
116 }
117 setSelection(
118 (current) =>
119 new Set([
120 ...(current ?? []),
121 ...newComputers.map((environment) => environment.environmentId),
122 ]),
123 );
124 }, [environments]);
125 const selectedIds =
126 selection ?? new Set(primaryEnvironment ? [primaryEnvironment.environmentId] : []);
127 const scans = useProjectScans(step === "import" ? setupIds : NO_ENVIRONMENTS);
128 const isLoadingProjects =
129 step === "import" &&
130 scans.every((scan) => scan.data === null) &&
131 scans.some((scan) => scan.isPending);
132 const startSetup = (ids: readonly EnvironmentId[]) => {
133 if (ids.length === 0) return;
134 setSetupIds(ids);
135 setStep("agents");
136 };
137 const stageIndex = step === "agents" ? 1 : step === "import" ? 2 : 0;
138 const finish = useCallback(
139 (projectRef?: ScopedProjectRef) => {
140 if (finishingPromiseRef.current !== null) return finishingPromiseRef.current;
141 if (completionErrorToastIdRef.current !== null) {
142 toastManager.close(completionErrorToastIdRef.current);
143 completionErrorToastIdRef.current = null;
144 }
145​
146 const completion = completeOnboarding()
147 .then(() => {
148 if (completionErrorToastIdRef.current !== null) {
149 toastManager.close(completionErrorToastIdRef.current);
150 completionErrorToastIdRef.current = null;
151 }
152 onDone(projectRef);
153 return true;
154 })
155 .catch(() => {
156 const errorToast = {
157 type: "error",
158 title: "Could not finish setup",
159 description: "Your settings could not be saved. Try again.",
160 } as const;
161 if (completionErrorToastIdRef.current === null) {
162 completionErrorToastIdRef.current = toastManager.add(errorToast);
163 } else {
164 toastManager.update(completionErrorToastIdRef.current, errorToast);
165 }
166 return false;
167 })
168 .finally(() => {
169 if (finishingPromiseRef.current === completion) {
170 finishingPromiseRef.current = null;
171 }
172 });
173 finishingPromiseRef.current = completion;
174 return completion;
175 },
176 [completeOnboarding, onDone],
177 );
178​
179 return (
180 <Dialog open disablePointerDismissal onOpenChange={(_, event) => event.cancel()}>
181 <DialogPopup
182 className="max-w-xl overflow-x-hidden overflow-y-auto"
183 bottomStickOnMobile={false}
184 showCloseButton={false}
185 initialFocus={() => document.getElementById("onboarding-pairing-url") ?? true}
186 >
187 <DialogTitle className="sr-only">Set up T3 Code</DialogTitle>
188 <div className="flex min-h-0 flex-col">
189 <DialogHeader className="gap-4">
190 <div className="flex items-baseline gap-1.5" role="img" aria-label="T3 Code">
191 <T3Wordmark className="h-4 w-auto shrink-0" aria-hidden />
192 <span className="text-[1.4rem] font-medium tracking-tight text-muted-foreground">
193 Code
194 </span>
195 </div>
196 <WizardSteps
197 steps={ONBOARDING_STAGES}
198 currentStep={stageIndex}
199 isStepDisabled={(index) => isImporting || index >= stageIndex}
200 onStepChange={(index) => {
201 if (isImporting || index > stageIndex) return;
202 setStep(index === 0 ? "connection" : "agents");
203 }}
204 />
205 </DialogHeader>
206​
207 <WizardPanel className="min-w-0" holdHeight={isLoadingProjects}>
208 {step === "connection" ? (
209 <ConnectionStep
210 expandPairingInitially={!localAvailable && !hasCloudPublicConfig()}
211 selectedIds={selectedIds}
212 autoSelectedComputers={autoSelectedComputers.current}
213 onSelectionChange={setSelection}
214 onToggleEnvironment={(environmentId, checked) =>
215 setSelection((current) => {
216 const next = new Set(current ?? selectedIds);
217 if (checked) next.add(environmentId);
218 else next.delete(environmentId);
219 return next;
220 })
221 }
222 onContinue={() =>
223 startSetup(
224 environments
225 .filter((environment) => selectedIds.has(environment.environmentId))
226 .map((environment) => environment.environmentId),
227 )
228 }
229 onPaired={(environmentId) => {
230 setSelection(new Set([...selectedIds, environmentId]));
231 }}
232 />
233 ) : step === "agents" ? (
234 <AgentsStep environmentIds={setupIds} onContinue={() => setStep("import")} />
235 ) : (
236 <ImportStep
237 scans={scans}
238 isImporting={isImporting}
239 setIsImporting={setIsImporting}
240 onDone={finish}
241 />
242 )}
243 </WizardPanel>
244 </div>
245 </DialogPopup>
246 </Dialog>
247 );
249​
250// ── Step 1: connection choice ────────────────────────────────
251​
252function ConnectionStep({
253 autoSelectedComputers,
254 expandPairingInitially,
255 selectedIds,
256 onSelectionChange,
257 onToggleEnvironment,
258 onContinue,
259 onPaired,
260}: {
261 readonly autoSelectedComputers: Set<EnvironmentId>;
262 readonly expandPairingInitially: boolean;
263 readonly selectedIds: ReadonlySet<EnvironmentId>;
264 readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId>) => void;
265 readonly onToggleEnvironment: (environmentId: EnvironmentId, checked: boolean) => void;
266 readonly onContinue: () => void;
267 readonly onPaired: (environmentId: EnvironmentId) => void;
268}) {
269 const { environments } = useEnvironments();
270 const cloudEnabled = hasCloudPublicConfig();
271 const directEnvironments = environments.filter(
272 (environment) => !cloudEnabled || !isOnboardingRelayEnvironment(environment),
273 );
274 const [pairingOpen, setPairingOpen] = useState(expandPairingInitially);
275 const [isPairing, setIsPairing] = useState(false);
276 const ready =
277 selectedIds.size > 0 &&
278 [...selectedIds].every((id) =>
279 environments.some(
280 (environment) =>
281 environment.environmentId === id && environment.connection.phase === "connected",
282 ),
283 );
284 const continueRef = useRef<HTMLButtonElement>(null);
285 useEffect(() => {
286 if (
287 ready &&
288 (document.activeElement === document.body ||
289 document.activeElement?.getAttribute("role") === "dialog")
290 ) {
291 continueRef.current?.focus();
292 }
293 }, [ready]);
294 return (
295 <>
296 <h1 className="text-2xl font-semibold tracking-tight text-foreground">
297 Connect your computers
298 </h1>
299 <p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">
300 Choose one or more computers. We’ll set up agents and projects on each.
301 </p>
302 {directEnvironments.length > 0 ? (
303 <fieldset className="mt-5 space-y-2">
304 <legend className="sr-only">Computers to set up</legend>
305 {directEnvironments.map((environment) => (
306 <label
307 key={environment.environmentId}
308 className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-3"
309 >
310 <Checkbox
311 checked={selectedIds.has(environment.environmentId)}
312 onCheckedChange={(checked) => {
313 const next = new Set(selectedIds);
314 if (checked) next.add(environment.environmentId);
315 else next.delete(environment.environmentId);
316 onSelectionChange(next);
317 }}
318 />
319 <MonitorIcon className="size-4 shrink-0 text-muted-foreground" />
320 <span className="min-w-0 flex-1">
321 <span className="flex items-baseline justify-between gap-3">
322 <span className="min-w-0 text-sm font-medium break-words">
323 {environment.label}
324 </span>
325 <span className="shrink-0 text-xs text-muted-foreground">
326 {environment.connection.phase === "connected" ? "Connected" : "Connecting…"}
327 </span>
328 </span>
329 {environment.displayUrl ? (
330 <span className="mt-0.5 block text-xs break-all text-muted-foreground">
331 {environment.displayUrl}
332 </span>
333 ) : null}
334 </span>
335 </label>
336 ))}
337 </fieldset>
338 ) : null}
339 <div className="mt-4 space-y-2">
340 {cloudEnabled ? (
341 <ConnectAccountOption
342 autoSelectedComputers={autoSelectedComputers}
343 disabled={isPairing}
344 selectedIds={selectedIds}
345 onToggleEnvironment={onToggleEnvironment}
346 />
347 ) : null}
348 <Collapsible
349 open={pairingOpen}
350 onOpenChange={setPairingOpen}
351 className="rounded-lg border border-border bg-background"
352 >
353 <CollapsibleTrigger
354 disabled={isPairing}
355 render={
356 <Button
357 variant="ghost"
358 className="h-auto min-h-14 w-full justify-start gap-3 px-3 py-3 text-left whitespace-normal sm:h-auto"
359 />
360 }
361 >
362 <LinkIcon className="size-4 text-muted-foreground" />
363 <span className="flex-1">Add a computer</span>
364 <ChevronRightIcon
365 className={cn("size-4 text-muted-foreground", pairingOpen && "rotate-90")}
366 />
367 </CollapsibleTrigger>
368 <CollapsiblePanel>
369 <div className="px-3 pb-3">
370 <PairingForm
371 isPairing={isPairing}
372 setIsPairing={setIsPairing}
373 onPaired={(environmentId) => {
374 setPairingOpen(false);
375 onPaired(environmentId);
376 requestAnimationFrame(() => continueRef.current?.focus());
377 }}
378 />
379 </div>
380 </CollapsiblePanel>
381 </Collapsible>
382 </div>
383 <div className="mt-6 flex items-center justify-end gap-3">
384 <Button
385 ref={continueRef}
386 autoFocus={!expandPairingInitially}
387 disabled={!ready || isPairing}
388 onClick={onContinue}
389 >
390 Continue
391 <ArrowRightIcon className="size-3.5" />
392 </Button>
393 </div>
394 </>
395 );
397​
398function ConnectAccountOption({
399 autoSelectedComputers,
400 disabled,
401 selectedIds,
402 onToggleEnvironment,
403}: {
404 readonly autoSelectedComputers: Set<EnvironmentId>;
405 readonly disabled: boolean;
406 readonly selectedIds: ReadonlySet<EnvironmentId>;
407 readonly onToggleEnvironment: (environmentId: EnvironmentId, checked: boolean) => void;
408}) {
409 const { environments } = useEnvironments();
410 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
411 const { openAuthPrompt } = useT3ConnectAuthPrompt();
412 const [expanded, setExpanded] = useState(true);
413 const [discoveryReady, setDiscoveryReady] = useState(false);
414 const onDiscoveryReady = useCallback(() => setDiscoveryReady(true), []);
415​
416 return (
417 <Collapsible
418 open={expanded && !!isSignedIn && discoveryReady}
419 onOpenChange={setExpanded}
420 className="rounded-lg border border-border bg-background"
421 >
422 <CollapsibleTrigger
423 disabled={disabled || !isLoaded}
424 onClick={(event) => {
425 if (!isSignedIn) {
426 event.preventDefault();
427 setExpanded(true);
428 openAuthPrompt();
429 }
430 }}
431 render={
432 <Button
433 variant="ghost"
434 className="h-auto min-h-14 w-full justify-start gap-3 px-3 py-3 text-left whitespace-normal sm:h-auto"
435 />
436 }
437 >
438 <CloudIcon className="size-4 text-muted-foreground" />
439 <span className="flex-1">T3 Connect</span>
440 <span className="text-xs text-muted-foreground">
441 {!isLoaded
442 ? "Loading sign-in…"
443 : !isSignedIn
444 ? "Sign in"
445 : !discoveryReady
446 ? "Loading computers…"
447 : null}
448 </span>
449 <ChevronRightIcon
450 className={cn("size-4 text-muted-foreground", expanded && isSignedIn && "rotate-90")}
451 />
452 </CollapsibleTrigger>
453 <CollapsiblePanel keepMounted>
454 <div className="px-3 pb-3">
455 <div className="mb-3 space-y-1.5">
456 {isSignedIn ? (
457 <CloudEnvironmentConnectRows
458 primaryEnvironmentId={null}
459 savedEnvironments={environments}
460 showSavedEnvironments
461 onDiscoveryReady={onDiscoveryReady}
462 selection={{ selectedIds, onChange: onToggleEnvironment, autoSelectedComputers }}
463 refreshWhileEmpty
464 empty={
465 <p className="py-3 text-sm text-muted-foreground">No computers linked yet.</p>
466 }
467 />
468 ) : null}
469 </div>
470 <p className="text-sm text-muted-foreground">
471 Run this on each computer you want to connect.
472 </p>
473 <CommandBlock command="npx t3 connect" className="mt-3" />
474 <p className="mt-3 text-xs text-muted-foreground">
475 Keep T3 Code running. Select the computers you want to set up above.
476 </p>
477 </div>
478 </CollapsiblePanel>
479 </Collapsible>
480 );
482​
483// ── Step 2′: Direct pairing ──────────────────────────────────
484​
485/**
486 * Register a computer in this browser using a server-minted pairing link.
487 */
488function PairingForm({
489 isPairing,
490 setIsPairing,
491 onPaired,
492}: {
493 readonly isPairing: boolean;
494 readonly setIsPairing: (value: boolean) => void;
495 readonly onPaired: (environmentId: EnvironmentId) => void;
496}) {
497 const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false });
498 const [pairingUrl, setPairingUrl] = useState("");
499 const [errorMessage, setErrorMessage] = useState("");
500 const mountedRef = useRef(true);
501​
502 useEffect(() => {
503 mountedRef.current = true;
504 return () => {
505 mountedRef.current = false;
506 };
507 }, []);
508​
509 const submit = async () => {
510 if (isPairing || pairingUrl.trim().length === 0) return;
511 setIsPairing(true);
512 setErrorMessage("");
513 const result = await connectPairingEnvironment({ pairingUrl: pairingUrl.trim() });
514 if (!mountedRef.current) return;
515 setIsPairing(false);
516 if (result._tag === "Success") {
517 onPaired(result.value);
518 return;
519 }
520 if (isAtomCommandInterrupted(result)) return;
521 const cause = squashAtomCommandFailure(result);
522 setErrorMessage(cause instanceof Error ? cause.message : "Pairing failed.");
523 };
524​
525 return (
526 <>
527 <form
528 className="space-y-3"
529 onSubmit={(event) => {
530 event.preventDefault();
531 void submit();
532 }}
533 >
534 <div>
535 <label className="block text-sm text-muted-foreground" htmlFor="onboarding-pairing-url">
536 Pairing link
537 </label>
538 <Input
539 id="onboarding-pairing-url"
540 autoFocus
541 aria-invalid={errorMessage.length > 0}
542 aria-describedby={errorMessage ? "onboarding-pairing-error" : undefined}
543 className="mt-2"
544 size="lg"
545 autoCapitalize="none"
546 autoComplete="off"
547 autoCorrect="off"
548 spellCheck={false}
549 nativeInput
550 readOnly={isPairing}
551 placeholder="https://your-server:5230/pair#token=…"
552 value={pairingUrl}
553 onChange={(event) => setPairingUrl(event.currentTarget.value)}
554 onKeyDown={(event) => {
555 if (
556 event.key === "Enter" &&
557 (event.nativeEvent.isComposing || event.keyCode === 229)
558 ) {
559 event.preventDefault();
560 }
561 }}
562 />
563 </div>
564 {errorMessage ? (
565 <div
566 id="onboarding-pairing-error"
567 role="alert"
568 className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive"
569 >
570 {errorMessage}
571 </div>
572 ) : null}
573 <Collapsible>
574 <div className="flex items-center justify-between gap-3">
575 <CollapsibleTrigger
576 type="button"
577 className="group flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
578 >
579 <ChevronRightIcon className="size-3.5 group-data-panel-open:rotate-90" />
580 Need a pairing link?
581 </CollapsibleTrigger>
582 <Button type="submit" disabled={isPairing || pairingUrl.trim().length === 0}>
583 {isPairing ? "Pairing..." : "Pair"}
584 </Button>
585 </div>
586 <CollapsiblePanel className="pt-3">
587 <p className="text-sm text-muted-foreground">
588 Run this on the computer with your code.
589 </p>
590 <CommandBlock command="npx t3 pair" className="mt-2" />
591 <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
592 Start T3 Code first, or run <code className="font-mono">npx t3 serve</code>. Add{" "}
593 <code className="font-mono">--tailscale</code> to use your tailnet.
594 </p>
595 </CollapsiblePanel>
596 </Collapsible>
597 </form>
598 </>
599 );
601​
602// ── Step 3: agents ───────────────────────────────────────────
603​
604const PRIMARY_AGENT_DRIVERS = ["claudeAgent", "codex"] as const;
605type OnboardingAgentDriver = (typeof PRIMARY_AGENT_DRIVERS)[number];
606​
607/** Setup values stay fixed while provider probes refresh the surrounding cards. */
608interface AgentTerminalSession {
609 readonly environmentId: EnvironmentId;
610 readonly driver: OnboardingAgentDriver;
611 readonly providerInstanceId: ServerProvider["instanceId"];
612 readonly cwd: string;
613 readonly command: string;
614 readonly keybindings: ServerConfig["keybindings"];
616​
617/**
618 * Claude Code and Codex use live probe status. Install opens the built-in
619 * terminal inline with the vendor's standalone installer pre-typed. The update
620 * RPC can't install a binary that isn't there yet (it infers the installer from
621 * the installed binary's path), and the terminal also handles the interactive
622 * login that follows.
623 */
624function AgentsStep({
625 environmentIds,
626 onContinue,
627}: {
628 readonly environmentIds: readonly EnvironmentId[];
629 readonly onContinue: () => void;
630}) {
631 const { environments } = useEnvironments();
632 return (
633 <StepShell title="Your agents" description="Agents available on your selected computers.">
634 <ScrollArea
635 scrollFade
636 className="mt-5 h-auto max-h-96 [&_[data-slot=scroll-area-scrollbar]]:opacity-100"
637 >
638 <div className="space-y-5 pr-3">
639 {environmentIds.map((environmentId) => (
640 <ConnectedAgentsStep
641 key={environmentId}
642 environmentId={environmentId}
643 machineLabel={
644 environments.find((environment) => environment.environmentId === environmentId)
645 ?.label ?? "Computer"
646 }
647 />
648 ))}
649 </div>
650 </ScrollArea>
651 <div className="mt-6 flex justify-end">
652 <Button autoFocus onClick={onContinue}>
653 Continue
654 <ArrowRightIcon className="size-3.5" />
655 </Button>
656 </div>
657 </StepShell>
658 );
660​
661function ConnectedAgentsStep({
662 environmentId,
663 machineLabel,
664}: {
665 readonly environmentId: EnvironmentId;
666 readonly machineLabel: string;
667}) {
668 const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));
669 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
670 reportFailure: false,
671 });
672 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
673 const [terminalSession, setTerminalSession] = useState<AgentTerminalSession | null>(null);
674​
675 // Re-probe on entry so freshly installed CLIs show up without a manual
676 // refresh; harmless when nothing changed (single-flighted per environment).
677 useEffect(() => {
678 void refreshProviders({ environmentId, input: {} });
679 }, [environmentId, refreshProviders]);
680​
681 const byDriver = useMemo(() => selectOnboardingProvidersByDriver(providers), [providers]);
682​
683 const primaryAgents = PRIMARY_AGENT_DRIVERS.map((driver) => ({
684 driver,
685 provider: byDriver.get(driver),
686 }));
687 return (
688 <section>
689 <h2 className="mb-2 text-sm font-medium">{machineLabel}</h2>
690 <div className="space-y-1.5">
691 {primaryAgents.map(({ driver, provider }) => (
692 <AgentCard
693 key={driver}
694 driver={driver}
695 provider={provider}
696 terminalOpen={terminalSession?.driver === driver}
697 terminalAvailable={serverConfig !== null}
698 onOpenTerminal={() => {
699 if (provider === undefined || serverConfig === null) return;
700 setTerminalSession({
701 environmentId,
702 driver,
703 providerInstanceId: provider.instanceId,
704 cwd: serverConfig.cwd,
705 command: provider.installed
706 ? resolveOnboardingProviderLoginCommand(
707 provider,
708 serverConfig.settings,
709 serverConfig.environment.platform.os,
710 )
711 : resolveOnboardingProviderInstallCommand(
712 driver,
713 serverConfig.environment.platform.os,
714 ),
715 keybindings: serverConfig.keybindings,
716 });
717 }}
718 />
719 ))}
720 </div>
721 {terminalSession !== null ? (
722 <AgentInstallTerminal
723 key={`${terminalSession.environmentId}:${terminalSession.providerInstanceId}:${terminalSession.driver}`}
724 session={terminalSession}
725 onClose={() => {
726 setTerminalSession(null);
727 void refreshProviders({ environmentId, input: {} });
728 }}
729 />
730 ) : null}
731 </section>
732 );
734​
735function AgentCard({
736 driver,
737 provider,
738 terminalOpen,
739 terminalAvailable,
740 onOpenTerminal,
741}: {
742 readonly driver: OnboardingAgentDriver;
743 readonly provider: ServerProvider | undefined;
744 readonly terminalOpen: boolean;
745 readonly terminalAvailable: boolean;
746 readonly onOpenTerminal: () => void;
747}) {
748 const meta = getDriverOption(ProviderDriverKind.make(driver));
749 const Icon = meta?.icon;
750 const displayName = driver === "claudeAgent" ? "Claude Code" : (meta?.label ?? driver);
751 const summary = getProviderSummary(provider);
752 const providerState = getOnboardingProviderState(provider);
753​
754 return (
755 <div className="flex items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5">
756 {Icon ? (
757 <Icon className={cn("size-5 shrink-0", driver !== "claudeAgent" && "fill-foreground")} />
758 ) : null}
759 <div className="min-w-0 flex-1">
760 <span className="block text-sm font-medium text-foreground">{displayName}</span>
761 <p className="mt-0.5 text-xs leading-relaxed break-words whitespace-pre-wrap text-muted-foreground">
762 {summary.headline}
763 {summary.detail ? ` · ${summary.detail}` : ""}
764 </p>
765 </div>
766 <div className="shrink-0">
767 {providerState === "ready" ? (
768 <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground">
769 <CheckIcon className="size-3.5" />
770 Ready
771 </span>
772 ) : providerState === "checking" ? (
773 <span className="text-xs text-muted-foreground">Checking...</span>
774 ) : providerState === "disabled" ? (
775 <span className="text-xs text-muted-foreground">Disabled</span>
776 ) : providerState === "attention" ? (
777 <span className="text-xs text-muted-foreground">{summary.headline}</span>
778 ) : (
779 <Button
780 size="xs"
781 variant="ghost"
782 onClick={onOpenTerminal}
783 disabled={terminalOpen || !terminalAvailable}
784 >
785 <TerminalIcon className="size-3.5" />
786 {providerState === "signIn" ? "Sign in" : "Install"}
787 </Button>
788 )}
789 </div>
790 </div>
791 );
793​
794/**
795 * Inline install terminal. Opens a PTY on the connected environment under a
796 * synthetic onboarding thread id (terminals are keyed by free-form thread id;
797 * the server validates only the cwd) and pre-types the install or login
798 * command without submitting, so the user reviews and presses Enter.
799 */
800function AgentInstallTerminal({
801 session,
802 onClose,
803}: {
804 readonly session: AgentTerminalSession;
805 readonly onClose: () => void;
806}) {
807 const { command, cwd, driver, environmentId, keybindings, providerInstanceId } = session;
808 // Same terminal typography preference the thread drawer honors.
809 const [advancedTypography] = useLocalStorage(
810 TYPOGRAPHY_ADVANCED_STORAGE_KEY,
811 false,
812 Schema.Boolean,
813 );
814 const openTerminal = useAtomCommand(terminalEnvironment.open, { reportFailure: false });
815 const writeTerminal = useAtomCommand(terminalEnvironment.write, { reportFailure: false });
816 const closeTerminal = useAtomCommand(terminalEnvironment.close, { reportFailure: false });
817 const setupQueueRef = useRef(Promise.resolve());
818 const setupGenerationRef = useRef(0);
819 const activeSetupGenerationRef = useRef<number | null>(null);
820 const [terminalId] = useState(() => `onboarding-${driver}-${randomUUID()}`);
821 const threadRef = useMemo(
822 () => scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID),
823 [environmentId],
824 );
825 const [setupAttempt, setSetupAttempt] = useState(0);
826 const [setupState, setSetupState] = useState<
827 "preparing" | "ready" | "openFailed" | "writeFailed"
828 >("preparing");
829 const terminalReady = setupState === "ready" || setupState === "writeFailed";
830​
831 // Keep each setup generation distinct. In Strict Mode, a canceled open can
832 // finish after the replacement setup starts; it must not close or pre-type
833 // into the replacement session that shares this terminal id.
834 useEffect(() => {
835 const generation = setupGenerationRef.current + 1;
836 setupGenerationRef.current = generation;
837 activeSetupGenerationRef.current = generation;
838 setSetupState("preparing");
839​
840 setupQueueRef.current = setupQueueRef.current.then(async () => {
841 if (activeSetupGenerationRef.current !== generation) return;
842 const opened = await openTerminal({
843 environmentId,
844 input: {
845 threadId: AGENT_ONBOARDING_THREAD_ID,
846 terminalId,
847 cwd,
848 providerInstanceId,
849 },
850 });
851 if (opened._tag !== "Success") {
852 if (activeSetupGenerationRef.current === generation) setSetupState("openFailed");
853 return;
854 }
855​
856 if (activeSetupGenerationRef.current !== generation) return;
857​
858 const wrote = await writeTerminal({
859 environmentId,
860 input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, data: command },
861 });
862 if (activeSetupGenerationRef.current !== generation) return;
863 setSetupState(wrote._tag === "Success" ? "ready" : "writeFailed");
864 });
865​
866 // Every exit path unmounts the drawer (Done, Continue/Skip, card switch,
867 // session exit), so this cleanup is the single place the PTY dies —
868 // nothing is left running behind the wizard. An interrupted install is
869 // re-runnable from the card.
870 return () => {
871 if (activeSetupGenerationRef.current === generation) {
872 activeSetupGenerationRef.current = null;
873 }
874 setupQueueRef.current = setupQueueRef.current.then(async () => {
875 await closeTerminal({
876 environmentId,
877 input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, deleteHistory: true },
878 });
879 });
880 };
881 }, [
882 closeTerminal,
883 command,
884 cwd,
885 environmentId,
886 openTerminal,
887 providerInstanceId,
888 setupAttempt,
889 terminalId,
890 writeTerminal,
891 ]);
892​
893 return (
894 <div className="thread-terminal-drawer mt-4 overflow-hidden rounded-lg border border-border/70 bg-background text-foreground">
895 <div className="flex items-center justify-between border-b border-border/60 bg-background/60 px-3 py-1.5">
896 <span className="text-[11px] font-medium text-muted-foreground">
897 {setupState === "writeFailed" ? (
898 <>
899 Run <code className="rounded bg-muted px-1 font-mono">{command}</code> in this
900 terminal.
901 </>
902 ) : setupState === "ready" ? (
903 "Review the command, then press Enter to run it."
904 ) : setupState === "openFailed" ? (
905 "Could not open the setup terminal."
906 ) : (
907 "Preparing command..."
908 )}
909 </span>
910 <div className="flex items-center gap-1">
911 {setupState === "openFailed" ? (
912 <Button size="xs" variant="ghost" onClick={() => setSetupAttempt((value) => value + 1)}>
913 Retry
914 </Button>
915 ) : null}
916 <Button size="xs" variant="ghost-muted" onClick={onClose}>
917 Close
918 </Button>
919 </div>
920 </div>
921 <div className="h-64">
922 {terminalReady ? (
923 <TerminalViewport
924 threadRef={threadRef}
925 threadId={AGENT_ONBOARDING_THREAD_ID}
926 terminalId={terminalId}
927 terminalLabel={`Install ${driver}`}
928 cwd={cwd}
929 providerInstanceId={providerInstanceId}
930 advancedTypography={advancedTypography}
931 onSessionExited={onClose}
932 focusRequestId={1}
933 autoFocus
934 visible
935 resizeEpoch={0}
936 drawerHeight={256}
937 keybindings={keybindings}
938 />
939 ) : null}
940 </div>
941 </div>
942 );
944​
945// ── Step 4: import ───────────────────────────────────────────
946​
947function ImportStep({
948 scans,
949 isImporting,
950 setIsImporting,
951 onDone,
952}: {
953 readonly scans: ReturnType<typeof useProjectScans>;
954 readonly isImporting: boolean;
955 readonly setIsImporting: (value: boolean) => void;
956 readonly onDone: (projectRef?: ScopedProjectRef) => Promise<boolean>;
957}) {
958 const { environments } = useEnvironments();
959 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
960 const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false });
961 const projects = useProjects();
962 const [selectedPaths, setSelectedPaths] = useState<ReadonlySet<string> | null>(null);
963 const [importError, setImportError] = useState("");
964 const [landingProject, setLandingProject] = useState<ScopedProjectRef | null>(null);
965 // Keep project creation attempts separate from completed history imports so both can retry.
966 const importedProjectsRef = useRef(new Map<string, ScopedProjectRef>());
967 const projectsWithImportedHistoryRef = useRef(new Map<string, ScopedProjectRef>());
968 const lastImportSelectionRef = useRef<ReadonlyArray<string>>([]);
969 const projectAttemptsRef = useRef(
970 new Map<string, { readonly projectId: ProjectId; readonly commandId: CommandId }>(),
971 );
972 const importGenerationRef = useRef(0);
973​
974 // Ignore command completions after leaving the import step.
975 useEffect(() => {
976 importGenerationRef.current += 1;
977 return () => {
978 importGenerationRef.current += 1;
979 };
980 }, []);
981​
982 useEffect(() => {
983 if (
984 landingProject !== null &&
985 projects.some(
986 (project) =>
987 project.id === landingProject.projectId &&
988 project.environmentId === landingProject.environmentId,
989 )
990 ) {
991 setLandingProject(null);
992 void onDone(landingProject).then((completed) => {
993 if (!completed) setIsImporting(false);
994 });
995 }
996 }, [landingProject, onDone, projects, setIsImporting]);
997​
998 const { available: candidates, recent } = useMemo(
999 () =>
1000 partitionOnboardingProjects(
1001 scans.flatMap((scan) =>
1002 (scan.data?.candidates ?? []).map((candidate) => ({
1003 ...candidate,
1004 environmentId: scan.environmentId,
1005 key: onboardingProjectKey(scan.environmentId, candidate.path),
1006 })),
1007 ),
1008 ),
1009 [scans],
1010 );
1011 const selected = candidates.filter((candidate) =>
1012 selectedPaths
1013 ? selectedPaths.has(candidate.key)
1014 : recent.some((item) => item.key === candidate.key),
1015 );
1016​
1017 const finishAfterImport = () => {
1018 const projectRef = resolveOnboardingLandingProject(
1019 lastImportSelectionRef.current,
1020 projectsWithImportedHistoryRef.current,
1021 importedProjectsRef.current,
1022 );
1023 if (projectRef === undefined) {
1024 void onDone();
1025 return;
1027 setIsImporting(true);
1028 setLandingProject(projectRef);
1029 };
1030​
1031 const runImport = async (selection: typeof candidates) => {
1032 if (isImporting) return;
1033 if (selection.length === 0) {
1034 void onDone();
1035 return;
1037 setIsImporting(true);
1038 setImportError("");
1039 lastImportSelectionRef.current = selection.map((candidate) => candidate.key);
1040 const importGeneration = importGenerationRef.current;
1041 const importedProjects = importedProjectsRef.current;
1042 const projectAttempts = projectAttemptsRef.current;
1043 // Interrupted imports are neither failures nor successes — the command was
1044 // superseded or the environment dropped — but they still didn't land, so
1045 // they must not read as "imported everything". Retries skip paths that
1046 // already landed this session (re-creating them would only trip the
1047 // duplicate-root invariant and read as a failure).
1048 let importedProjectsCount =
1049 importedProjects.size > 0
1050 ? selection.filter((candidate) => importedProjects.has(candidate.key)).length
1051 : 0;
1052 let importedThreadCount = 0;
1053 let skippedThreadCount = 0;
1054 const refreshEnvironments = new Set<EnvironmentId>();
1055 for (const candidate of selection) {
1056 const { environmentId } = candidate;
1057 if (
1058 importGeneration !== importGenerationRef.current ||
1059 importedProjects !== importedProjectsRef.current
1060 ) {
1061 return;
1063 if (importedProjects.has(candidate.key)) continue;
1064 let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate);
1065 if (projectId === null) {
1066 let attempt = projectAttempts.get(candidate.key);
1067 if (attempt === undefined) {
1068 const nextProjectId = newProjectId();
1069 attempt = {
1070 projectId: nextProjectId,
1071 commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`),
1072 };
1073 projectAttempts.set(candidate.key, attempt);
1075 projectId = attempt.projectId;
1076 const result = await createProject({
1077 environmentId,
1078 input: {
1079 projectId,
1080 commandId: attempt.commandId,
1081 title: candidate.title,
1082 workspaceRoot: candidate.path,
1083 createWorkspaceRootIfMissing: false,
1084 defaultModelSelection: null,
1085 },
1086 });
1087 if (
1088 importGeneration !== importGenerationRef.current ||
1089 importedProjects !== importedProjectsRef.current
1090 ) {
1091 return;
1093 if (result._tag !== "Success") {
1094 if (!isAtomCommandInterrupted(result)) {
1095 projectAttempts.delete(candidate.key);
1096 refreshEnvironments.add(environmentId);
1098 continue;
1101​
1102 const threadImportResult = await importThreads({
1103 environmentId,
1104 input: { projectId, expectedWorkspaceRoot: candidate.path },
1105 });
1106 if (
1107 importGeneration !== importGenerationRef.current ||
1108 importedProjects !== importedProjectsRef.current
1109 ) {
1110 return;
1112 if (threadImportResult._tag === "Success") {
1113 importedThreadCount += threadImportResult.value.importedCount;
1114 skippedThreadCount += threadImportResult.value.skippedCount;
1115 if (threadImportResult.value.importedCount > 0) {
1116 projectsWithImportedHistoryRef.current.set(
1117 candidate.key,
1118 scopeProjectRef(environmentId, projectId),
1119 );
1121 if (threadImportResult.value.skippedCount === 0) {
1122 importedProjectsCount += 1;
1123 importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId));
1125 } else if (!isAtomCommandInterrupted(threadImportResult)) {
1126 projectAttempts.delete(candidate.key);
1127 refreshEnvironments.add(environmentId);
1130 for (const scan of scans) {
1131 if (refreshEnvironments.has(scan.environmentId)) scan.refresh();
1133 setIsImporting(false);
1134 if (importedProjectsCount < selection.length) {
1135 if (importedThreadCount > 0 && skippedThreadCount > 0) {
1136 setImportError(
1137 `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedThreadCount} ${skippedThreadCount === 1 ? "thread" : "threads"} could not be imported.`,
1138 );
1139 } else if (skippedThreadCount > 0) {
1140 setImportError(
1141 `${skippedThreadCount} ${skippedThreadCount === 1 ? "thread could" : "threads could"} not be imported.`,
1142 );
1143 } else if (importedThreadCount > 0) {
1144 setImportError(
1145 `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`,
1146 );
1147 } else {
1148 setImportError("Could not import thread history.");
1150 return;
1152 finishAfterImport();
1153 };
1154​
1155 if (scans.every((scan) => scan.data === null) && scans.some((scan) => scan.isPending)) {
1156 return (
1157 <div className="flex h-full min-h-40 flex-col">
1158 <h1 className="text-2xl font-semibold tracking-tight text-foreground">Your projects</h1>
1159 <div className="flex flex-1 flex-col items-center justify-center gap-3 py-6">
1160 <Spinner className="size-5 text-muted-foreground" />
1161 <p className="text-center text-sm text-muted-foreground">
1162 Looking for projects from Claude Code and Codex…
1163 </p>
1164 </div>
1165 <div className="flex justify-end">
1166 <Button variant="ghost-muted" onClick={() => void onDone()}>
1167 Do not import projects
1168 </Button>
1169 </div>
1170 </div>
1171 );
1173​
1174 return (
1175 <StepShell
1176 title="Choose your projects"
1177 description="Import projects and conversations from your selected computers."
1179 <ScrollArea
1180 scrollFade
1181 className="mt-5 h-auto max-h-80 [&_[data-slot=scroll-area-scrollbar]]:opacity-100"
1183 <div className="space-y-5 pr-3">
1184 {scans.map((scan) => {
1185 const groupCandidates = candidates.filter(
1186 (candidate) => candidate.environmentId === scan.environmentId,
1187 );
1188 const label =
1189 environments.find((environment) => environment.environmentId === scan.environmentId)
1190 ?.label ?? "Computer";
1191 return (
1192 <fieldset
1193 key={scan.environmentId}
1194 className="min-w-0 space-y-1.5"
1195 disabled={isImporting}
1197 <legend className="mb-2 text-sm font-medium">{label}</legend>
1198 {scan.isPending && scan.data === null ? (
1199 <div className="flex items-center gap-2 py-3 text-sm text-muted-foreground">
1200 <Spinner className="size-4" />
1201 Looking for projects…
1202 </div>
1203 ) : scan.error !== null ? (
1204 <div
1205 role="alert"
1206 className="flex items-center justify-between gap-3 text-sm text-muted-foreground"
1208 <span>Could not check projects. {scan.error}</span>
1209 <Button variant="ghost" size="sm" onClick={scan.refresh}>
1210 Retry
1211 </Button>
1212 </div>
1213 ) : groupCandidates.length === 0 ? (
1214 <p className="py-2 text-sm text-muted-foreground">
1215 No existing Claude Code or Codex projects found.
1216 </p>
1217 ) : null}
1218 {scan.data?.truncated ? (
1219 <p className="text-xs text-muted-foreground" role="status">
1220 {SCAN_LIMIT_MESSAGE}
1221 </p>
1222 ) : null}
1223 {groupCandidates.map((candidate) => (
1224 <label
1225 key={candidate.key}
1226 className="flex cursor-pointer items-center gap-2.5 rounded-lg border border-border bg-background px-2.5 py-2 has-disabled:cursor-default"
1228 <Checkbox
1229 checked={selected.some((item) => item.key === candidate.key)}
1230 onCheckedChange={(checked) => {
1231 const next = new Set(selected.map((item) => item.key));
1232 if (checked) next.add(candidate.key);
1233 else next.delete(candidate.key);
1234 setSelectedPaths(next);
1235 }}
1236 />
1237 <Tooltip>
1238 <TooltipTrigger
1239 render={<span className="min-w-0 flex-1 truncate font-mono text-xs" />}
1241 {candidate.path}
1242 </TooltipTrigger>
1243 <TooltipPopup className="max-w-96 break-all font-mono">
1244 {candidate.path}
1245 </TooltipPopup>
1246 </Tooltip>
1247 <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground">
1248 {candidate.sources
1249 .map((source) => (source === "claudeAgent" ? "Claude" : "Codex"))
1250 .join(", ")}{" "}
1251 · {candidate.threadCount} {candidate.threadCount === 1 ? "thread" : "threads"}
1252 </span>
1253 </label>
1254 ))}
1255 </fieldset>
1256 );
1257 })}
1258 </div>
1259 </ScrollArea>
1260 {importError ? <p className="mt-3 text-sm text-destructive">{importError}</p> : null}
1261 <div className="mt-6 flex flex-wrap items-center justify-end gap-3">
1262 <Button
1263 variant="ghost-muted"
1264 disabled={isImporting}
1265 onClick={importError ? finishAfterImport : () => void onDone()}
1267 {importError ? "Continue without the rest" : "Do not import projects"}
1268 </Button>
1269 <Button
1270 autoFocus
1271 disabled={isImporting || selected.length === 0}
1272 onClick={() => void runImport(selected)}
1274 {isImporting
1275 ? "Importing…"
1276 : `Import ${selected.length} ${selected.length === 1 ? "project" : "projects"}`}
1277 </Button>
1278 </div>
1279 </StepShell>
1280 );
1282​
1283// ── Shared bits ──────────────────────────────────────────────
1284​
1285function StepShell({
1286 title,
1287 description,
1288 children,
1289}: {
1290 readonly title: string;
1291 readonly description?: string;
1292 readonly children?: React.ReactNode;
1293}) {
1294 return (
1295 <>
1296 <h1 className="text-2xl font-semibold tracking-tight text-foreground">{title}</h1>
1297 {description ? (
1298 <p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">{description}</p>
1299 ) : null}
1300 {children}
1301 </>
1302 );
1304​
1305function CommandBlock({
1306 command,
1307 className,
1308 prominent = false,
1309}: {
1310 readonly command: string;
1311 readonly className?: string;
1312 readonly prominent?: boolean;
1313}) {
1314 const { copyToClipboard, isCopied } = useCopyToClipboard({
1315 timeout: 1500,
1316 target: "command",
1317 });
1318 return (
1319 <div
1320 className={cn(
1321 "flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/50 font-mono",
1322 prominent ? "px-4 py-3.5 text-base" : "px-3 py-2.5 text-sm",
1323 className,
1324 )}
1326 <span className="min-w-0 truncate">
1327 <span className="mr-2 text-muted-foreground">$</span>
1328 {command}
1329 </span>
1330 <Button
1331 size="icon-xs"
1332 variant="ghost"
1333 aria-label="Copy command"
1334 onClick={() => copyToClipboard(command, undefined)}
1336 {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
1337 </Button>
1338 </div>
1339 );