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

WelcomeWizard.tsx

1,473 lines52.7 KB

1import { useAuth } from "@clerk/react";
2import { useAtomValue } from "@effect/atom-react";
3import type {
4 AgentSessionProjectCandidate,
5 EnvironmentId,
6 ProjectId,
7 ScopedProjectRef,
8 ServerConfig,
9 ServerProvider,
10} from "@t3tools/contracts";
11import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import { CommandId, ProviderDriverKind, ThreadId } from "@t3tools/contracts";
17import * as Schema from "effect/Schema";
18import {
19 ArrowRightIcon,
20 CheckIcon,
21 ChevronLeftIcon,
22 ChevronRightIcon,
23 CloudIcon,
24 CopyIcon,
25 LinkIcon,
26 MonitorIcon,
27 TerminalIcon,
28 type LucideIcon,
29} from "lucide-react";
30import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
31​
32import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";
33import { useLocalStorage } from "../../hooks/useLocalStorage";
34import { mountOnboardingTheme } from "../../hooks/useTheme";
35import { hasCloudPublicConfig } from "../../cloud/publicConfig";
36import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
37import { useCompleteOnboarding } from "../../onboarding/firstRun";
38import {
39 partitionOnboardingProjects,
40 resolveOnboardingLandingProject,
41 resolveOnboardingProjectId,
42} from "../../onboarding/projectImport.logic";
43import {
44 getOnboardingProviderState,
45 resolveOnboardingProviderInstallCommand,
46 resolveOnboardingProviderLoginCommand,
47 selectOnboardingProvidersByDriver,
48} from "../../onboarding/providerReadiness.logic";
49import {
50 isOnboardingRelayEnvironment,
51 resolveOnboardingTargetEnvironment,
52} from "../../onboarding/targetEnvironment.logic";
53import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
54import { newProjectId, randomUUID } from "../../lib/utils";
55import { agentSessionImport, agentSessionScan } from "../../state/agentSessions";
56import { readProjects, useProjects } from "../../state/entities";
57import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
58import { useEnvironmentQuery } from "../../state/query";
59import { projectEnvironment } from "../../state/projects";
60import { serverEnvironment } from "../../state/server";
61import { terminalEnvironment } from "../../state/terminal";
62import { useAtomCommand } from "../../state/use-atom-command";
63import { connectPairing } from "../../connection/onboarding";
64import { isElectron } from "../../env";
65import { formatRelativeTimeLabel } from "../../timestampFormat";
66import { getProviderSummary } from "../settings/providerStatus";
67import { getDriverOption } from "../settings/providerDriverMeta";
68import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
69import { TerminalViewport } from "../ThreadTerminalDrawer";
70import { Button } from "../ui/button";
71import { Checkbox } from "../ui/checkbox";
72import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
73import { Input } from "../ui/input";
74import { toastManager } from "../ui/toast";
75import { cn } from "../../lib/utils";
76​
77/**
78 * First-run welcome wizard. Rendered as the full-screen `/welcome` route on a
79 * fresh install (no completed-onboarding flag, empty workspace). Flow per the
80 * onboarding overhaul spec: connection choice → sign-in/pair (remote paths) →
81 * agent setup with inline install terminal → project import → main screen.
82 * Every step past the connection gate is skippable; the whole wizard is
83 * re-runnable by clearing the flag.
84 */
85​
86type WizardStep = "connection" | "connect-machines" | "pair-direct" | "agents" | "import";
87​
88type ConnectionMode = "local" | "connect" | "direct";
89​
90/**
91 * The machine the agent and import steps run against. Local mode targets the
92 * primary environment; the remote modes prefer the machine the user just
93 * connected (the most recently added connected non-primary environment), so
94 * probing and import happen where their code lives rather than on the local
95 * server that happens to serve the app. Deliberately not a persisted
96 * "primary machine" concept — just whichever machine fits the chosen path
97 * right now, labeled inline on each step.
98 */
99function useOnboardingTargetEnvironment(
100 mode: ConnectionMode,
101 pairedEnvironmentId: EnvironmentId | null,
102) {
103 const { environments } = useEnvironments();
104 const primaryEnvironment = usePrimaryEnvironment();
105 return resolveOnboardingTargetEnvironment({
106 mode,
107 environments,
108 primaryEnvironment,
109 pairedEnvironmentId,
110 });
112​
113const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup");
114const ONBOARDING_STAGES = ["Connect", "Agents", "Projects"] as const;
115const SCAN_LIMIT_MESSAGE = "Scan limit reached. Some projects or conversations may be missing.";
116​
117export function WelcomeWizard({
118 localAvailable,
119 onDone,
120}: {
121 /**
122 * Whether the "Local Only" card is offered. True whenever the app is served
123 * by an authenticated primary server — desktop, `npx t3`, or a dev server —
124 * since that server is "this machine" regardless of the hostname the app
125 * was opened from. Only hosted-static (app.t3.codes) has no local server.
126 */
127 readonly localAvailable: boolean;
128 readonly onDone: (projectRef?: ScopedProjectRef) => void;
129}) {
130 useLayoutEffect(() => mountOnboardingTheme(), []);
131 const completeOnboarding = useCompleteOnboarding();
132 const [step, setStep] = useState<WizardStep>("connection");
133 const [mode, setMode] = useState<ConnectionMode>("local");
134 const [pairedEnvironmentId, setPairedEnvironmentId] = useState<EnvironmentId | null>(null);
135 const finishingPromiseRef = useRef<Promise<boolean> | null>(null);
136 const completionErrorToastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
137 const targetEnvironment = useOnboardingTargetEnvironment(mode, pairedEnvironmentId);
138 const stageIndex = step === "agents" ? 1 : step === "import" ? 2 : 0;
139 const finish = useCallback(
140 (projectRef?: ScopedProjectRef) => {
141 if (finishingPromiseRef.current !== null) return finishingPromiseRef.current;
142 if (completionErrorToastIdRef.current !== null) {
143 toastManager.close(completionErrorToastIdRef.current);
144 completionErrorToastIdRef.current = null;
145 }
146​
147 const completion = completeOnboarding()
148 .then(() => {
149 if (completionErrorToastIdRef.current !== null) {
150 toastManager.close(completionErrorToastIdRef.current);
151 completionErrorToastIdRef.current = null;
152 }
153 onDone(projectRef);
154 return true;
155 })
156 .catch(() => {
157 const errorToast = {
158 type: "error",
159 title: "Could not finish setup",
160 description: "Your settings could not be saved. Try again.",
161 } as const;
162 if (completionErrorToastIdRef.current === null) {
163 completionErrorToastIdRef.current = toastManager.add(errorToast);
164 } else {
165 toastManager.update(completionErrorToastIdRef.current, errorToast);
166 }
167 return false;
168 })
169 .finally(() => {
170 if (finishingPromiseRef.current === completion) {
171 finishingPromiseRef.current = null;
172 }
173 });
174 finishingPromiseRef.current = completion;
175 return completion;
176 },
177 [completeOnboarding, onDone],
178 );
179​
180 return (
181 <div className="flex h-dvh min-h-0 flex-col overflow-hidden bg-black text-foreground">
182 {isElectron ? (
183 <div
184 aria-hidden
185 className="drag-region h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 wco:pr-[var(--workspace-native-controls-inset)]"
186 />
187 ) : null}
188 <main className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">
189 <div className="mx-auto grid min-h-full w-full max-w-5xl content-center gap-10 px-6 py-12 sm:grid-cols-[170px_minmax(0,1fr)] sm:gap-14 sm:px-10 lg:px-12">
190 <aside className="flex min-w-0 flex-col justify-between sm:min-h-72">
191 <nav
192 aria-label="Setup progress"
193 className="flex flex-wrap gap-x-5 gap-y-1 sm:flex-col sm:gap-1"
194 >
195 {ONBOARDING_STAGES.map((stage, index) => (
196 <div
197 key={stage}
198 aria-current={index === stageIndex ? "step" : undefined}
199 className={cn(
200 "flex min-h-9 items-center gap-2.5 text-sm",
201 index < stageIndex
202 ? "text-success-foreground"
203 : index === stageIndex
204 ? "text-foreground"
205 : "text-muted-foreground/60",
206 )}
207 >
208 {index < stageIndex ? (
209 <CheckIcon className="size-3.5" />
210 ) : (
211 <span className="w-3.5 font-mono text-xs">0{index + 1}</span>
212 )}
213 <span>{stage}</span>
214 </div>
215 ))}
216 </nav>
217 {targetEnvironment ? (
218 <div className="mt-8 hidden items-center gap-2 text-xs text-muted-foreground sm:flex">
219 <span className="size-1.5 rounded-full bg-success" />
220 <span className="truncate">{targetEnvironment.label}</span>
221 </div>
222 ) : null}
223 </aside>
224​
225 <section className="min-w-0">
226 {step === "connection" ? (
227 <ConnectionStep
228 localAvailable={localAvailable}
229 localLabel={targetEnvironment?.label ?? "This computer"}
230 onLocal={() => {
231 setMode("local");
232 setPairedEnvironmentId(null);
233 setStep("agents");
234 }}
235 onConnect={() => {
236 setMode("connect");
237 setPairedEnvironmentId(null);
238 setStep("connect-machines");
239 }}
240 onDirect={() => {
241 setMode("direct");
242 setPairedEnvironmentId(null);
243 setStep("pair-direct");
244 }}
245 />
246 ) : step === "connect-machines" ? (
247 <ConnectMachinesStep
248 onBack={() => setStep("connection")}
249 onContinue={() => setStep("agents")}
250 />
251 ) : step === "pair-direct" ? (
252 <PairDirectStep
253 onBack={() => setStep("connection")}
254 onPaired={(environmentId) => {
255 setPairedEnvironmentId(environmentId);
256 setStep("agents");
257 }}
258 />
259 ) : step === "agents" ? (
260 <AgentsStep
261 mode={mode}
262 pairedEnvironmentId={pairedEnvironmentId}
263 onBack={() =>
264 setStep(
265 mode === "local"
266 ? "connection"
267 : mode === "connect"
268 ? "connect-machines"
269 : "pair-direct",
270 )
271 }
272 onContinue={() => setStep("import")}
273 onSkip={() => setStep("import")}
274 />
275 ) : (
276 <ImportStep
277 mode={mode}
278 pairedEnvironmentId={pairedEnvironmentId}
279 onBack={() => setStep("agents")}
280 onDone={finish}
281 />
282 )}
283 </section>
284 </div>
285 </main>
286 </div>
287 );
289​
290// ── Step 1: connection choice ────────────────────────────────
291​
292function ConnectionStep({
293 localAvailable,
294 localLabel,
295 onLocal,
296 onConnect,
297 onDirect,
298}: {
299 readonly localAvailable: boolean;
300 readonly localLabel: string;
301 readonly onLocal: () => void;
302 readonly onConnect: () => void;
303 readonly onDirect: () => void;
304}) {
305 const cloudEnabled = hasCloudPublicConfig();
306 const [choice, setChoice] = useState<"local" | "connect" | "direct">(
307 localAvailable ? "local" : cloudEnabled ? "connect" : "direct",
308 );
309​
310 const advance = () => {
311 if (choice === "local") onLocal();
312 else if (choice === "connect") onConnect();
313 else onDirect();
314 };
315​
316 return (
317 <>
318 <h1 className="text-3xl font-semibold text-foreground sm:text-[34px]">Where is your code?</h1>
319 <p className="mt-2.5 text-sm text-muted-foreground">Choose where your agents will run.</p>
320 <div className="mt-8 border-t border-border">
321 {localAvailable ? (
322 <ConnectionOption
323 icon={MonitorIcon}
324 title="This computer"
325 description={localLabel}
326 truncateDescription
327 detail="No account"
328 selected={choice === "local"}
329 onSelect={() => setChoice("local")}
330 />
331 ) : null}
332 {cloudEnabled ? (
333 <ConnectionOption
334 icon={CloudIcon}
335 title="T3 Connect"
336 description="Your computers, wherever you are"
337 detail="Sign in"
338 selected={choice === "connect"}
339 onSelect={() => setChoice("connect")}
340 />
341 ) : null}
342 <ConnectionOption
343 icon={LinkIcon}
344 title="Pair a server"
345 description="Local network or Tailscale"
346 detail="Pairing link"
347 selected={choice === "direct"}
348 onSelect={() => setChoice("direct")}
349 />
350 </div>
351 <div className="mt-7 flex justify-end">
352 <Button className="gap-2" onClick={advance}>
353 Continue
354 <ArrowRightIcon className="size-3.5" />
355 </Button>
356 </div>
357 </>
358 );
360​
361function ConnectionOption({
362 icon: Icon,
363 title,
364 description,
365 truncateDescription = false,
366 detail,
367 selected,
368 onSelect,
369}: {
370 readonly icon: LucideIcon;
371 readonly title: string;
372 readonly description: string;
373 readonly truncateDescription?: boolean;
374 readonly detail: string;
375 readonly selected: boolean;
376 readonly onSelect: () => void;
377}) {
378 return (
379 <button
380 type="button"
381 aria-pressed={selected}
382 onClick={onSelect}
383 className={cn(
384 "group flex min-h-20 w-full cursor-pointer items-center gap-4 border-b border-border px-1 py-3 text-left transition-colors",
385 "outline-none focus-visible:bg-accent focus-visible:ring-1 focus-visible:ring-ring",
386 selected
387 ? "text-foreground"
388 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
389 )}
390 >
391 <Icon
392 className={cn("size-[18px]", selected ? "text-success-foreground" : "text-icon-muted")}
393 />
394 <span className="min-w-0 flex-1">
395 <span className="block text-sm font-medium">{title}</span>
396 <span
397 className={cn(
398 "mt-1 block text-xs text-muted-foreground",
399 truncateDescription ? "truncate" : "break-words whitespace-normal",
400 )}
401 >
402 {description}
403 </span>
404 </span>
405 <span className="hidden text-xs text-muted-foreground sm:block">{detail}</span>
406 {selected ? (
407 <CheckIcon className="size-4 text-success-foreground" />
408 ) : (
409 <span className="size-4" />
410 )}
411 </button>
412 );
414​
415// ── Step 2: T3 Connect (sign in, then connect machines) ──────
416​
417const CONNECT_LOGIN_COMMAND = "npx t3 connect";
418​
419/**
420 * Sign-in and machine-connection combined: signed out shows the Clerk prompt,
421 * signed in forks on account state — zero connected machines blocks on the
422 * `npx t3 connect` command and auto-advance is left to the user pressing
423 * Continue once their machine appears; existing machines show a confirmation
424 * list with the command folded away. There is deliberately no "primary
425 * machine" selection.
426 */
427function ConnectMachinesStep({
428 onBack,
429 onContinue,
430}: {
431 readonly onBack: () => void;
432 readonly onContinue: () => void;
433}) {
434 // Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read
435 // as signed-out mid-transition.
436 const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
437 const { openAuthPrompt } = useT3ConnectAuthPrompt();
438 const { environments } = useEnvironments();
439 const primaryEnvironment = usePrimaryEnvironment();
440 const savedEnvironments = environments.filter(isOnboardingRelayEnvironment);
441 // Only a live connection counts: a saved-but-offline machine must not show
442 // the "connected" confirmation (the agents step would find nothing to
443 // probe). Its row still renders in the list either way.
444 const hasRemoteMachines = savedEnvironments.some(
445 (environment) => environment.connection.phase === "connected",
446 );
447​
448 if (!isLoaded) {
449 return <StepShell title="Sign in to T3 Connect" onBack={onBack} />;
450 }
451​
452 if (!isSignedIn) {
453 return (
454 <StepShell
455 title="Sign in to T3 Connect"
456 description="Connect your computers with one account."
457 onBack={onBack}
458 >
459 <div className="mt-6">
460 <Button onClick={openAuthPrompt}>Sign in</Button>
461 </div>
462 </StepShell>
463 );
464 }
465​
466 return (
467 <StepShell
468 title={hasRemoteMachines ? "Your computers" : "Connect your computer"}
469 description={
470 hasRemoteMachines
471 ? "Connected to your T3 account."
472 : "Run this command on the computer with your code."
473 }
474 onBack={onBack}
475 >
476 {hasRemoteMachines ? (
477 <>
478 <div className="mt-6 overflow-hidden border-y border-border">
479 <CloudEnvironmentConnectRows
480 primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
481 savedEnvironments={savedEnvironments}
482 showSavedEnvironments
483 empty={null}
484 />
485 </div>
486 <Collapsible className="mt-4">
487 <CollapsibleTrigger className="group flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground">
488 <ChevronRightIcon className="size-3.5 transition-transform duration-200 group-data-panel-open:rotate-90" />
489 Add another machine
490 </CollapsibleTrigger>
491 <CollapsiblePanel>
492 <CommandBlock command={CONNECT_LOGIN_COMMAND} className="mt-2" />
493 <p className="mt-2 text-xs text-muted-foreground">
494 Keep T3 Code running on that computer. If it is not running, open T3 Code or run{" "}
495 <code className="font-mono">npx t3 serve</code>.
496 </p>
497 </CollapsiblePanel>
498 </Collapsible>
499 <div className="mt-7 flex justify-end">
500 <Button onClick={onContinue}>Continue</Button>
501 </div>
502 </>
503 ) : (
504 <>
505 <CommandBlock command={CONNECT_LOGIN_COMMAND} className="mt-7" prominent />
506 <p className="mt-2 text-xs text-muted-foreground">
507 Keep T3 Code running on that computer. If it is not running, open T3 Code or run{" "}
508 <code className="font-mono">npx t3 serve</code>.
509 </p>
510 <div className="mt-5 overflow-hidden border-y border-border">
511 <CloudEnvironmentConnectRows
512 primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
513 savedEnvironments={savedEnvironments}
514 showSavedEnvironments
515 refreshWhileEmpty
516 empty={
517 <p className="px-1 py-4 text-xs text-muted-foreground">
518 Waiting for your computer to connect.
519 </p>
520 }
521 />
522 </div>
523 <div className="mt-7 flex flex-wrap items-center justify-between gap-3">
524 <Button variant="ghost-muted" onClick={onContinue}>
525 Skip for now
526 </Button>
527 <div className="flex flex-wrap items-center justify-end gap-3">
528 <span className="hidden text-xs text-muted-foreground sm:block">
529 Waiting for connection
530 </span>
531 <Button disabled>Continue</Button>
532 </div>
533 </div>
534 </>
535 )}
536 </StepShell>
537 );
539​
540// ── Step 2′: Direct pairing ──────────────────────────────────
541​
542/**
543 * Server-minted pairing, D-B treatment: numbered steps, `t3 pair` on the
544 * server, paste the URL here. Registers the remote environment in this
545 * browser's catalog (same path the hosted /pair surface uses).
546 */
547function PairDirectStep({
548 onBack,
549 onPaired,
550}: {
551 readonly onBack: () => void;
552 readonly onPaired: (environmentId: EnvironmentId) => void;
553}) {
554 const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false });
555 const [pairingUrl, setPairingUrl] = useState("");
556 const [errorMessage, setErrorMessage] = useState("");
557 const [isPairing, setIsPairing] = useState(false);
558 const mountedRef = useRef(true);
559​
560 useEffect(() => {
561 mountedRef.current = true;
562 return () => {
563 mountedRef.current = false;
564 };
565 }, []);
566​
567 const submit = async () => {
568 setIsPairing(true);
569 setErrorMessage("");
570 const result = await connectPairingEnvironment({ pairingUrl });
571 if (!mountedRef.current) return;
572 setIsPairing(false);
573 if (result._tag === "Success") {
574 onPaired(result.value);
575 return;
576 }
577 if (isAtomCommandInterrupted(result)) return;
578 const cause = squashAtomCommandFailure(result);
579 setErrorMessage(cause instanceof Error ? cause.message : "Pairing failed.");
580 };
581​
582 return (
583 <StepShell
584 title="Pair a server"
585 description="Connect with a one-time pairing link."
586 onBack={onBack}
587 >
588 <div className="mt-7 space-y-5">
589 <div>
590 <p className="text-sm text-muted-foreground">
591 <span className="font-mono text-muted-foreground/70">01</span> Run this on your server
592 </p>
593 <CommandBlock command="npx t3 pair" className="mt-2" />
594 <p className="mt-2 text-xs text-muted-foreground">
595 Start the server with <code className="font-mono">npx t3 serve</code> first. Add{" "}
596 <code className="font-mono">--tailscale</code> to use your tailnet.
597 </p>
598 </div>
599 <div>
600 <label className="block text-sm text-muted-foreground" htmlFor="onboarding-pairing-url">
601 <span className="font-mono text-muted-foreground/70">02</span> Paste the pairing link
602 </label>
603 <Input
604 id="onboarding-pairing-url"
605 className="mt-2"
606 size="lg"
607 autoCapitalize="none"
608 autoComplete="off"
609 autoCorrect="off"
610 spellCheck={false}
611 nativeInput
612 disabled={isPairing}
613 placeholder="https://your-server:5230/pair#token=…"
614 value={pairingUrl}
615 onChange={(event) => setPairingUrl(event.currentTarget.value)}
616 onKeyDown={(event) => {
617 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
618 if (event.key === "Enter" && pairingUrl.trim().length > 0) void submit();
619 }}
620 />
621 </div>
622 {errorMessage ? (
623 <div className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">
624 {errorMessage}
625 </div>
626 ) : null}
627 </div>
628 <div className="mt-7 flex justify-end">
629 <Button
630 disabled={isPairing || pairingUrl.trim().length === 0}
631 onClick={() => void submit()}
632 >
633 {isPairing ? "Pairing..." : "Connect"}
634 </Button>
635 </div>
636 </StepShell>
637 );
639​
640// ── Step 3: agents ───────────────────────────────────────────
641​
642const PRIMARY_AGENT_DRIVERS = ["claudeAgent", "codex"] as const;
643type OnboardingAgentDriver = (typeof PRIMARY_AGENT_DRIVERS)[number];
644​
645/** Setup values stay fixed while provider probes refresh the surrounding cards. */
646interface AgentTerminalSession {
647 readonly environmentId: EnvironmentId;
648 readonly driver: OnboardingAgentDriver;
649 readonly providerInstanceId: ServerProvider["instanceId"];
650 readonly cwd: string;
651 readonly command: string;
652 readonly keybindings: ServerConfig["keybindings"];
654​
655/**
656 * Claude Code and Codex use live probe status. Install opens the built-in
657 * terminal inline with the vendor's standalone installer pre-typed. The update
658 * RPC can't install a binary that isn't there yet (it infers the installer from
659 * the installed binary's path), and the terminal also handles the interactive
660 * login that follows.
661 */
662function AgentsStep({
663 mode,
664 pairedEnvironmentId,
665 onBack,
666 onContinue,
667 onSkip,
668}: {
669 readonly mode: ConnectionMode;
670 readonly pairedEnvironmentId: EnvironmentId | null;
671 readonly onBack: () => void;
672 readonly onContinue: () => void;
673 readonly onSkip: () => void;
674}) {
675 const targetEnvironment = useOnboardingTargetEnvironment(mode, pairedEnvironmentId);
676 if (targetEnvironment === null) {
677 return (
678 <StepShell
679 title="Your agents"
680 description="Waiting for this computer to connect."
681 onBack={onBack}
682 >
683 <div className="mt-6 flex justify-end">
684 <Button variant="ghost-muted" onClick={onSkip}>
685 Skip for now
686 </Button>
687 </div>
688 </StepShell>
689 );
690 }
691 return (
692 <ConnectedAgentsStep
693 key={targetEnvironment.environmentId}
694 environmentId={targetEnvironment.environmentId}
695 machineLabel={targetEnvironment.label}
696 onBack={onBack}
697 onContinue={onContinue}
698 onSkip={onSkip}
699 />
700 );
702​
703function ConnectedAgentsStep({
704 environmentId,
705 machineLabel,
706 onBack,
707 onContinue,
708 onSkip,
709}: {
710 readonly environmentId: EnvironmentId;
711 readonly machineLabel: string;
712 readonly onBack: () => void;
713 readonly onContinue: () => void;
714 readonly onSkip: () => void;
715}) {
716 const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));
717 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
718 reportFailure: false,
719 });
720 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
721 const [terminalSession, setTerminalSession] = useState<AgentTerminalSession | null>(null);
722​
723 // Re-probe on entry so freshly installed CLIs show up without a manual
724 // refresh; harmless when nothing changed (single-flighted per environment).
725 useEffect(() => {
726 void refreshProviders({ environmentId, input: {} });
727 }, [environmentId, refreshProviders]);
728​
729 const byDriver = useMemo(() => selectOnboardingProvidersByDriver(providers), [providers]);
730​
731 const primaryAgents = PRIMARY_AGENT_DRIVERS.map((driver) => ({
732 driver,
733 provider: byDriver.get(driver),
734 }));
735 const readyCount = primaryAgents.filter(
736 ({ provider }) => getOnboardingProviderState(provider) === "ready",
737 ).length;
738 return (
739 <StepShell title="Your agents" description={`Detected on ${machineLabel}.`} onBack={onBack}>
740 <div className="mt-7 border-t border-border">
741 {primaryAgents.map(({ driver, provider }) => (
742 <AgentCard
743 key={driver}
744 driver={driver}
745 provider={provider}
746 terminalOpen={terminalSession?.driver === driver}
747 terminalAvailable={serverConfig !== null}
748 onOpenTerminal={() => {
749 if (provider === undefined || serverConfig === null) return;
750 setTerminalSession({
751 environmentId,
752 driver,
753 providerInstanceId: provider.instanceId,
754 cwd: serverConfig.cwd,
755 command: provider.installed
756 ? resolveOnboardingProviderLoginCommand(
757 provider,
758 serverConfig.settings,
759 serverConfig.environment.platform.os,
760 )
761 : resolveOnboardingProviderInstallCommand(
762 driver,
763 serverConfig.environment.platform.os,
764 ),
765 keybindings: serverConfig.keybindings,
766 });
767 }}
768 />
769 ))}
770 </div>
771 {terminalSession !== null ? (
772 <AgentInstallTerminal
773 key={`${terminalSession.environmentId}:${terminalSession.providerInstanceId}:${terminalSession.driver}`}
774 session={terminalSession}
775 onClose={() => {
776 setTerminalSession(null);
777 void refreshProviders({ environmentId, input: {} });
778 }}
779 />
780 ) : null}
781 <div className="mt-7 flex flex-wrap items-center justify-between gap-3">
782 <Button variant="ghost-muted" onClick={onSkip}>
783 Skip
784 </Button>
785 <div className="flex flex-wrap items-center justify-end gap-3">
786 <span className="text-xs text-muted-foreground">
787 {readyCount} of {primaryAgents.length} ready
788 </span>
789 <Button className="gap-2" onClick={onContinue}>
790 Continue
791 <ArrowRightIcon className="size-3.5" />
792 </Button>
793 </div>
794 </div>
795 </StepShell>
796 );
798​
799function AgentCard({
800 driver,
801 provider,
802 terminalOpen,
803 terminalAvailable,
804 onOpenTerminal,
805}: {
806 readonly driver: OnboardingAgentDriver;
807 readonly provider: ServerProvider | undefined;
808 readonly terminalOpen: boolean;
809 readonly terminalAvailable: boolean;
810 readonly onOpenTerminal: () => void;
811}) {
812 const meta = getDriverOption(ProviderDriverKind.make(driver));
813 const Icon = meta?.icon;
814 const displayName = driver === "claudeAgent" ? "Claude Code" : (meta?.label ?? driver);
815 const summary = getProviderSummary(provider);
816 const providerState = getOnboardingProviderState(provider);
817​
818 return (
819 <div className="flex min-h-20 items-center gap-4 border-b border-border py-3">
820 {Icon ? (
821 <Icon className={cn("size-6 shrink-0", driver !== "claudeAgent" && "fill-foreground")} />
822 ) : null}
823 <div className="min-w-0 flex-1">
824 <span className="block text-sm font-medium text-foreground">{displayName}</span>
825 <p className="mt-1 truncate text-xs text-muted-foreground">
826 {summary.headline}
827 {summary.detail ? ` · ${summary.detail}` : ""}
828 </p>
829 </div>
830 <div className="shrink-0">
831 {providerState === "ready" ? (
832 <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground">
833 <CheckIcon className="size-3.5" />
834 Ready
835 </span>
836 ) : providerState === "checking" ? (
837 <span className="text-xs text-muted-foreground">Checking...</span>
838 ) : providerState === "disabled" ? (
839 <span className="text-xs text-muted-foreground">Disabled</span>
840 ) : providerState === "attention" ? (
841 <span className="text-xs text-muted-foreground">{summary.headline}</span>
842 ) : (
843 <Button
844 size="xs"
845 variant="ghost"
846 onClick={onOpenTerminal}
847 disabled={terminalOpen || !terminalAvailable}
848 >
849 <TerminalIcon className="size-3.5" />
850 {providerState === "signIn" ? "Sign in" : "Install"}
851 </Button>
852 )}
853 </div>
854 </div>
855 );
857​
858/**
859 * Inline install terminal. Opens a PTY on the connected environment under a
860 * synthetic onboarding thread id (terminals are keyed by free-form thread id;
861 * the server validates only the cwd) and pre-types the install or login
862 * command without submitting, so the user reviews and presses Enter.
863 */
864function AgentInstallTerminal({
865 session,
866 onClose,
867}: {
868 readonly session: AgentTerminalSession;
869 readonly onClose: () => void;
870}) {
871 const { command, cwd, driver, environmentId, keybindings, providerInstanceId } = session;
872 // Same terminal typography preference the thread drawer honors.
873 const [advancedTypography] = useLocalStorage(
874 TYPOGRAPHY_ADVANCED_STORAGE_KEY,
875 false,
876 Schema.Boolean,
877 );
878 const openTerminal = useAtomCommand(terminalEnvironment.open, { reportFailure: false });
879 const writeTerminal = useAtomCommand(terminalEnvironment.write, { reportFailure: false });
880 const closeTerminal = useAtomCommand(terminalEnvironment.close, { reportFailure: false });
881 const setupQueueRef = useRef(Promise.resolve());
882 const setupGenerationRef = useRef(0);
883 const activeSetupGenerationRef = useRef<number | null>(null);
884 const [terminalId] = useState(() => `onboarding-${driver}-${randomUUID()}`);
885 const threadRef = useMemo(
886 () => scopeThreadRef(environmentId, AGENT_ONBOARDING_THREAD_ID),
887 [environmentId],
888 );
889 const [setupAttempt, setSetupAttempt] = useState(0);
890 const [setupState, setSetupState] = useState<
891 "preparing" | "ready" | "openFailed" | "writeFailed"
892 >("preparing");
893 const terminalReady = setupState === "ready" || setupState === "writeFailed";
894​
895 // Keep each setup generation distinct. In Strict Mode, a canceled open can
896 // finish after the replacement setup starts; it must not close or pre-type
897 // into the replacement session that shares this terminal id.
898 useEffect(() => {
899 const generation = setupGenerationRef.current + 1;
900 setupGenerationRef.current = generation;
901 activeSetupGenerationRef.current = generation;
902 setSetupState("preparing");
903​
904 setupQueueRef.current = setupQueueRef.current.then(async () => {
905 if (activeSetupGenerationRef.current !== generation) return;
906 const opened = await openTerminal({
907 environmentId,
908 input: {
909 threadId: AGENT_ONBOARDING_THREAD_ID,
910 terminalId,
911 cwd,
912 providerInstanceId,
913 },
914 });
915 if (opened._tag !== "Success") {
916 if (activeSetupGenerationRef.current === generation) setSetupState("openFailed");
917 return;
918 }
919​
920 if (activeSetupGenerationRef.current !== generation) return;
921​
922 const wrote = await writeTerminal({
923 environmentId,
924 input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, data: command },
925 });
926 if (activeSetupGenerationRef.current !== generation) return;
927 setSetupState(wrote._tag === "Success" ? "ready" : "writeFailed");
928 });
929​
930 // Every exit path unmounts the drawer (Done, Continue/Skip, card switch,
931 // session exit), so this cleanup is the single place the PTY dies —
932 // nothing is left running behind the wizard. An interrupted install is
933 // re-runnable from the card.
934 return () => {
935 if (activeSetupGenerationRef.current === generation) {
936 activeSetupGenerationRef.current = null;
937 }
938 setupQueueRef.current = setupQueueRef.current.then(async () => {
939 await closeTerminal({
940 environmentId,
941 input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, deleteHistory: true },
942 });
943 });
944 };
945 }, [
946 closeTerminal,
947 command,
948 cwd,
949 environmentId,
950 openTerminal,
951 providerInstanceId,
952 setupAttempt,
953 terminalId,
954 writeTerminal,
955 ]);
956​
957 return (
958 <div className="thread-terminal-drawer mt-4 overflow-hidden rounded-lg border border-border/70 bg-background text-foreground">
959 <div className="flex items-center justify-between border-b border-border/60 bg-background/60 px-3 py-1.5">
960 <span className="text-[11px] font-medium text-muted-foreground">
961 {setupState === "writeFailed" ? (
962 <>
963 Run <code className="rounded bg-muted px-1 font-mono">{command}</code> in this
964 terminal.
965 </>
966 ) : setupState === "ready" ? (
967 "Review the command, then press Enter to run it."
968 ) : setupState === "openFailed" ? (
969 "Could not open the setup terminal."
970 ) : (
971 "Preparing command..."
972 )}
973 </span>
974 <div className="flex items-center gap-1">
975 {setupState === "openFailed" ? (
976 <Button size="xs" variant="ghost" onClick={() => setSetupAttempt((value) => value + 1)}>
977 Retry
978 </Button>
979 ) : null}
980 <Button size="xs" variant="ghost-muted" onClick={onClose}>
981 Close
982 </Button>
983 </div>
984 </div>
985 <div className="h-64">
986 {terminalReady ? (
987 <TerminalViewport
988 threadRef={threadRef}
989 threadId={AGENT_ONBOARDING_THREAD_ID}
990 terminalId={terminalId}
991 terminalLabel={`Install ${driver}`}
992 cwd={cwd}
993 providerInstanceId={providerInstanceId}
994 advancedTypography={advancedTypography}
995 onSessionExited={onClose}
996 focusRequestId={1}
997 autoFocus
998 visible
999 resizeEpoch={0}
1000 drawerHeight={256}
1001 keybindings={keybindings}
1002 />
1003 ) : null}
1004 </div>
1005 </div>
1006 );
1008​
1009// ── Step 4: import ───────────────────────────────────────────
1010​
1011/**
1012 * One-decision import (4B): a summary line with Import recent / Choose /
1013 * Skip. The default imports only projects touched in the last 30 days;
1014 * Choose expands a checklist including older ones. Imported projects also
1015 * receive Codex and Claude threads active within the last 30 days.
1016 */
1017function ImportStep({
1018 mode,
1019 pairedEnvironmentId,
1020 onBack,
1021 onDone,
1022}: {
1023 readonly mode: ConnectionMode;
1024 readonly pairedEnvironmentId: EnvironmentId | null;
1025 readonly onBack: () => void;
1026 readonly onDone: (projectRef?: ScopedProjectRef) => Promise<boolean>;
1027}) {
1028 const targetEnvironment = useOnboardingTargetEnvironment(mode, pairedEnvironmentId);
1029 const environmentId = targetEnvironment?.environmentId ?? null;
1030 const machineLabel = targetEnvironment?.label ?? "this machine";
1031 const scan = useEnvironmentQuery(
1032 environmentId === null ? null : agentSessionScan({ environmentId, input: {} }),
1033 );
1034 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
1035 const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false });
1036 const projects = useProjects();
1037 const [choosing, setChoosing] = useState(false);
1038 const [deselected, setDeselected] = useState<ReadonlySet<string>>(new Set());
1039 const [isImporting, setIsImporting] = useState(false);
1040 const [importError, setImportError] = useState("");
1041 const [landingProject, setLandingProject] = useState<ScopedProjectRef | null>(null);
1042 // Keep project creation attempts separate from completed history imports so both can retry.
1043 const importedProjectsRef = useRef(new Map<string, ScopedProjectRef>());
1044 const projectsWithImportedHistoryRef = useRef(new Map<string, ScopedProjectRef>());
1045 const lastImportSelectionRef = useRef<ReadonlyArray<string>>([]);
1046 const projectAttemptsRef = useRef(
1047 new Map<string, { readonly projectId: ProjectId; readonly commandId: CommandId }>(),
1048 );
1049 const importGenerationRef = useRef(0);
1050​
1051 // Candidate paths are per-environment; a target switch would otherwise
1052 // leave stale entries in the deselection set (and stale success records).
1053 useEffect(() => {
1054 importGenerationRef.current += 1;
1055 setDeselected(new Set());
1056 setIsImporting(false);
1057 setImportError("");
1058 setLandingProject(null);
1059 importedProjectsRef.current = new Map();
1060 projectsWithImportedHistoryRef.current = new Map();
1061 lastImportSelectionRef.current = [];
1062 projectAttemptsRef.current = new Map();
1063 return () => {
1064 importGenerationRef.current += 1;
1065 };
1066 }, [environmentId]);
1067​
1068 useEffect(() => {
1069 if (
1070 landingProject !== null &&
1071 landingProject.environmentId === environmentId &&
1072 projects.some(
1073 (project) =>
1074 project.id === landingProject.projectId &&
1075 project.environmentId === landingProject.environmentId,
1077 ) {
1078 setLandingProject(null);
1079 void onDone(landingProject).then((completed) => {
1080 if (!completed) setIsImporting(false);
1081 });
1083 }, [environmentId, landingProject, onDone, projects]);
1084​
1085 const { available: candidates, recent } = useMemo(
1086 () => partitionOnboardingProjects(scan.data?.candidates ?? []),
1087 [scan.data],
1088 );
1089 const more = candidates.length - recent.length;
1090 const scanTruncated = scan.data?.truncated === true;
1091 const scanLimitNotice = scanTruncated ? (
1092 <p className="mt-3 text-sm text-muted-foreground" role="status">
1093 {SCAN_LIMIT_MESSAGE}
1094 </p>
1095 ) : null;
1096​
1097 const finishAfterImport = () => {
1098 const projectRef = resolveOnboardingLandingProject(
1099 lastImportSelectionRef.current,
1100 projectsWithImportedHistoryRef.current,
1101 importedProjectsRef.current,
1102 );
1103 if (projectRef === undefined) {
1104 void onDone();
1105 return;
1107 setIsImporting(true);
1108 setLandingProject(projectRef);
1109 };
1110​
1111 const runImport = async (selection: ReadonlyArray<AgentSessionProjectCandidate>) => {
1112 if (environmentId === null || selection.length === 0) {
1113 void onDone();
1114 return;
1116 setIsImporting(true);
1117 setImportError("");
1118 lastImportSelectionRef.current = selection.map((candidate) => candidate.path);
1119 const importGeneration = importGenerationRef.current;
1120 const importedProjects = importedProjectsRef.current;
1121 const projectAttempts = projectAttemptsRef.current;
1122 // Interrupted imports are neither failures nor successes — the command was
1123 // superseded or the environment dropped — but they still didn't land, so
1124 // they must not read as "imported everything". Retries skip paths that
1125 // already landed this session (re-creating them would only trip the
1126 // duplicate-root invariant and read as a failure).
1127 let importedProjectsCount =
1128 importedProjects.size > 0
1129 ? selection.filter((candidate) => importedProjects.has(candidate.path)).length
1130 : 0;
1131 let importedThreadCount = 0;
1132 let skippedThreadCount = 0;
1133 let shouldRefreshScan = false;
1134 for (const candidate of selection) {
1135 if (
1136 importGeneration !== importGenerationRef.current ||
1137 importedProjects !== importedProjectsRef.current
1138 ) {
1139 return;
1141 if (importedProjects.has(candidate.path)) continue;
1142 let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate);
1143 if (projectId === null) {
1144 let attempt = projectAttempts.get(candidate.path);
1145 if (attempt === undefined) {
1146 const nextProjectId = newProjectId();
1147 attempt = {
1148 projectId: nextProjectId,
1149 commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`),
1150 };
1151 projectAttempts.set(candidate.path, attempt);
1153 projectId = attempt.projectId;
1154 const result = await createProject({
1155 environmentId,
1156 input: {
1157 projectId,
1158 commandId: attempt.commandId,
1159 title: candidate.title,
1160 workspaceRoot: candidate.path,
1161 createWorkspaceRootIfMissing: false,
1162 defaultModelSelection: null,
1163 },
1164 });
1165 if (
1166 importGeneration !== importGenerationRef.current ||
1167 importedProjects !== importedProjectsRef.current
1168 ) {
1169 return;
1171 if (result._tag !== "Success") {
1172 if (!isAtomCommandInterrupted(result)) {
1173 projectAttempts.delete(candidate.path);
1174 shouldRefreshScan = true;
1176 continue;
1179​
1180 const threadImportResult = await importThreads({
1181 environmentId,
1182 input: { projectId, expectedWorkspaceRoot: candidate.path },
1183 });
1184 if (
1185 importGeneration !== importGenerationRef.current ||
1186 importedProjects !== importedProjectsRef.current
1187 ) {
1188 return;
1190 if (threadImportResult._tag === "Success") {
1191 importedThreadCount += threadImportResult.value.importedCount;
1192 skippedThreadCount += threadImportResult.value.skippedCount;
1193 if (threadImportResult.value.importedCount > 0) {
1194 projectsWithImportedHistoryRef.current.set(
1195 candidate.path,
1196 scopeProjectRef(environmentId, projectId),
1197 );
1199 if (threadImportResult.value.skippedCount === 0) {
1200 importedProjectsCount += 1;
1201 importedProjects.set(candidate.path, scopeProjectRef(environmentId, projectId));
1203 } else if (!isAtomCommandInterrupted(threadImportResult)) {
1204 projectAttempts.delete(candidate.path);
1205 shouldRefreshScan = true;
1208 if (shouldRefreshScan) scan.refresh();
1209 setIsImporting(false);
1210 if (importedProjectsCount < selection.length) {
1211 if (importedThreadCount > 0 && skippedThreadCount > 0) {
1212 setImportError(
1213 `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. ${skippedThreadCount} ${skippedThreadCount === 1 ? "thread" : "threads"} could not be imported.`,
1214 );
1215 } else if (skippedThreadCount > 0) {
1216 setImportError(
1217 `${skippedThreadCount} ${skippedThreadCount === 1 ? "thread could" : "threads could"} not be imported.`,
1218 );
1219 } else if (importedThreadCount > 0) {
1220 setImportError(
1221 `Imported ${importedThreadCount} ${importedThreadCount === 1 ? "thread" : "threads"}. Some thread history could not be imported.`,
1222 );
1223 } else {
1224 setImportError("Could not import thread history.");
1226 return;
1228 finishAfterImport();
1229 };
1230​
1231 if (environmentId === null || (scan.isPending && scan.data === null)) {
1232 return (
1233 <StepShell
1234 title="Your projects"
1235 description="Looking for projects from Claude Code and Codex."
1236 onBack={onBack}
1238 <div className="mt-6 flex justify-end">
1239 <Button variant="ghost-muted" onClick={() => void onDone()}>
1240 Skip
1241 </Button>
1242 </div>
1243 </StepShell>
1244 );
1246​
1247 if (scan.error !== null || candidates.length === 0) {
1248 return (
1249 <StepShell
1250 title="Your projects"
1251 description={
1252 scan.error !== null
1253 ? "Could not check this computer for projects."
1254 : scanTruncated
1255 ? SCAN_LIMIT_MESSAGE
1256 : "No existing Claude Code or Codex projects found."
1258 onBack={onBack}
1260 {scan.error !== null ? (
1261 <p className="mt-3 text-xs text-muted-foreground">You can add projects later.</p>
1262 ) : null}
1263 <div className="mt-6 flex justify-end gap-2">
1264 {scan.error !== null ? (
1265 <Button variant="ghost" onClick={scan.refresh}>
1266 Retry
1267 </Button>
1268 ) : null}
1269 <Button
1270 variant={scan.error !== null || scanTruncated ? "ghost-muted" : "default"}
1271 onClick={() => void onDone()}
1273 {scan.error !== null || scanTruncated ? "Skip" : "Start coding"}
1274 </Button>
1275 </div>
1276 </StepShell>
1277 );
1279​
1280 if (choosing) {
1281 const selected = candidates.filter((candidate) => !deselected.has(candidate.path));
1282 return (
1283 <StepShell
1284 title="Choose your projects"
1285 onBack={() => setChoosing(false)}
1286 backDisabled={isImporting}
1287 description={`${candidates.length} found on ${machineLabel}.`}
1289 {scanLimitNotice}
1290 <div className="mt-6 max-h-72 overflow-x-hidden overflow-y-auto border-y border-border">
1291 {candidates.map((candidate) => (
1292 <label
1293 key={candidate.path}
1294 className="flex min-h-12 cursor-pointer items-center gap-3 border-b border-border/60 px-1 py-2 last:border-b-0 hover:bg-accent/50"
1296 <Checkbox
1297 checked={!deselected.has(candidate.path)}
1298 onCheckedChange={(checked) => {
1299 setDeselected((previous) => {
1300 const next = new Set(previous);
1301 if (checked === true) next.delete(candidate.path);
1302 else next.add(candidate.path);
1303 return next;
1304 });
1305 }}
1306 />
1307 <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
1308 {candidate.path}
1309 </span>
1310 <span className="hidden shrink-0 whitespace-nowrap text-[11px] text-muted-foreground sm:block">
1311 {candidate.sources.map(formatSource).join(", ")} · {candidate.threadCount}{" "}
1312 {candidate.threadCount === 1 ? "thread" : "threads"}
1313 {candidate.lastActiveAt
1314 ? ` · ${formatRelativeTimeLabel(candidate.lastActiveAt)}`
1315 : ""}
1316 </span>
1317 </label>
1318 ))}
1319 </div>
1320 {importError ? <p className="mt-3 text-sm text-destructive">{importError}</p> : null}
1321 <div className="mt-7 flex flex-wrap items-center justify-between gap-3">
1322 <Button
1323 variant="ghost-muted"
1324 disabled={isImporting}
1325 onClick={importError ? finishAfterImport : () => void onDone()}
1327 {importError ? "Continue without the rest" : "Skip"}
1328 </Button>
1329 <Button
1330 disabled={isImporting || selected.length === 0}
1331 onClick={() => void runImport(selected)}
1333 {isImporting ? "Importing..." : `Import ${selected.length}`}
1334 </Button>
1335 </div>
1336 </StepShell>
1337 );
1339​
1340 return (
1341 <StepShell
1342 title="Your recent projects"
1343 description={`${recent.length} ${recent.length === 1 ? "project" : "projects"} found on ${machineLabel}.${more > 0 ? ` ${more} more available.` : ""}`}
1344 onBack={onBack}
1345 backDisabled={isImporting}
1347 {scanLimitNotice}
1348 <div className="mt-6 border-y border-border">
1349 {recent.slice(0, 4).map((candidate) => (
1350 <div
1351 key={candidate.path}
1352 className="flex min-h-12 items-center gap-3 border-b border-border/60 px-1 py-2 last:border-b-0"
1354 <CheckIcon className="size-3.5 shrink-0 text-success-foreground" />
1355 <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
1356 {candidate.path}
1357 </span>
1358 <span className="hidden shrink-0 whitespace-nowrap text-[11px] text-muted-foreground sm:block">
1359 {candidate.sources.map(formatSource).join(", ")}
1360 </span>
1361 </div>
1362 ))}
1363 {recent.length > 4 ? (
1364 <p className="px-1 py-3 text-xs text-muted-foreground">
1365 {recent.length - 4} more projects
1366 </p>
1367 ) : null}
1368 </div>
1369 {importError ? <p className="mt-3 text-sm text-destructive">{importError}</p> : null}
1370 <div className="mt-7 flex flex-wrap items-center justify-between gap-3">
1371 <Button
1372 variant="ghost-muted"
1373 disabled={isImporting}
1374 onClick={importError ? finishAfterImport : () => void onDone()}
1376 {importError ? "Continue without the rest" : "Skip"}
1377 </Button>
1378 <div className="flex items-center gap-2">
1379 <Button variant="ghost" disabled={isImporting} onClick={() => setChoosing(true)}>
1380 Choose
1381 </Button>
1382 <Button
1383 disabled={isImporting || recent.length === 0}
1384 onClick={() => void runImport(recent)}
1386 {isImporting
1387 ? "Importing..."
1388 : `Import ${recent.length} ${recent.length === 1 ? "project" : "projects"}`}
1389 </Button>
1390 </div>
1391 </div>
1392 </StepShell>
1393 );
1395​
1396// ── Shared bits ──────────────────────────────────────────────
1397​
1398function StepShell({
1399 title,
1400 description,
1401 onBack,
1402 backDisabled = false,
1403 children,
1404}: {
1405 readonly title: string;
1406 readonly description?: string;
1407 readonly onBack?: () => void;
1408 readonly backDisabled?: boolean;
1409 readonly children?: React.ReactNode;
1410}) {
1411 return (
1412 <>
1413 {onBack ? (
1414 <Button
1415 className="mb-5 -ml-2"
1416 disabled={backDisabled}
1417 onClick={onBack}
1418 size="xs"
1419 variant="ghost-muted"
1421 <ChevronLeftIcon className="size-3.5" />
1422 Back
1423 </Button>
1424 ) : null}
1425 <h1 className="text-3xl font-semibold text-foreground sm:text-[34px]">{title}</h1>
1426 {description ? (
1427 <p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">{description}</p>
1428 ) : null}
1429 {children}
1430 </>
1431 );
1433​
1434function CommandBlock({
1435 command,
1436 className,
1437 prominent = false,
1438}: {
1439 readonly command: string;
1440 readonly className?: string;
1441 readonly prominent?: boolean;
1442}) {
1443 const { copyToClipboard, isCopied } = useCopyToClipboard({
1444 timeout: 1500,
1445 target: "command",
1446 });
1447 return (
1448 <div
1449 className={cn(
1450 "flex items-center justify-between gap-3 border border-border bg-accent/50 font-mono",
1451 prominent ? "px-4 py-3.5 text-base" : "px-3 py-2.5 text-sm",
1452 className,
1453 )}
1455 <span className="min-w-0 truncate">
1456 <span className="mr-2 text-muted-foreground">$</span>
1457 {command}
1458 </span>
1459 <Button
1460 size="icon-xs"
1461 variant="ghost"
1462 aria-label="Copy command"
1463 onClick={() => copyToClipboard(command, undefined)}
1465 {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
1466 </Button>
1467 </div>
1468 );
1470​
1471function formatSource(source: "claudeAgent" | "codex"): string {
1472 return source === "claudeAgent" ? "Claude" : "Codex";