TypeScript
fix(web): make onboarding a shared multi-computer wizard (#10465)
Julius Marmingef729e8fd837e
diff --git a/apps/web/src/components/AnimatedHeight.tsx b/apps/web/src/components/AnimatedHeight.tsxindex d0e21b3907e..719c0149484 100644--- a/apps/web/src/components/AnimatedHeight.tsx+++ b/apps/web/src/components/AnimatedHeight.tsx@@ -4,7 +4,14 @@ import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from "reconst HEIGHT_TRANSITION_FALLBACK_MS = 250;-export function AnimatedHeight({ children }: { readonly children: ReactNode }) {+export function AnimatedHeight({+ children,+ holdHeight = false,+}: {+ readonly children: ReactNode;+ /** Retain the previous content height while a replacement is loading. */+ readonly holdHeight?: boolean;+}) {const contentRef = useRef<HTMLDivElement>(null);const [heightState, setHeightState] = useState<{readonly height: number | null;@@ -22,6 +29,7 @@ export function AnimatedHeight({ children }: { readonly children: ReactNode }) {}, [heightState.height, heightState.isClipping]);useLayoutEffect(() => {+ if (holdHeight) return;const element = contentRef.current;if (!element) return;let firstFrameId: number | null = null;@@ -67,7 +75,7 @@ export function AnimatedHeight({ children }: { readonly children: ReactNode }) {resizeObserver.disconnect();cancelPendingFrames();};- }, []);+ }, [holdHeight]);return (<div@@ -85,7 +93,9 @@ export function AnimatedHeight({ children }: { readonly children: ReactNode }) {);}}>- <div ref={contentRef}>{children}</div>+ <div ref={contentRef} style={holdHeight ? { height: "100%" } : undefined}>+ {children}+ </div></div>);}diff --git a/apps/web/src/components/NoProjectsHero.tsx b/apps/web/src/components/NoProjectsHero.tsxnew file mode 100644index 00000000000..09bd92c82ec--- /dev/null+++ b/apps/web/src/components/NoProjectsHero.tsx@@ -0,0 +1,36 @@+import { PlusIcon } from "lucide-react";+import { useCallback } from "react";++import { openCommandPalette } from "../commandPaletteBus";+import { Button } from "./ui/button";+import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty";+import { SidebarInset } from "./ui/sidebar";++export function NoProjectsHero() {+ const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);++ return (+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">+ <Empty className="flex-1">+ <div className="w-full max-w-lg px-8 py-12">+ <EmptyHeader className="max-w-none">+ <EmptyTitle className="text-foreground text-2xl sm:text-3xl">+ What should we work on?+ </EmptyTitle>+ <EmptyDescription className="mt-2 text-sm text-muted-foreground/78">+ Add a project to start your first thread.+ </EmptyDescription>+ <div className="mt-6 flex justify-center">+ <Button size="sm" onClick={openAddProject}>+ <PlusIcon className="size-4" />+ Add project+ </Button>+ </div>+ </EmptyHeader>+ </div>+ </Empty>+ </div>+ </SidebarInset>+ );+}diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsxindex e82135dc44b..6474c2208c7 100644--- a/apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsx+++ b/apps/web/src/components/cloud/CloudEnvironmentConnectList.test.tsx@@ -3,7 +3,7 @@ import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";import { EnvironmentId } from "@t3tools/contracts";import * as Option from "effect/Option";import { AsyncResult } from "effect/unstable/reactivity";-import { act, type ButtonHTMLAttributes } from "react";+import { act, useState, type ButtonHTMLAttributes, type ReactNode } from "react";import { create, type ReactTestRenderer } from "react-test-renderer";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";@@ -42,6 +42,25 @@ vi.mock("~/state/environments", async () => {return { useRelayEnvironmentDiscovery: () => useSyncExternalStore(subscribe, read, read) };});vi.mock("../ConnectionStatusDot", () => ({ ConnectionStatusDot: () => null }));+vi.mock("../ui/tooltip", () => ({+ Tooltip: ({ children }: { children: ReactNode }) => children,+ TooltipTrigger: ({ children }: { children: ReactNode }) => <span>{children}</span>,+ TooltipPopup: () => null,+}));+vi.mock("../ui/checkbox", () => ({+ Checkbox: (props: {+ checked: boolean;+ disabled: boolean;+ onCheckedChange: (checked: boolean) => void;+ }) => (+ <input+ type="checkbox"+ checked={props.checked}+ disabled={props.disabled}+ onChange={(event) => props.onCheckedChange(event.target.checked)}+ />+ ),+}));vi.mock("../ui/button", () => ({Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (<button {...props}>{children}</button>@@ -118,6 +137,7 @@ beforeEach(() => {error: Option.none(),};discovery.listEnvironments.mockReset().mockResolvedValue(new Map());+ discovery.register.mockReset().mockResolvedValue(AsyncResult.success(undefined));discovery.refresh.mockReset().mockImplementation(async () => {publish({ environments: new Map(), refreshing: true, offline: false, error: Option.none() });const environments = await discovery.listEnvironments();@@ -133,6 +153,71 @@ afterEach(async () => {});describe("cloud onboarding discovery", () => {+ it("signals that the section can expand after initial discovery settles", async () => {+ let finishDiscovery!: (environments: DiscoveredEnvironments) => void;+ discovery.listEnvironments.mockReturnValue(+ new Promise((resolve) => {+ finishDiscovery = resolve;+ }),+ );+ const onDiscoveryReady = vi.fn();+ await act(async () => {+ renderer = create(+ <CloudEnvironmentConnectRows+ primaryEnvironmentId={null}+ savedEnvironments={[]}+ onDiscoveryReady={onDiscoveryReady}+ />,+ );+ });+ expect(onDiscoveryReady).not.toHaveBeenCalled();+ await act(async () => {+ finishDiscovery(linkedMachines);+ });+ expect(onDiscoveryReady).toHaveBeenCalledTimes(1);+ expect(renderer!.root.findByType("button").children).toEqual(["Connect"]);+ });++ it("connects and selects discovered computers by default without overwriting deselection", async () => {+ discovery.listEnvironments.mockResolvedValue(linkedMachines);+ const autoSelectedComputers = new Set<EnvironmentId>();+ function Setup() {+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId>>(new Set());+ return (+ <CloudEnvironmentConnectRows+ primaryEnvironmentId={null}+ savedEnvironments={[]}+ showSavedEnvironments+ selection={{+ autoSelectedComputers,+ selectedIds,+ onChange: (id, checked) =>+ setSelectedIds((current) => {+ const next = new Set(current);+ if (checked) next.add(id);+ else next.delete(id);+ return next;+ }),+ }}+ />+ );+ }+ await act(async () => {+ renderer = create(<Setup />);+ });++ expect(discovery.register).toHaveBeenCalledTimes(1);+ expect(renderer!.root.findByType("input").props.checked).toBe(true);+ await act(async () => {+ await renderer!.root.findByType("input").props.onChange({ target: { checked: false } });+ });+ await act(async () => {+ publish({ ...discovery.state!, environments: new Map(linkedMachines) });+ });+ expect(renderer!.root.findByType("input").props.checked).toBe(false);+ expect(discovery.register).toHaveBeenCalledTimes(1);+ });+it("shows a newly linked computer without remounting and stops polling once found", async () => {discovery.listEnvironments.mockResolvedValueOnce(new Map())@@ -152,6 +237,31 @@ describe("cloud onboarding discovery", () => {expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);});+ it("keeps a discovered computer visible when it is added to the browser", async () => {+ discovery.listEnvironments.mockResolvedValue(linkedMachines);+ await mount();+ expect(renderer!.root.findByType("button").children).toEqual(["Connect"]);+ await act(async () => {+ renderer!.update(+ <CloudEnvironmentConnectRows+ primaryEnvironmentId={null}+ savedEnvironments={[+ {+ environmentId: newMachineId,+ connection: { phase: "connected", error: null, traceId: null },+ },+ ]}+ showSavedEnvironments+ refreshWhileEmpty+ />,+ );+ });+ expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([+ "Work laptop",+ ]);+ expect(renderer!.root.findByType("button").children).toEqual(["Connected"]);+ });+it("waits while hidden and refreshes immediately when visible again", async () => {page.visibilityState = "hidden";await mount();diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsxindex 747b82d1e55..abc643965c0 100644--- a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx+++ b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx@@ -20,9 +20,11 @@ import { useRelayEnvironmentDiscovery } from "~/state/environments";import { useAtomCommand } from "~/state/use-atom-command";import { ConnectionStatusDot } from "../ConnectionStatusDot";import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRows";+import { Checkbox } from "../ui/checkbox";import { Button } from "../ui/button";import { Skeleton } from "../ui/skeleton";import { toastManager } from "../ui/toast";+import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";const EMPTY_DISCOVERY_REFRESH_INTERVAL_MS = 5_000;@@ -59,12 +61,20 @@ export function CloudEnvironmentConnectRows({showSavedEnvironments = false,refreshWhileEmpty = false,empty = null,+ selection,+ onDiscoveryReady,}: {readonly primaryEnvironmentId: EnvironmentId | null;readonly savedEnvironments: ReadonlyArray<SavedCloudEnvironmentConnection>;readonly showSavedEnvironments?: boolean;readonly refreshWhileEmpty?: boolean;readonly empty?: ReactNode;+ readonly onDiscoveryReady?: () => void;+ readonly selection?: {+ readonly autoSelectedComputers?: Set<EnvironmentId>;+ readonly selectedIds: ReadonlySet<EnvironmentId>;+ readonly onChange: (environmentId: EnvironmentId, selected: boolean) => void;+ };}) {const environmentsState = useRelayEnvironmentDiscovery();const registerEnvironment = useAtomCommand(environmentCatalog.register, {@@ -89,33 +99,43 @@ export function CloudEnvironmentConnectRows({),[registerEnvironment],);- const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(- null,- );+ const [connectingEnvironmentIds, setConnectingEnvironmentIds] = useState<+ ReadonlySet<EnvironmentId>+ >(new Set());const savedById = new Map(savedEnvironments.map((environment) => [environment.environmentId, environment]),);useEffect(() => {- if (!refreshWhileEmpty || document.visibilityState === "visible") {- void refreshRelayEnvironments();+ let active = true;+ if (onDiscoveryReady || !refreshWhileEmpty || document.visibilityState === "visible") {+ void refreshRelayEnvironments().then(() => {+ if (active) onDiscoveryReady?.();+ });}- }, [refreshRelayEnvironments, refreshWhileEmpty]);+ return () => {+ active = false;+ };+ }, [refreshRelayEnvironments, refreshWhileEmpty, onDiscoveryReady]);const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {- setConnectingEnvironmentId(environment.environmentId);+ setConnectingEnvironmentIds((current) => new Set([...current, environment.environmentId]));const result = await connectRelayEnvironment(environment);- setConnectingEnvironmentId(null);+ setConnectingEnvironmentIds((current) => {+ const next = new Set(current);+ next.delete(environment.environmentId);+ return next;+ });if (result._tag === "Success") {toastManager.add({type: "success",title: "Environment added",description: `Connecting to ${environment.label} through T3 Connect.`,});- return;+ return true;}if (isAtomCommandInterrupted(result)) {- return;+ return false;}const cause = squashAtomCommandFailure(result);const message =@@ -135,6 +155,7 @@ export function CloudEnvironmentConnectRows({}: undefined,});+ return false;};const visibleEnvironments = [...environmentsState.environments.values()].filter(@@ -142,6 +163,25 @@ export function CloudEnvironmentConnectRows({environment.environmentId !== primaryEnvironmentId &&(showSavedEnvironments || !savedById.has(environment.environmentId)),);+ const selectNewComputers = useEffectEvent(() => {+ const seen = selection?.autoSelectedComputers;+ if (!selection || !seen) return;+ for (const { environment } of visibleEnvironments) {+ const id = environment.environmentId;+ if (seen.has(id)) continue;+ seen.add(id);+ selection.onChange(id, true);+ if (!savedById.has(id)) {+ void connectEnvironment(environment).then((connected) => {+ if (!connected) selection.onChange(id, false);+ });+ }+ }+ });+ useEffect(() => {+ selectNewComputers();+ }, [environmentsState.environments]);+// Discovery clears its list on refresh, so poll only until a machine appears.const shouldRefreshWhileEmpty =refreshWhileEmpty && visibleEnvironments.length === 0 && !environmentsState.offline;@@ -254,6 +294,48 @@ export function CloudEnvironmentConnectRows({: availability === "checking"? "Available · Checking relay status…": (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable");+ if (selection) {+ return (+ <label+ key={environment.environmentId}+ className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 has-disabled:cursor-default"+ >+ <Checkbox+ checked={selection.selectedIds.has(environment.environmentId)}+ disabled={connectingEnvironmentIds.has(environment.environmentId)}+ onCheckedChange={async (checked) => {+ selection.onChange(environment.environmentId, checked);+ if (checked && !savedEnvironment) {+ const connected = await connectEnvironment(environment);+ if (!connected) selection.onChange(environment.environmentId, false);+ }+ }}+ />+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{environment.label}</span>+ <Tooltip>+ <TooltipTrigger+ render={<span tabIndex={0} />}+ className={cn(+ "max-w-[45%] shrink-0 truncate text-xs",+ savedConnection?.tone === "error" ? "text-destructive" : "text-muted-foreground",+ )}+ >+ {connectingEnvironmentIds.has(environment.environmentId)+ ? "Connecting…"+ : (savedConnection?.buttonLabel ??+ (availability === "online"+ ? "Available"+ : availability === "offline"+ ? "Offline"+ : availability === "error"+ ? "Unavailable"+ : "Checking…"))}+ </TooltipTrigger>+ <TooltipPopup className="max-w-80 break-words">{statusText}</TooltipPopup>+ </Tooltip>+ </label>+ );+ }return (<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}><div className={ITEM_ROW_INNER_CLASSNAME}>@@ -301,10 +383,10 @@ export function CloudEnvironmentConnectRows({) : (<Buttonsize="sm"- disabled={connectingEnvironmentId !== null}+ disabled={connectingEnvironmentIds.size > 0}onClick={() => void connectEnvironment(environment)}>- {connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}+ {connectingEnvironmentIds.has(environment.environmentId) ? "Connecting…" : "Connect"}</Button>)}</div>diff --git a/apps/web/src/components/onboarding/FirstRunGate.tsx b/apps/web/src/components/onboarding/FirstRunGate.tsxindex 6debb0376bd..b7c378537fc 100644--- a/apps/web/src/components/onboarding/FirstRunGate.tsx+++ b/apps/web/src/components/onboarding/FirstRunGate.tsx@@ -2,14 +2,13 @@ import { RefreshIcon } from "~/components/ui/refresh-icon";import { useAtomValue } from "@effect/atom-react";import { useLocation, useNavigate } from "@tanstack/react-router";import { Atom } from "effect/unstable/reactivity";-import { useEffect, useLayoutEffect, useState } from "react";+import { useEffect, useState } from "react";import {ensureClientSettingsHydrated,useClientSettings,useClientSettingsHydrationStatus,} from "../../hooks/useSettings";-import { mountOnboardingTheme } from "../../hooks/useTheme";import { useCompleteOnboarding } from "../../onboarding/firstRun";import {isFirstRunWorkspaceProvenanceAuthoritative,@@ -104,13 +103,6 @@ export function FirstRunGate({}));const { decision, stalled } = gateState;const settingsReadFailed = hydrationStatus === "failed" || hydrationStatus === "retrying";- const ownsOnboardingTheme = settingsReadFailed || stalled || decision === "wizard";-- useLayoutEffect(() => {- if (!ownsOnboardingTheme) return;- return mountOnboardingTheme();- }, [ownsOnboardingTheme]);-// A workspace still counts as fresh when its only content is the server's// own cwd auto-bootstrap: web mode creates a project + thread from cwd at// startup (`autoBootstrapProjectFromCwd` defaults on there), so "nodiff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsxindex c43dbf6a445..24e38d353a8 100644--- a/apps/web/src/components/onboarding/WelcomeWizard.tsx+++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx@@ -1,7 +1,6 @@import { useAuth } from "@clerk/react";import { useAtomValue } from "@effect/atom-react";import type {- AgentSessionProjectCandidate,EnvironmentId,ProjectId,ScopedProjectRef,@@ -18,25 +17,23 @@ import * as Schema from "effect/Schema";import {ArrowRightIcon,CheckIcon,- ChevronLeftIcon,ChevronRightIcon,CloudIcon,CopyIcon,LinkIcon,MonitorIcon,TerminalIcon,- type LucideIcon,} from "lucide-react";-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";import { useLocalStorage } from "../../hooks/useLocalStorage";-import { mountOnboardingTheme } from "../../hooks/useTheme";import { hasCloudPublicConfig } from "../../cloud/publicConfig";import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";import { useCompleteOnboarding } from "../../onboarding/firstRun";import {partitionOnboardingProjects,+ onboardingProjectKey,resolveOnboardingLandingProject,resolveOnboardingProjectId,} from "../../onboarding/projectImport.logic";@@ -46,36 +43,37 @@ import {resolveOnboardingProviderLoginCommand,selectOnboardingProvidersByDriver,} from "../../onboarding/providerReadiness.logic";-import {- isOnboardingRelayEnvironment,- resolveOnboardingTargetEnvironment,-} from "../../onboarding/targetEnvironment.logic";import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";import { newProjectId, randomUUID } from "../../lib/utils";-import { agentSessionImport, agentSessionScan } from "../../state/agentSessions";+import { agentSessionImport } from "../../state/agentSessions";import { readProjects, useProjects } from "../../state/entities";import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";-import { useEnvironmentQuery } from "../../state/query";+import { isOnboardingRelayEnvironment } from "../../onboarding/targetEnvironment.logic";+import { useProjectScans } from "../../onboarding/useProjectScans";import { projectEnvironment } from "../../state/projects";import { serverEnvironment } from "../../state/server";import { terminalEnvironment } from "../../state/terminal";import { useAtomCommand } from "../../state/use-atom-command";import { connectPairing } from "../../connection/onboarding";-import { isElectron } from "../../env";-import { formatRelativeTimeLabel } from "../../timestampFormat";import { getProviderSummary } from "../settings/providerStatus";import { getDriverOption } from "../settings/providerDriverMeta";-import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";import { TerminalViewport } from "../ThreadTerminalDrawer";+import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";+import { T3Wordmark } from "../T3Wordmark";import { Button } from "../ui/button";import { Checkbox } from "../ui/checkbox";import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";import { Input } from "../ui/input";+import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";+import { ScrollArea } from "../ui/scroll-area";+import { Spinner } from "../ui/spinner";+import { WizardPanel, WizardSteps } from "../ui/wizard";+import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog";import { toastManager } from "../ui/toast";import { cn } from "../../lib/utils";/**- * First-run welcome wizard. Rendered as the full-screen `/welcome` route on a+ * First-run welcome wizard. Rendered over the workspace at `/welcome` on a* fresh install (no completed-onboarding flag, empty workspace). Flow per the* onboarding overhaul spec: connection choice → sign-in/pair (remote paths) →* agent setup with inline install terminal → project import → main screen.@@ -83,32 +81,8 @@ import { cn } from "../../lib/utils";* re-runnable by clearing the flag.*/-type WizardStep = "connection" | "connect-machines" | "pair-direct" | "agents" | "import";--type ConnectionMode = "local" | "connect" | "direct";--/**- * The machine the agent and import steps run against. Local mode targets the- * primary environment; the remote modes prefer the machine the user just- * connected (the most recently added connected non-primary environment), so- * probing and import happen where their code lives rather than on the local- * server that happens to serve the app. Deliberately not a persisted- * "primary machine" concept — just whichever machine fits the chosen path- * right now, labeled inline on each step.- */-function useOnboardingTargetEnvironment(- mode: ConnectionMode,- pairedEnvironmentId: EnvironmentId | null,-) {- const { environments } = useEnvironments();- const primaryEnvironment = usePrimaryEnvironment();- return resolveOnboardingTargetEnvironment({- mode,- environments,- primaryEnvironment,- pairedEnvironmentId,- });-}+type WizardStep = "connection" | "agents" | "import";+const NO_ENVIRONMENTS: readonly EnvironmentId[] = [];const AGENT_ONBOARDING_THREAD_ID = ThreadId.make("onboarding-agent-setup");const ONBOARDING_STAGES = ["Connect", "Agents", "Projects"] as const;@@ -118,23 +92,48 @@ export function WelcomeWizard({localAvailable,onDone,}: {- /**- * Whether the "Local Only" card is offered. True whenever the app is served- * by an authenticated primary server — desktop, `npx t3`, or a dev server —- * since that server is "this machine" regardless of the hostname the app- * was opened from. Only hosted-static (app.t3.codes) has no local server.- */+ /** Whether this client is authenticated to the server serving the app. */readonly localAvailable: boolean;readonly onDone: (projectRef?: ScopedProjectRef) => void;}) {- useLayoutEffect(() => mountOnboardingTheme(), []);const completeOnboarding = useCompleteOnboarding();const [step, setStep] = useState<WizardStep>("connection");- const [mode, setMode] = useState<ConnectionMode>("local");- const [pairedEnvironmentId, setPairedEnvironmentId] = useState<EnvironmentId | null>(null);+ const { environments } = useEnvironments();+ const [selection, setSelection] = useState<ReadonlySet<EnvironmentId> | null>(null);+ const autoSelectedComputers = useRef(new Set<EnvironmentId>());+ const [setupIds, setSetupIds] = useState<readonly EnvironmentId[]>([]);+ const [isImporting, setIsImporting] = useState(false);const finishingPromiseRef = useRef<Promise<boolean> | null>(null);const completionErrorToastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);- const targetEnvironment = useOnboardingTargetEnvironment(mode, pairedEnvironmentId);+ const primaryEnvironment = usePrimaryEnvironment();+ useEffect(() => {+ const newComputers = environments.filter(+ (environment) => !autoSelectedComputers.current.has(environment.environmentId),+ );+ if (newComputers.length === 0) return;+ for (const environment of newComputers) {+ autoSelectedComputers.current.add(environment.environmentId);+ }+ setSelection(+ (current) =>+ new Set([+ ...(current ?? []),+ ...newComputers.map((environment) => environment.environmentId),+ ]),+ );+ }, [environments]);+ const selectedIds =+ selection ?? new Set(primaryEnvironment ? [primaryEnvironment.environmentId] : []);+ const scans = useProjectScans(step === "import" ? setupIds : NO_ENVIRONMENTS);+ const isLoadingProjects =+ step === "import" &&+ scans.every((scan) => scan.data === null) &&+ scans.some((scan) => scan.isPending);+ const startSetup = (ids: readonly EnvironmentId[]) => {+ if (ids.length === 0) return;+ setSetupIds(ids);+ setStep("agents");+ };const stageIndex = step === "agents" ? 1 : step === "import" ? 2 : 0;const finish = useCallback((projectRef?: ScopedProjectRef) => {@@ -178,178 +177,216 @@ export function WelcomeWizard({);return (- <div className="flex h-dvh min-h-0 flex-col overflow-hidden bg-background text-foreground">- {isElectron ? (- <div- aria-hidden- className="drag-region h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 wco:pr-[var(--workspace-native-controls-inset)]"- />- ) : null}- <main className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">- <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">- <aside className="flex min-w-0 flex-col justify-between sm:min-h-72">- <nav- aria-label="Setup progress"- className="flex flex-wrap gap-x-5 gap-y-1 sm:flex-col sm:gap-1"- >- {ONBOARDING_STAGES.map((stage, index) => (- <div- key={stage}- aria-current={index === stageIndex ? "step" : undefined}- className={cn(- "flex min-h-9 items-center gap-2.5 text-sm",- index < stageIndex- ? "text-success-foreground"- : index === stageIndex- ? "text-foreground"- : "text-muted-foreground/60",- )}- >- {index < stageIndex ? (- <CheckIcon className="size-3.5" />- ) : (- <span className="w-3.5 font-mono text-xs">0{index + 1}</span>- )}- <span>{stage}</span>- </div>- ))}- </nav>- {targetEnvironment ? (- <div className="mt-8 hidden items-center gap-2 text-xs text-muted-foreground sm:flex">- <span className="size-1.5 rounded-full bg-success" />- <span className="truncate">{targetEnvironment.label}</span>- </div>- ) : null}- </aside>+ <Dialog open disablePointerDismissal onOpenChange={(_, event) => event.cancel()}>+ <DialogPopup+ className="max-w-xl overflow-x-hidden overflow-y-auto"+ bottomStickOnMobile={false}+ showCloseButton={false}+ initialFocus={() => document.getElementById("onboarding-pairing-url") ?? true}+ >+ <DialogTitle className="sr-only">Set up T3 Code</DialogTitle>+ <div className="flex min-h-0 flex-col">+ <DialogHeader className="gap-4">+ <div className="flex items-baseline gap-1.5" role="img" aria-label="T3 Code">+ <T3Wordmark className="h-4 w-auto shrink-0" aria-hidden />+ <span className="text-[1.4rem] font-medium tracking-tight text-muted-foreground">+ Code+ </span>+ </div>+ <WizardSteps+ steps={ONBOARDING_STAGES}+ currentStep={stageIndex}+ isStepDisabled={(index) => isImporting || index >= stageIndex}+ onStepChange={(index) => {+ if (isImporting || index > stageIndex) return;+ setStep(index === 0 ? "connection" : "agents");+ }}+ />+ </DialogHeader>- <section className="min-w-0">+ <WizardPanel className="min-w-0" holdHeight={isLoadingProjects}>{step === "connection" ? (<ConnectionStep- localAvailable={localAvailable}- localLabel={targetEnvironment?.label ?? "This computer"}- onLocal={() => {- setMode("local");- setPairedEnvironmentId(null);- setStep("agents");- }}- onConnect={() => {- setMode("connect");- setPairedEnvironmentId(null);- setStep("connect-machines");- }}- onDirect={() => {- setMode("direct");- setPairedEnvironmentId(null);- setStep("pair-direct");- }}- />- ) : step === "connect-machines" ? (- <ConnectMachinesStep- onBack={() => setStep("connection")}- onContinue={() => setStep("agents")}- />- ) : step === "pair-direct" ? (- <PairDirectStep- onBack={() => setStep("connection")}+ expandPairingInitially={!localAvailable && !hasCloudPublicConfig()}+ selectedIds={selectedIds}+ autoSelectedComputers={autoSelectedComputers.current}+ onSelectionChange={setSelection}+ onToggleEnvironment={(environmentId, checked) =>+ setSelection((current) => {+ const next = new Set(current ?? selectedIds);+ if (checked) next.add(environmentId);+ else next.delete(environmentId);+ return next;+ })+ }+ onContinue={() =>+ startSetup(+ environments+ .filter((environment) => selectedIds.has(environment.environmentId))+ .map((environment) => environment.environmentId),+ )+ }onPaired={(environmentId) => {- setPairedEnvironmentId(environmentId);- setStep("agents");+ setSelection(new Set([...selectedIds, environmentId]));}}/>) : step === "agents" ? (- <AgentsStep- mode={mode}- pairedEnvironmentId={pairedEnvironmentId}- onBack={() =>- setStep(- mode === "local"- ? "connection"- : mode === "connect"- ? "connect-machines"- : "pair-direct",- )- }- onContinue={() => setStep("import")}- onSkip={() => setStep("import")}- />+ <AgentsStep environmentIds={setupIds} onContinue={() => setStep("import")} />) : (<ImportStep- mode={mode}- pairedEnvironmentId={pairedEnvironmentId}- onBack={() => setStep("agents")}+ scans={scans}+ isImporting={isImporting}+ setIsImporting={setIsImporting}onDone={finish}/>)}- </section>+ </WizardPanel></div>- </main>- </div>+ </DialogPopup>+ </Dialog>);}// ── Step 1: connection choice ────────────────────────────────function ConnectionStep({- localAvailable,- localLabel,- onLocal,- onConnect,- onDirect,+ autoSelectedComputers,+ expandPairingInitially,+ selectedIds,+ onSelectionChange,+ onToggleEnvironment,+ onContinue,+ onPaired,}: {- readonly localAvailable: boolean;- readonly localLabel: string;- readonly onLocal: () => void;- readonly onConnect: () => void;- readonly onDirect: () => void;+ readonly autoSelectedComputers: Set<EnvironmentId>;+ readonly expandPairingInitially: boolean;+ readonly selectedIds: ReadonlySet<EnvironmentId>;+ readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId>) => void;+ readonly onToggleEnvironment: (environmentId: EnvironmentId, checked: boolean) => void;+ readonly onContinue: () => void;+ readonly onPaired: (environmentId: EnvironmentId) => void;}) {+ const { environments } = useEnvironments();const cloudEnabled = hasCloudPublicConfig();- const [choice, setChoice] = useState<"local" | "connect" | "direct">(- localAvailable ? "local" : cloudEnabled ? "connect" : "direct",+ const directEnvironments = environments.filter(+ (environment) => !cloudEnabled || !isOnboardingRelayEnvironment(environment),);-- const advance = () => {- if (choice === "local") onLocal();- else if (choice === "connect") onConnect();- else onDirect();- };-+ const [pairingOpen, setPairingOpen] = useState(expandPairingInitially);+ const [isPairing, setIsPairing] = useState(false);+ const ready =+ selectedIds.size > 0 &&+ [...selectedIds].every((id) =>+ environments.some(+ (environment) =>+ environment.environmentId === id && environment.connection.phase === "connected",+ ),+ );+ const continueRef = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ if (+ ready &&+ (document.activeElement === document.body ||+ document.activeElement?.getAttribute("role") === "dialog")+ ) {+ continueRef.current?.focus();+ }+ }, [ready]);return (<>- <h1 className="text-3xl font-semibold text-foreground sm:text-[34px]">Where is your code?</h1>- <p className="mt-2.5 text-sm text-muted-foreground">Choose where your agents will run.</p>- <div className="mt-8 border-t border-border">- {localAvailable ? (- <ConnectionOption- icon={MonitorIcon}- title="This computer"- description={localLabel}- truncateDescription- detail="No account"- selected={choice === "local"}- onSelect={() => setChoice("local")}- />- ) : null}+ <h1 className="text-2xl font-semibold tracking-tight text-foreground">+ Connect your computers+ </h1>+ <p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">+ Choose one or more computers. We’ll set up agents and projects on each.+ </p>+ {directEnvironments.length > 0 ? (+ <fieldset className="mt-5 space-y-2">+ <legend className="sr-only">Computers to set up</legend>+ {directEnvironments.map((environment) => (+ <label+ key={environment.environmentId}+ className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-3"+ >+ <Checkbox+ checked={selectedIds.has(environment.environmentId)}+ onCheckedChange={(checked) => {+ const next = new Set(selectedIds);+ if (checked) next.add(environment.environmentId);+ else next.delete(environment.environmentId);+ onSelectionChange(next);+ }}+ />+ <MonitorIcon className="size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1">+ <span className="flex items-baseline justify-between gap-3">+ <span className="min-w-0 text-sm font-medium break-words">+ {environment.label}+ </span>+ <span className="shrink-0 text-xs text-muted-foreground">+ {environment.connection.phase === "connected" ? "Connected" : "Connecting…"}+ </span>+ </span>+ {environment.displayUrl ? (+ <span className="mt-0.5 block text-xs break-all text-muted-foreground">+ {environment.displayUrl}+ </span>+ ) : null}+ </span>+ </label>+ ))}+ </fieldset>+ ) : null}+ <div className="mt-4 space-y-2">{cloudEnabled ? (- <ConnectionOption- icon={CloudIcon}- title="T3 Connect"- description="Your computers, wherever you are"- detail="Sign in"- selected={choice === "connect"}- onSelect={() => setChoice("connect")}+ <ConnectAccountOption+ autoSelectedComputers={autoSelectedComputers}+ disabled={isPairing}+ selectedIds={selectedIds}+ onToggleEnvironment={onToggleEnvironment}/>) : null}- <ConnectionOption- icon={LinkIcon}- title="Pair a server"- description="Local network or Tailscale"- detail="Pairing link"- selected={choice === "direct"}- onSelect={() => setChoice("direct")}- />+ <Collapsible+ open={pairingOpen}+ onOpenChange={setPairingOpen}+ className="rounded-lg border border-border bg-background"+ >+ <CollapsibleTrigger+ disabled={isPairing}+ render={+ <Button+ variant="ghost"+ className="h-auto min-h-14 w-full justify-start gap-3 px-3 py-3 text-left whitespace-normal sm:h-auto"+ />+ }+ >+ <LinkIcon className="size-4 text-muted-foreground" />+ <span className="flex-1">Add a computer</span>+ <ChevronRightIcon+ className={cn("size-4 text-muted-foreground", pairingOpen && "rotate-90")}+ />+ </CollapsibleTrigger>+ <CollapsiblePanel>+ <div className="px-3 pb-3">+ <PairingForm+ isPairing={isPairing}+ setIsPairing={setIsPairing}+ onPaired={(environmentId) => {+ setPairingOpen(false);+ onPaired(environmentId);+ requestAnimationFrame(() => continueRef.current?.focus());+ }}+ />+ </div>+ </CollapsiblePanel>+ </Collapsible></div>- <div className="mt-7 flex justify-end">- <Button className="gap-2" onClick={advance}>+ <div className="mt-6 flex items-center justify-end gap-3">+ <Button+ ref={continueRef}+ autoFocus={!expandPairingInitially}+ disabled={!ready || isPairing}+ onClick={onContinue}+ >Continue<ArrowRightIcon className="size-3.5" /></Button>@@ -358,203 +395,108 @@ function ConnectionStep({);}-function ConnectionOption({- icon: Icon,- title,- description,- truncateDescription = false,- detail,- selected,- onSelect,+function ConnectAccountOption({+ autoSelectedComputers,+ disabled,+ selectedIds,+ onToggleEnvironment,}: {- readonly icon: LucideIcon;- readonly title: string;- readonly description: string;- readonly truncateDescription?: boolean;- readonly detail: string;- readonly selected: boolean;- readonly onSelect: () => void;+ readonly autoSelectedComputers: Set<EnvironmentId>;+ readonly disabled: boolean;+ readonly selectedIds: ReadonlySet<EnvironmentId>;+ readonly onToggleEnvironment: (environmentId: EnvironmentId, checked: boolean) => void;}) {- return (- <button- type="button"- aria-pressed={selected}- onClick={onSelect}- className={cn(- "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",- "outline-none focus-visible:bg-accent focus-visible:ring-1 focus-visible:ring-ring",- selected- ? "text-foreground"- : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",- )}- >- <Icon- className={cn("size-[18px]", selected ? "text-success-foreground" : "text-icon-muted")}- />- <span className="min-w-0 flex-1">- <span className="block text-sm font-medium">{title}</span>- <span- className={cn(- "mt-1 block text-xs text-muted-foreground",- truncateDescription ? "truncate" : "break-words whitespace-normal",- )}- >- {description}- </span>- </span>- <span className="hidden text-xs text-muted-foreground sm:block">{detail}</span>- {selected ? (- <CheckIcon className="size-4 text-success-foreground" />- ) : (- <span className="size-4" />- )}- </button>- );-}--// ── Step 2: T3 Connect (sign in, then connect machines) ──────--const CONNECT_LOGIN_COMMAND = "npx t3 connect";--/**- * Sign-in and machine-connection combined: signed out shows the Clerk prompt,- * signed in forks on account state — zero connected machines blocks on the- * `npx t3 connect` command and auto-advance is left to the user pressing- * Continue once their machine appears; existing machines show a confirmation- * list with the command folded away. There is deliberately no "primary- * machine" selection.- */-function ConnectMachinesStep({- onBack,- onContinue,-}: {- readonly onBack: () => void;- readonly onContinue: () => void;-}) {- // Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read- // as signed-out mid-transition.+ const { environments } = useEnvironments();const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });const { openAuthPrompt } = useT3ConnectAuthPrompt();- const { environments } = useEnvironments();- const primaryEnvironment = usePrimaryEnvironment();- const savedEnvironments = environments.filter(isOnboardingRelayEnvironment);- // Only a live connection counts: a saved-but-offline machine must not show- // the "connected" confirmation (the agents step would find nothing to- // probe). Its row still renders in the list either way.- const hasRemoteMachines = savedEnvironments.some(- (environment) => environment.connection.phase === "connected",- );-- if (!isLoaded) {- return <StepShell title="Sign in to T3 Connect" onBack={onBack} />;- }-- if (!isSignedIn) {- return (- <StepShell- title="Sign in to T3 Connect"- description="Connect your computers with one account."- onBack={onBack}- >- <div className="mt-6">- <Button onClick={openAuthPrompt}>Sign in</Button>- </div>- </StepShell>- );- }+ const [expanded, setExpanded] = useState(true);+ const [discoveryReady, setDiscoveryReady] = useState(false);+ const onDiscoveryReady = useCallback(() => setDiscoveryReady(true), []);return (- <StepShell- title={hasRemoteMachines ? "Your computers" : "Connect your computer"}- description={- hasRemoteMachines- ? "Connected to your T3 account."- : "Run this command on the computer with your code."- }- onBack={onBack}+ <Collapsible+ open={expanded && !!isSignedIn && discoveryReady}+ onOpenChange={setExpanded}+ className="rounded-lg border border-border bg-background">- {hasRemoteMachines ? (- <>- <div className="mt-6 overflow-hidden border-y border-border">- <CloudEnvironmentConnectRows- primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}- savedEnvironments={savedEnvironments}- showSavedEnvironments- empty={null}- />- </div>- <Collapsible className="mt-4">- <CollapsibleTrigger className="group flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground">- <ChevronRightIcon className="size-3.5 transition-transform duration-200 group-data-panel-open:rotate-90" />- Add another machine- </CollapsibleTrigger>- <CollapsiblePanel>- <CommandBlock command={CONNECT_LOGIN_COMMAND} className="mt-2" />- <p className="mt-2 text-xs text-muted-foreground">- Keep T3 Code running on that computer. If it is not running, open T3 Code or run{" "}- <code className="font-mono">npx t3 serve</code>.- </p>- </CollapsiblePanel>- </Collapsible>- <div className="mt-7 flex justify-end">- <Button onClick={onContinue}>Continue</Button>+ <CollapsibleTrigger+ disabled={disabled || !isLoaded}+ onClick={(event) => {+ if (!isSignedIn) {+ event.preventDefault();+ setExpanded(true);+ openAuthPrompt();+ }+ }}+ render={+ <Button+ variant="ghost"+ className="h-auto min-h-14 w-full justify-start gap-3 px-3 py-3 text-left whitespace-normal sm:h-auto"+ />+ }+ >+ <CloudIcon className="size-4 text-muted-foreground" />+ <span className="flex-1">T3 Connect</span>+ <span className="text-xs text-muted-foreground">+ {!isLoaded+ ? "Loading sign-in…"+ : !isSignedIn+ ? "Sign in"+ : !discoveryReady+ ? "Loading computers…"+ : null}+ </span>+ <ChevronRightIcon+ className={cn("size-4 text-muted-foreground", expanded && isSignedIn && "rotate-90")}+ />+ </CollapsibleTrigger>+ <CollapsiblePanel keepMounted>+ <div className="px-3 pb-3">+ <div className="mb-3 space-y-1.5">+ {isSignedIn ? (+ <CloudEnvironmentConnectRows+ primaryEnvironmentId={null}+ savedEnvironments={environments}+ showSavedEnvironments+ onDiscoveryReady={onDiscoveryReady}+ selection={{ selectedIds, onChange: onToggleEnvironment, autoSelectedComputers }}+ refreshWhileEmpty+ empty={+ <p className="py-3 text-sm text-muted-foreground">No computers linked yet.</p>+ }+ />+ ) : null}</div>- </>- ) : (- <>- <CommandBlock command={CONNECT_LOGIN_COMMAND} className="mt-7" prominent />- <p className="mt-2 text-xs text-muted-foreground">- Keep T3 Code running on that computer. If it is not running, open T3 Code or run{" "}- <code className="font-mono">npx t3 serve</code>.+ <p className="text-sm text-muted-foreground">+ Run this on each computer you want to connect.</p>- <div className="mt-5 overflow-hidden border-y border-border">- <CloudEnvironmentConnectRows- primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}- savedEnvironments={savedEnvironments}- showSavedEnvironments- refreshWhileEmpty- empty={- <p className="px-1 py-4 text-xs text-muted-foreground">- Waiting for your computer to connect.- </p>- }- />- </div>- <div className="mt-7 flex flex-wrap items-center justify-between gap-3">- <Button variant="ghost-muted" onClick={onContinue}>- Skip for now- </Button>- <div className="flex flex-wrap items-center justify-end gap-3">- <span className="hidden text-xs text-muted-foreground sm:block">- Waiting for connection- </span>- <Button disabled>Continue</Button>- </div>- </div>- </>- )}- </StepShell>+ <CommandBlock command="npx t3 connect" className="mt-3" />+ <p className="mt-3 text-xs text-muted-foreground">+ Keep T3 Code running. Select the computers you want to set up above.+ </p>+ </div>+ </CollapsiblePanel>+ </Collapsible>);}// ── Step 2′: Direct pairing ──────────────────────────────────/**- * Server-minted pairing, D-B treatment: numbered steps, `t3 pair` on the- * server, paste the URL here. Registers the remote environment in this- * browser's catalog (same path the hosted /pair surface uses).+ * Register a computer in this browser using a server-minted pairing link.*/-function PairDirectStep({- onBack,+function PairingForm({+ isPairing,+ setIsPairing,onPaired,}: {- readonly onBack: () => void;+ readonly isPairing: boolean;+ readonly setIsPairing: (value: boolean) => void;readonly onPaired: (environmentId: EnvironmentId) => void;}) {const connectPairingEnvironment = useAtomCommand(connectPairing, { reportFailure: false });const [pairingUrl, setPairingUrl] = useState("");const [errorMessage, setErrorMessage] = useState("");- const [isPairing, setIsPairing] = useState(false);const mountedRef = useRef(true);useEffect(() => {@@ -565,9 +507,10 @@ function PairDirectStep({}, []);const submit = async () => {+ if (isPairing || pairingUrl.trim().length === 0) return;setIsPairing(true);setErrorMessage("");- const result = await connectPairingEnvironment({ pairingUrl });+ const result = await connectPairingEnvironment({ pairingUrl: pairingUrl.trim() });if (!mountedRef.current) return;setIsPairing(false);if (result._tag === "Success") {@@ -580,28 +523,23 @@ function PairDirectStep({};return (- <StepShell- title="Pair a server"- description="Connect with a one-time pairing link."- onBack={onBack}- >- <div className="mt-7 space-y-5">- <div>- <p className="text-sm text-muted-foreground">- <span className="font-mono text-muted-foreground/70">01</span> Run this on your server- </p>- <CommandBlock command="npx t3 pair" className="mt-2" />- <p className="mt-2 text-xs text-muted-foreground">- Start the server with <code className="font-mono">npx t3 serve</code> first. Add{" "}- <code className="font-mono">--tailscale</code> to use your tailnet.- </p>- </div>+ <>+ <form+ className="space-y-3"+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ ><div><label className="block text-sm text-muted-foreground" htmlFor="onboarding-pairing-url">- <span className="font-mono text-muted-foreground/70">02</span> Paste the pairing link+ Pairing link</label><Inputid="onboarding-pairing-url"+ autoFocus+ aria-invalid={errorMessage.length > 0}+ aria-describedby={errorMessage ? "onboarding-pairing-error" : undefined}className="mt-2"size="lg"autoCapitalize="none"@@ -609,31 +547,55 @@ function PairDirectStep({autoCorrect="off"spellCheck={false}nativeInput- disabled={isPairing}+ readOnly={isPairing}placeholder="https://your-server:5230/pair#token=…"value={pairingUrl}onChange={(event) => setPairingUrl(event.currentTarget.value)}onKeyDown={(event) => {- if (event.nativeEvent.isComposing || event.keyCode === 229) return;- if (event.key === "Enter" && pairingUrl.trim().length > 0) void submit();+ if (+ event.key === "Enter" &&+ (event.nativeEvent.isComposing || event.keyCode === 229)+ ) {+ event.preventDefault();+ }}}/></div>{errorMessage ? (- <div className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">+ <div+ id="onboarding-pairing-error"+ role="alert"+ className="rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive"+ >{errorMessage}</div>) : null}- </div>- <div className="mt-7 flex justify-end">- <Button- disabled={isPairing || pairingUrl.trim().length === 0}- onClick={() => void submit()}- >- {isPairing ? "Pairing..." : "Connect"}- </Button>- </div>- </StepShell>+ <Collapsible>+ <div className="flex items-center justify-between gap-3">+ <CollapsibleTrigger+ type="button"+ className="group flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"+ >+ <ChevronRightIcon className="size-3.5 group-data-panel-open:rotate-90" />+ Need a pairing link?+ </CollapsibleTrigger>+ <Button type="submit" disabled={isPairing || pairingUrl.trim().length === 0}>+ {isPairing ? "Pairing..." : "Pair"}+ </Button>+ </div>+ <CollapsiblePanel className="pt-3">+ <p className="text-sm text-muted-foreground">+ Run this on the computer with your code.+ </p>+ <CommandBlock command="npx t3 pair" className="mt-2" />+ <p className="mt-2 text-xs leading-relaxed text-muted-foreground">+ Start T3 Code first, or run <code className="font-mono">npx t3 serve</code>. Add{" "}+ <code className="font-mono">--tailscale</code> to use your tailnet.+ </p>+ </CollapsiblePanel>+ </Collapsible>+ </form>+ </>);}@@ -660,58 +622,48 @@ interface AgentTerminalSession {* login that follows.*/function AgentsStep({- mode,- pairedEnvironmentId,- onBack,+ environmentIds,onContinue,- onSkip,}: {- readonly mode: ConnectionMode;- readonly pairedEnvironmentId: EnvironmentId | null;- readonly onBack: () => void;+ readonly environmentIds: readonly EnvironmentId[];readonly onContinue: () => void;- readonly onSkip: () => void;}) {- const targetEnvironment = useOnboardingTargetEnvironment(mode, pairedEnvironmentId);- if (targetEnvironment === null) {- return (- <StepShell- title="Your agents"- description="Waiting for this computer to connect."- onBack={onBack}+ const { environments } = useEnvironments();+ return (+ <StepShell title="Your agents" description="Agents available on your selected computers.">+ <ScrollArea+ scrollFade+ className="mt-5 h-auto max-h-96 [&_[data-slot=scroll-area-scrollbar]]:opacity-100">- <div className="mt-6 flex justify-end">- <Button variant="ghost-muted" onClick={onSkip}>- Skip for now- </Button>+ <div className="space-y-5 pr-3">+ {environmentIds.map((environmentId) => (+ <ConnectedAgentsStep+ key={environmentId}+ environmentId={environmentId}+ machineLabel={+ environments.find((environment) => environment.environmentId === environmentId)+ ?.label ?? "Computer"+ }+ />+ ))}</div>- </StepShell>- );- }- return (- <ConnectedAgentsStep- key={targetEnvironment.environmentId}- environmentId={targetEnvironment.environmentId}- machineLabel={targetEnvironment.label}- onBack={onBack}- onContinue={onContinue}- onSkip={onSkip}- />+ </ScrollArea>+ <div className="mt-6 flex justify-end">+ <Button autoFocus onClick={onContinue}>+ Continue+ <ArrowRightIcon className="size-3.5" />+ </Button>+ </div>+ </StepShell>);}function ConnectedAgentsStep({environmentId,machineLabel,- onBack,- onContinue,- onSkip,}: {readonly environmentId: EnvironmentId;readonly machineLabel: string;- readonly onBack: () => void;- readonly onContinue: () => void;- readonly onSkip: () => void;}) {const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {@@ -732,12 +684,10 @@ function ConnectedAgentsStep({driver,provider: byDriver.get(driver),}));- const readyCount = primaryAgents.filter(- ({ provider }) => getOnboardingProviderState(provider) === "ready",- ).length;return (- <StepShell title="Your agents" description={`Detected on ${machineLabel}.`} onBack={onBack}>- <div className="mt-7 border-t border-border">+ <section>+ <h2 className="mb-2 text-sm font-medium">{machineLabel}</h2>+ <div className="space-y-1.5">{primaryAgents.map(({ driver, provider }) => (<AgentCardkey={driver}@@ -778,21 +728,7 @@ function ConnectedAgentsStep({}}/>) : null}- <div className="mt-7 flex flex-wrap items-center justify-between gap-3">- <Button variant="ghost-muted" onClick={onSkip}>- Skip- </Button>- <div className="flex flex-wrap items-center justify-end gap-3">- <span className="text-xs text-muted-foreground">- {readyCount} of {primaryAgents.length} ready- </span>- <Button className="gap-2" onClick={onContinue}>- Continue- <ArrowRightIcon className="size-3.5" />- </Button>- </div>- </div>- </StepShell>+ </section>);}@@ -816,13 +752,13 @@ function AgentCard({const providerState = getOnboardingProviderState(provider);return (- <div className="flex min-h-20 items-center gap-4 border-b border-border py-3">+ <div className="flex items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5">{Icon ? (- <Icon className={cn("size-6 shrink-0", driver !== "claudeAgent" && "fill-foreground")} />+ <Icon className={cn("size-5 shrink-0", driver !== "claudeAgent" && "fill-foreground")} />) : null}<div className="min-w-0 flex-1"><span className="block text-sm font-medium text-foreground">{displayName}</span>- <p className="mt-1 truncate text-xs text-muted-foreground">+ <p className="mt-0.5 text-xs leading-relaxed break-words whitespace-pre-wrap text-muted-foreground">{summary.headline}{summary.detail ? ` · ${summary.detail}` : ""}</p>@@ -1008,35 +944,22 @@ function AgentInstallTerminal({// ── Step 4: import ───────────────────────────────────────────-/**- * One-decision import (4B): a summary line with Import recent / Choose /- * Skip. The default imports only projects touched in the last 30 days;- * Choose expands a checklist including older ones. Imported projects also- * receive Codex and Claude threads active within the last 30 days.- */function ImportStep({- mode,- pairedEnvironmentId,- onBack,+ scans,+ isImporting,+ setIsImporting,onDone,}: {- readonly mode: ConnectionMode;- readonly pairedEnvironmentId: EnvironmentId | null;- readonly onBack: () => void;+ readonly scans: ReturnType<typeof useProjectScans>;+ readonly isImporting: boolean;+ readonly setIsImporting: (value: boolean) => void;readonly onDone: (projectRef?: ScopedProjectRef) => Promise<boolean>;}) {- const targetEnvironment = useOnboardingTargetEnvironment(mode, pairedEnvironmentId);- const environmentId = targetEnvironment?.environmentId ?? null;- const machineLabel = targetEnvironment?.label ?? "this machine";- const scan = useEnvironmentQuery(- environmentId === null ? null : agentSessionScan({ environmentId, input: {} }),- );+ const { environments } = useEnvironments();const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });const importThreads = useAtomCommand(agentSessionImport, { reportFailure: false });const projects = useProjects();- const [choosing, setChoosing] = useState(false);- const [deselected, setDeselected] = useState<ReadonlySet<string>>(new Set());- const [isImporting, setIsImporting] = useState(false);+ const [selectedPaths, setSelectedPaths] = useState<ReadonlySet<string> | null>(null);const [importError, setImportError] = useState("");const [landingProject, setLandingProject] = useState<ScopedProjectRef | null>(null);// Keep project creation attempts separate from completed history imports so both can retry.@@ -1048,27 +971,17 @@ function ImportStep({);const importGenerationRef = useRef(0);- // Candidate paths are per-environment; a target switch would otherwise- // leave stale entries in the deselection set (and stale success records).+ // Ignore command completions after leaving the import step.useEffect(() => {importGenerationRef.current += 1;- setDeselected(new Set());- setIsImporting(false);- setImportError("");- setLandingProject(null);- importedProjectsRef.current = new Map();- projectsWithImportedHistoryRef.current = new Map();- lastImportSelectionRef.current = [];- projectAttemptsRef.current = new Map();return () => {importGenerationRef.current += 1;};- }, [environmentId]);+ }, []);useEffect(() => {if (landingProject !== null &&- landingProject.environmentId === environmentId &&projects.some((project) =>project.id === landingProject.projectId &&@@ -1080,19 +993,26 @@ function ImportStep({if (!completed) setIsImporting(false);});}- }, [environmentId, landingProject, onDone, projects]);+ }, [landingProject, onDone, projects, setIsImporting]);const { available: candidates, recent } = useMemo(- () => partitionOnboardingProjects(scan.data?.candidates ?? []),- [scan.data],+ () =>+ partitionOnboardingProjects(+ scans.flatMap((scan) =>+ (scan.data?.candidates ?? []).map((candidate) => ({+ ...candidate,+ environmentId: scan.environmentId,+ key: onboardingProjectKey(scan.environmentId, candidate.path),+ })),+ ),+ ),+ [scans],+ );+ const selected = candidates.filter((candidate) =>+ selectedPaths+ ? selectedPaths.has(candidate.key)+ : recent.some((item) => item.key === candidate.key),);- const more = candidates.length - recent.length;- const scanTruncated = scan.data?.truncated === true;- const scanLimitNotice = scanTruncated ? (- <p className="mt-3 text-sm text-muted-foreground" role="status">- {SCAN_LIMIT_MESSAGE}- </p>- ) : null;const finishAfterImport = () => {const projectRef = resolveOnboardingLandingProject(@@ -1108,14 +1028,15 @@ function ImportStep({setLandingProject(projectRef);};- const runImport = async (selection: ReadonlyArray<AgentSessionProjectCandidate>) => {- if (environmentId === null || selection.length === 0) {+ const runImport = async (selection: typeof candidates) => {+ if (isImporting) return;+ if (selection.length === 0) {void onDone();return;}setIsImporting(true);setImportError("");- lastImportSelectionRef.current = selection.map((candidate) => candidate.path);+ lastImportSelectionRef.current = selection.map((candidate) => candidate.key);const importGeneration = importGenerationRef.current;const importedProjects = importedProjectsRef.current;const projectAttempts = projectAttemptsRef.current;@@ -1126,29 +1047,30 @@ function ImportStep({// duplicate-root invariant and read as a failure).let importedProjectsCount =importedProjects.size > 0- ? selection.filter((candidate) => importedProjects.has(candidate.path)).length+ ? selection.filter((candidate) => importedProjects.has(candidate.key)).length: 0;let importedThreadCount = 0;let skippedThreadCount = 0;- let shouldRefreshScan = false;+ const refreshEnvironments = new Set<EnvironmentId>();for (const candidate of selection) {+ const { environmentId } = candidate;if (importGeneration !== importGenerationRef.current ||importedProjects !== importedProjectsRef.current) {return;}- if (importedProjects.has(candidate.path)) continue;+ if (importedProjects.has(candidate.key)) continue;let projectId = resolveOnboardingProjectId(readProjects(), environmentId, candidate);if (projectId === null) {- let attempt = projectAttempts.get(candidate.path);+ let attempt = projectAttempts.get(candidate.key);if (attempt === undefined) {const nextProjectId = newProjectId();attempt = {projectId: nextProjectId,commandId: CommandId.make(`onboarding:project:create:${nextProjectId}`),};- projectAttempts.set(candidate.path, attempt);+ projectAttempts.set(candidate.key, attempt);}projectId = attempt.projectId;const result = await createProject({@@ -1170,8 +1092,8 @@ function ImportStep({}if (result._tag !== "Success") {if (!isAtomCommandInterrupted(result)) {- projectAttempts.delete(candidate.path);- shouldRefreshScan = true;+ projectAttempts.delete(candidate.key);+ refreshEnvironments.add(environmentId);}continue;}@@ -1192,20 +1114,22 @@ function ImportStep({skippedThreadCount += threadImportResult.value.skippedCount;if (threadImportResult.value.importedCount > 0) {projectsWithImportedHistoryRef.current.set(- candidate.path,+ candidate.key,scopeProjectRef(environmentId, projectId),);}if (threadImportResult.value.skippedCount === 0) {importedProjectsCount += 1;- importedProjects.set(candidate.path, scopeProjectRef(environmentId, projectId));+ importedProjects.set(candidate.key, scopeProjectRef(environmentId, projectId));}} else if (!isAtomCommandInterrupted(threadImportResult)) {- projectAttempts.delete(candidate.path);- shouldRefreshScan = true;+ projectAttempts.delete(candidate.key);+ refreshEnvironments.add(environmentId);}}- if (shouldRefreshScan) scan.refresh();+ for (const scan of scans) {+ if (refreshEnvironments.has(scan.environmentId)) scan.refresh();+ }setIsImporting(false);if (importedProjectsCount < selection.length) {if (importedThreadCount > 0 && skippedThreadCount > 0) {@@ -1228,166 +1152,129 @@ function ImportStep({finishAfterImport();};- if (environmentId === null || (scan.isPending && scan.data === null)) {- return (- <StepShell- title="Your projects"- description="Looking for projects from Claude Code and Codex."- onBack={onBack}- >- <div className="mt-6 flex justify-end">- <Button variant="ghost-muted" onClick={() => void onDone()}>- Skip- </Button>- </div>- </StepShell>- );- }-- if (scan.error !== null || candidates.length === 0) {- return (- <StepShell- title="Your projects"- description={- scan.error !== null- ? "Could not check this computer for projects."- : scanTruncated- ? SCAN_LIMIT_MESSAGE- : "No existing Claude Code or Codex projects found."- }- onBack={onBack}- >- {scan.error !== null ? (- <p className="mt-3 text-xs text-muted-foreground">You can add projects later.</p>- ) : null}- <div className="mt-6 flex justify-end gap-2">- {scan.error !== null ? (- <Button variant="ghost" onClick={scan.refresh}>- Retry- </Button>- ) : null}- <Button- variant={scan.error !== null || scanTruncated ? "ghost-muted" : "default"}- onClick={() => void onDone()}- >- {scan.error !== null || scanTruncated ? "Skip" : "Start coding"}- </Button>- </div>- </StepShell>- );- }-- if (choosing) {- const selected = candidates.filter((candidate) => !deselected.has(candidate.path));+ if (scans.every((scan) => scan.data === null) && scans.some((scan) => scan.isPending)) {return (- <StepShell- title="Choose your projects"- onBack={() => setChoosing(false)}- backDisabled={isImporting}- description={`${candidates.length} found on ${machineLabel}.`}- >- {scanLimitNotice}- <div className="mt-6 max-h-72 overflow-x-hidden overflow-y-auto border-y border-border">- {candidates.map((candidate) => (- <label- key={candidate.path}- 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"- >- <Checkbox- checked={!deselected.has(candidate.path)}- onCheckedChange={(checked) => {- setDeselected((previous) => {- const next = new Set(previous);- if (checked === true) next.delete(candidate.path);- else next.add(candidate.path);- return next;- });- }}- />- <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">- {candidate.path}- </span>- <span className="hidden shrink-0 whitespace-nowrap text-[11px] text-muted-foreground sm:block">- {candidate.sources.map(formatSource).join(", ")} · {candidate.threadCount}{" "}- {candidate.threadCount === 1 ? "thread" : "threads"}- {candidate.lastActiveAt- ? ` · ${formatRelativeTimeLabel(candidate.lastActiveAt)}`- : ""}- </span>- </label>- ))}+ <div className="flex h-full min-h-40 flex-col">+ <h1 className="text-2xl font-semibold tracking-tight text-foreground">Your projects</h1>+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-6">+ <Spinner className="size-5 text-muted-foreground" />+ <p className="text-center text-sm text-muted-foreground">+ Looking for projects from Claude Code and Codex…+ </p></div>- {importError ? <p className="mt-3 text-sm text-destructive">{importError}</p> : null}- <div className="mt-7 flex flex-wrap items-center justify-between gap-3">- <Button- variant="ghost-muted"- disabled={isImporting}- onClick={importError ? finishAfterImport : () => void onDone()}- >- {importError ? "Continue without the rest" : "Skip"}- </Button>- <Button- disabled={isImporting || selected.length === 0}- onClick={() => void runImport(selected)}- >- {isImporting ? "Importing..." : `Import ${selected.length}`}+ <div className="flex justify-end">+ <Button variant="ghost-muted" onClick={() => void onDone()}>+ Do not import projects</Button></div>- </StepShell>+ </div>);}return (<StepShell- title="Your recent projects"- description={`${recent.length} ${recent.length === 1 ? "project" : "projects"} found on ${machineLabel}.${more > 0 ? ` ${more} more available.` : ""}`}- onBack={onBack}- backDisabled={isImporting}+ title="Choose your projects"+ description="Import projects and conversations from your selected computers.">- {scanLimitNotice}- <div className="mt-6 border-y border-border">- {recent.slice(0, 4).map((candidate) => (- <div- key={candidate.path}- className="flex min-h-12 items-center gap-3 border-b border-border/60 px-1 py-2 last:border-b-0"- >- <CheckIcon className="size-3.5 shrink-0 text-success-foreground" />- <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">- {candidate.path}- </span>- <span className="hidden shrink-0 whitespace-nowrap text-[11px] text-muted-foreground sm:block">- {candidate.sources.map(formatSource).join(", ")}- </span>- </div>- ))}- {recent.length > 4 ? (- <p className="px-1 py-3 text-xs text-muted-foreground">- {recent.length - 4} more projects- </p>- ) : null}- </div>+ <ScrollArea+ scrollFade+ className="mt-5 h-auto max-h-80 [&_[data-slot=scroll-area-scrollbar]]:opacity-100"+ >+ <div className="space-y-5 pr-3">+ {scans.map((scan) => {+ const groupCandidates = candidates.filter(+ (candidate) => candidate.environmentId === scan.environmentId,+ );+ const label =+ environments.find((environment) => environment.environmentId === scan.environmentId)+ ?.label ?? "Computer";+ return (+ <fieldset+ key={scan.environmentId}+ className="min-w-0 space-y-1.5"+ disabled={isImporting}+ >+ <legend className="mb-2 text-sm font-medium">{label}</legend>+ {scan.isPending && scan.data === null ? (+ <div className="flex items-center gap-2 py-3 text-sm text-muted-foreground">+ <Spinner className="size-4" />+ Looking for projects…+ </div>+ ) : scan.error !== null ? (+ <div+ role="alert"+ className="flex items-center justify-between gap-3 text-sm text-muted-foreground"+ >+ <span>Could not check projects. {scan.error}</span>+ <Button variant="ghost" size="sm" onClick={scan.refresh}>+ Retry+ </Button>+ </div>+ ) : groupCandidates.length === 0 ? (+ <p className="py-2 text-sm text-muted-foreground">+ No existing Claude Code or Codex projects found.+ </p>+ ) : null}+ {scan.data?.truncated ? (+ <p className="text-xs text-muted-foreground" role="status">+ {SCAN_LIMIT_MESSAGE}+ </p>+ ) : null}+ {groupCandidates.map((candidate) => (+ <label+ key={candidate.key}+ 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"+ >+ <Checkbox+ checked={selected.some((item) => item.key === candidate.key)}+ onCheckedChange={(checked) => {+ const next = new Set(selected.map((item) => item.key));+ if (checked) next.add(candidate.key);+ else next.delete(candidate.key);+ setSelectedPaths(next);+ }}+ />+ <Tooltip>+ <TooltipTrigger+ render={<span className="min-w-0 flex-1 truncate font-mono text-xs" />}+ >+ {candidate.path}+ </TooltipTrigger>+ <TooltipPopup className="max-w-96 break-all font-mono">+ {candidate.path}+ </TooltipPopup>+ </Tooltip>+ <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground">+ {candidate.sources+ .map((source) => (source === "claudeAgent" ? "Claude" : "Codex"))+ .join(", ")}{" "}+ · {candidate.threadCount} {candidate.threadCount === 1 ? "thread" : "threads"}+ </span>+ </label>+ ))}+ </fieldset>+ );+ })}+ </div>+ </ScrollArea>{importError ? <p className="mt-3 text-sm text-destructive">{importError}</p> : null}- <div className="mt-7 flex flex-wrap items-center justify-between gap-3">+ <div className="mt-6 flex flex-wrap items-center justify-end gap-3"><Buttonvariant="ghost-muted"disabled={isImporting}onClick={importError ? finishAfterImport : () => void onDone()}>- {importError ? "Continue without the rest" : "Skip"}+ {importError ? "Continue without the rest" : "Do not import projects"}+ </Button>+ <Button+ autoFocus+ disabled={isImporting || selected.length === 0}+ onClick={() => void runImport(selected)}+ >+ {isImporting+ ? "Importing…"+ : `Import ${selected.length} ${selected.length === 1 ? "project" : "projects"}`}</Button>- <div className="flex items-center gap-2">- <Button variant="ghost" disabled={isImporting} onClick={() => setChoosing(true)}>- Choose- </Button>- <Button- disabled={isImporting || recent.length === 0}- onClick={() => void runImport(recent)}- >- {isImporting- ? "Importing..."- : `Import ${recent.length} ${recent.length === 1 ? "project" : "projects"}`}- </Button>- </div></div></StepShell>);@@ -1398,31 +1285,15 @@ function ImportStep({function StepShell({title,description,- onBack,- backDisabled = false,children,}: {readonly title: string;readonly description?: string;- readonly onBack?: () => void;- readonly backDisabled?: boolean;readonly children?: React.ReactNode;}) {return (<>- {onBack ? (- <Button- className="mb-5 -ml-2"- disabled={backDisabled}- onClick={onBack}- size="xs"- variant="ghost-muted"- >- <ChevronLeftIcon className="size-3.5" />- Back- </Button>- ) : null}- <h1 className="text-3xl font-semibold text-foreground sm:text-[34px]">{title}</h1>+ <h1 className="text-2xl font-semibold tracking-tight text-foreground">{title}</h1>{description ? (<p className="mt-2.5 text-sm leading-relaxed text-muted-foreground">{description}</p>) : null}@@ -1447,7 +1318,7 @@ function CommandBlock({return (<divclassName={cn(- "flex items-center justify-between gap-3 border border-border bg-accent/50 font-mono",+ "flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/50 font-mono",prominent ? "px-4 py-3.5 text-base" : "px-3 py-2.5 text-sm",className,)}@@ -1467,7 +1338,3 @@ function CommandBlock({</div>);}--function formatSource(source: "claudeAgent" | "codex"): string {- return source === "claudeAgent" ? "Claude" : "Codex";-}diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsxindex 9671755f8be..d29d5fd04fe 100644--- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx@@ -29,7 +29,7 @@ import { RadioGroup } from "../ui/radio-group";import { toastManager } from "../ui/toast";import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";-import { AnimatedHeight } from "../AnimatedHeight";+import { WizardPanel } from "../ui/wizard";import {ADD_PROVIDER_WIZARD_STEPS,resolveWizardNavigation,@@ -246,173 +246,168 @@ export function AddProviderInstanceDialog({/></DialogHeader>- <div- data-slot="dialog-panel"- className="space-y-4 bg-zinc-25/80 px-6 py-5 ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5"- >- <AnimatedHeight>- <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>- <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">- Driver- </div>- <RadioGroup- value={driver}- onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}- aria-labelledby="add-instance-driver-label"- className="grid grid-cols-1 gap-2 sm:grid-cols-2"- >- {DRIVER_OPTIONS.map((option) => {- const IconComponent = option.icon;- return (- <RadioPrimitive.Root- key={option.value}- value={option.value}- className="relative flex cursor-pointer items-center gap-3 rounded-lg bg-card px-3 py-3 text-left text-muted-foreground outline-none ring-1 ring-black/5 hover:bg-zinc-50 focus-visible:ring-2 focus-visible:ring-ring data-checked:bg-primary/8 data-checked:text-foreground data-checked:ring-2 data-checked:ring-primary data-checked:hover:bg-primary/8 dark:bg-white/3 dark:ring-white/5 dark:hover:bg-white/5 dark:data-checked:bg-primary/15 dark:data-checked:ring-primary dark:data-checked:hover:bg-primary/15"- >- <IconComponent className="size-4 shrink-0" aria-hidden />- <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">- {option.label}- </span>- <RadioPrimitive.Indicator- className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"- aria-hidden- >- <CheckIcon className="size-3.5 shrink-0" />- </RadioPrimitive.Indicator>- {option.badgeLabel ? (- <Badge variant="warning" size="sm">- {option.badgeLabel}- </Badge>- ) : null}- </RadioPrimitive.Root>- );- })}- {COMING_SOON_DRIVER_OPTIONS.map((option) => {- const IconComponent = option.icon;- return (- <RadioPrimitive.Root- key={option.value}- value={option.value}- disabled- className={cn(- "relative flex cursor-not-allowed items-center gap-3 rounded-lg bg-card/60 px-3 py-3 text-left opacity-55 outline-none ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5",- )}+ <WizardPanel>+ <div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>+ <div id="add-instance-driver-label" className="text-sm font-medium text-foreground">+ Driver+ </div>+ <RadioGroup+ value={driver}+ onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}+ aria-labelledby="add-instance-driver-label"+ className="grid grid-cols-1 gap-2 sm:grid-cols-2"+ >+ {DRIVER_OPTIONS.map((option) => {+ const IconComponent = option.icon;+ return (+ <RadioPrimitive.Root+ key={option.value}+ value={option.value}+ className="relative flex cursor-pointer items-center gap-3 rounded-lg bg-card px-3 py-3 text-left text-muted-foreground outline-none ring-1 ring-black/5 hover:bg-zinc-50 focus-visible:ring-2 focus-visible:ring-ring data-checked:bg-primary/8 data-checked:text-foreground data-checked:ring-2 data-checked:ring-primary data-checked:hover:bg-primary/8 dark:bg-white/3 dark:ring-white/5 dark:hover:bg-white/5 dark:data-checked:bg-primary/15 dark:data-checked:ring-primary dark:data-checked:hover:bg-primary/15"+ >+ <IconComponent className="size-4 shrink-0" aria-hidden />+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">+ {option.label}+ </span>+ <RadioPrimitive.Indicator+ className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"+ aria-hidden>- <IconComponent- className="size-4 shrink-0 text-muted-foreground"- aria-hidden- />- <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">- {option.label}- </span>+ <CheckIcon className="size-3.5 shrink-0" />+ </RadioPrimitive.Indicator>+ {option.badgeLabel ? (<Badge variant="warning" size="sm">- Coming Soon+ {option.badgeLabel}</Badge>- </RadioPrimitive.Root>- );- })}- </RadioGroup>- </div>+ ) : null}+ </RadioPrimitive.Root>+ );+ })}+ {COMING_SOON_DRIVER_OPTIONS.map((option) => {+ const IconComponent = option.icon;+ return (+ <RadioPrimitive.Root+ key={option.value}+ value={option.value}+ disabled+ className={cn(+ "relative flex cursor-not-allowed items-center gap-3 rounded-lg bg-card/60 px-3 py-3 text-left opacity-55 outline-none ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5",+ )}+ >+ <IconComponent+ className="size-4 shrink-0 text-muted-foreground"+ aria-hidden+ />+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">+ {option.label}+ </span>+ <Badge variant="warning" size="sm">+ Coming Soon+ </Badge>+ </RadioPrimitive.Root>+ );+ })}+ </RadioGroup>+ </div>- <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>- <span className="text-xs font-medium text-foreground">Label</span>- <Input- className="bg-background"- placeholder="e.g. Work"- value={label}- onChange={(event) => setLabel(event.target.value)}- />+ <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>+ <span className="text-xs font-medium text-foreground">Label</span>+ <Input+ className="bg-background"+ placeholder="e.g. Work"+ value={label}+ onChange={(event) => setLabel(event.target.value)}+ />+ <span className="text-[11px] text-muted-foreground">+ Shown in the provider list. Optional.+ </span>+ </label>++ <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>+ <span className="text-xs font-medium text-foreground">Instance ID</span>+ <Input+ className="bg-background"+ placeholder={`${driver}_work`}+ value={instanceId}+ onChange={(event) => {+ setInstanceIdOverride(event.target.value);+ }}+ aria-invalid={showInstanceIdError}+ />+ {showInstanceIdError ? (+ <span className="text-[11px] text-destructive">{instanceIdError}</span>+ ) : (<span className="text-[11px] text-muted-foreground">- Shown in the provider list. Optional.+ Routing key used by threads and sessions. Letters, digits, '-', or '_'.</span>- </label>+ )}+ </label>- <label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>- <span className="text-xs font-medium text-foreground">Instance ID</span>- <Input- className="bg-background"- placeholder={`${driver}_work`}- value={instanceId}- onChange={(event) => {- setInstanceIdOverride(event.target.value);- }}- aria-invalid={showInstanceIdError}+ <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>+ <span className="text-xs font-medium text-foreground">Accent color</span>+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <input+ type="color"+ value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}+ onChange={(event) => setAccentColor(event.target.value)}+ aria-label="Provider instance accent color"+ className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"/>- {showInstanceIdError ? (- <span className="text-[11px] text-destructive">{instanceIdError}</span>- ) : (- <span className="text-[11px] text-muted-foreground">- Routing key used by threads and sessions. Letters, digits, '-', or '_'.- </span>- )}- </label>-- <div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>- <span className="text-xs font-medium text-foreground">Accent color</span>- <div className="flex min-w-0 flex-wrap items-center gap-2">- <input- type="color"- value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}- onChange={(event) => setAccentColor(event.target.value)}- aria-label="Provider instance accent color"- className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"- />- <div className="flex flex-wrap gap-1.5">- {PROVIDER_ACCENT_SWATCHES.map((swatch) => {- const selected = accentColor.toLowerCase() === swatch;- return (- <button- key={swatch}- type="button"- className={cn(- "size-6 cursor-pointer rounded-full border transition",- selected- ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"- : "border-black/10 hover:scale-105 dark:border-white/20",- )}- style={{ backgroundColor: swatch }}- onClick={() => setAccentColor(swatch)}- aria-label={`Use ${swatch} accent`}- />- );- })}- </div>- {accentColor ? (- <Button- type="button"- size="xs"- variant="ghost"- className="text-muted-foreground"- onClick={() => setAccentColor("")}- >- Clear- </Button>- ) : null}+ <div className="flex flex-wrap gap-1.5">+ {PROVIDER_ACCENT_SWATCHES.map((swatch) => {+ const selected = accentColor.toLowerCase() === swatch;+ return (+ <button+ key={swatch}+ type="button"+ className={cn(+ "size-6 cursor-pointer rounded-full border transition",+ selected+ ? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"+ : "border-black/10 hover:scale-105 dark:border-white/20",+ )}+ style={{ backgroundColor: swatch }}+ onClick={() => setAccentColor(swatch)}+ aria-label={`Use ${swatch} accent`}+ />+ );+ })}</div>- <span className="text-[11px] text-muted-foreground">- Optional marker shown in the picker.- </span>+ {accentColor ? (+ <Button+ type="button"+ size="xs"+ variant="ghost"+ className="text-muted-foreground"+ onClick={() => setAccentColor("")}+ >+ Clear+ </Button>+ ) : null}</div>+ <span className="text-[11px] text-muted-foreground">+ Optional marker shown in the picker.+ </span>+ </div>- {driverSettingsFields.length > 0 ? (- <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>- <ProviderSettingsForm- definition={driverOption}- value={configDraft}- idPrefix={`add-provider-${driver}`}- variant="dialog"- onChange={setConfigDraft}- />- </div>- ) : wizardStep === 2 ? (- <div className="grid gap-2">- <p className="text-sm text-muted-foreground">- This driver has no required configuration. You can add the instance now.- </p>- </div>- ) : null}- </AnimatedHeight>- </div>+ {driverSettingsFields.length > 0 ? (+ <div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>+ <ProviderSettingsForm+ definition={driverOption}+ value={configDraft}+ idPrefix={`add-provider-${driver}`}+ variant="dialog"+ onChange={setConfigDraft}+ />+ </div>+ ) : wizardStep === 2 ? (+ <div className="grid gap-2">+ <p className="text-sm text-muted-foreground">+ This driver has no required configuration. You can add the instance now.+ </p>+ </div>+ ) : null}+ </WizardPanel><DialogFooter variant="bare"><Buttondiff --git a/apps/web/src/components/settings/AddProviderInstanceWizardSteps.test.tsx b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.test.tsxindex cec11163fec..fba6551d8c8 100644--- a/apps/web/src/components/settings/AddProviderInstanceWizardSteps.test.tsx+++ b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.test.tsx@@ -1,6 +1,7 @@import { Children, isValidElement, type ReactElement } from "react";import { describe, expect, it, vi } from "vite-plus/test";+import { WizardSteps } from "../ui/wizard";import { ADD_PROVIDER_WIZARD_STEPS } from "./AddProviderInstanceDialog.logic";import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps";@@ -25,7 +26,7 @@ function renderStepButtons(onNavigation,});- return Children.toArray(header.props.children)+ return Children.toArray(WizardSteps(header.props).props.children).filter((child): child is ReactElement<StepListItemProps> => isValidElement(child)).map((item) => item.props.children);}diff --git a/apps/web/src/components/settings/AddProviderInstanceWizardSteps.tsx b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.tsxindex f209474be6b..97df226aa79 100644--- a/apps/web/src/components/settings/AddProviderInstanceWizardSteps.tsx+++ b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.tsx@@ -1,6 +1,4 @@-import { CheckIcon } from "lucide-react";--import { cn } from "../../lib/utils";+import { WizardSteps } from "../ui/wizard";import {ADD_PROVIDER_WIZARD_STEPS,resolveWizardNavigation,@@ -21,53 +19,17 @@ export function AddProviderInstanceWizardSteps({onNavigation,}: AddProviderInstanceWizardStepsProps) {return (- <ol- className="grid grid-cols-3 gap-1 rounded-xl bg-zinc-25 p-1 ring-1 ring-black/5 dark:bg-white/4 dark:ring-white/5"- role="list"- >- {ADD_PROVIDER_WIZARD_STEPS.map((step, index) => (- <li key={step} className="min-w-0">- <button- type="button"- className={cn(- "flex w-full min-w-0 cursor-pointer items-center gap-2 rounded-lg px-2.5 py-2 text-left outline-none hover:bg-card focus-visible:ring-2 focus-visible:ring-ring max-sm:justify-center max-sm:px-2",- index === currentStep &&- "bg-card text-foreground shadow-xs ring-1 ring-black/5 hover:bg-card dark:shadow-none dark:ring-white/5",- )}- aria-current={index === currentStep ? "step" : undefined}- aria-label={`${step}, step ${index + 1}${index < currentStep && summaries[index] ? `, ${summaries[index]}` : ""}`}- onClick={() =>- onNavigation(- resolveWizardNavigation(currentStep, index, ADD_PROVIDER_WIZARD_STEPS.length, {- instanceIdError,- }),- )- }- >- <span- className={cn(- "grid size-5 shrink-0 place-items-center rounded-full text-sm font-medium ring-1",- index < currentStep- ? "bg-primary text-primary-foreground ring-primary"- : index === currentStep- ? "bg-primary/10 text-primary ring-primary/30"- : "bg-card text-muted-foreground ring-black/10 dark:bg-white/5 dark:ring-white/10",- )}- aria-hidden- >- {index < currentStep ? <CheckIcon className="size-4 shrink-0" /> : index + 1}- </span>- <span- className={cn(- "min-w-0 truncate text-sm font-medium max-sm:hidden",- index === currentStep ? "text-foreground" : "text-muted-foreground",- )}- >- {step}- </span>- </button>- </li>- ))}- </ol>+ <WizardSteps+ steps={ADD_PROVIDER_WIZARD_STEPS}+ currentStep={currentStep}+ summaries={summaries}+ onStepChange={(requestedStep) =>+ onNavigation(+ resolveWizardNavigation(currentStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, {+ instanceIdError,+ }),+ )+ }+ />);}diff --git a/apps/web/src/components/ui/wizard.tsx b/apps/web/src/components/ui/wizard.tsxnew file mode 100644index 00000000000..8843e265e03--- /dev/null+++ b/apps/web/src/components/ui/wizard.tsx@@ -0,0 +1,90 @@+import { CheckIcon } from "lucide-react";+import type { ComponentProps } from "react";++import { cn } from "../../lib/utils";+import { AnimatedHeight } from "../AnimatedHeight";++export function WizardSteps({+ steps,+ currentStep,+ summaries,+ onStepChange,+ isStepDisabled,+}: {+ readonly steps: readonly string[];+ readonly currentStep: number;+ readonly summaries?: readonly (string | null)[];+ readonly isStepDisabled?: (step: number) => boolean;+ readonly onStepChange?: (step: number) => void;+}) {+ const Step = onStepChange ? "button" : "div";+ return (+ <ol+ className="grid auto-cols-fr grid-flow-col gap-1 rounded-xl bg-zinc-25 p-1 ring-1 ring-black/5 dark:bg-white/4 dark:ring-white/5"+ role="list"+ aria-label="Setup progress"+ >+ {steps.map((step, index) => (+ <li key={step} className="min-w-0">+ <Step+ {...(onStepChange+ ? { type: "button" as const, disabled: isStepDisabled?.(index) }+ : {})}+ className={cn(+ "flex w-full min-w-0 items-center gap-2 rounded-lg px-2.5 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring max-sm:justify-center max-sm:px-2",+ onStepChange &&+ "cursor-pointer hover:bg-card disabled:cursor-default disabled:hover:bg-transparent",+ index === currentStep &&+ "bg-card text-foreground shadow-xs ring-1 ring-black/5 hover:bg-card dark:shadow-none dark:ring-white/5",+ )}+ aria-current={index === currentStep ? "step" : undefined}+ aria-label={`${step}, step ${index + 1}${index < currentStep && summaries?.[index] ? `, ${summaries?.[index]}` : ""}`}+ onClick={onStepChange ? () => onStepChange(index) : undefined}+ >+ <span+ className={cn(+ "grid size-5 shrink-0 place-items-center rounded-full text-sm font-medium ring-1",+ index < currentStep+ ? "bg-primary text-primary-foreground ring-primary"+ : index === currentStep+ ? "bg-primary/10 text-primary ring-primary/30"+ : "bg-card text-muted-foreground ring-black/10 dark:bg-white/5 dark:ring-white/10",+ )}+ aria-hidden+ >+ {index < currentStep ? <CheckIcon className="size-4 shrink-0" /> : index + 1}+ </span>+ <span+ className={cn(+ "min-w-0 truncate text-sm font-medium max-sm:hidden",+ index === currentStep ? "text-foreground" : "text-muted-foreground",+ )}+ >+ {step}+ </span>+ </Step>+ </li>+ ))}+ </ol>+ );+}++export function WizardPanel({+ className,+ children,+ holdHeight = false,+ ...props+}: ComponentProps<"div"> & { readonly holdHeight?: boolean }) {+ return (+ <div+ data-slot="dialog-panel"+ className={cn(+ "space-y-4 bg-zinc-25/80 px-6 py-5 ring-1 ring-black/5 dark:bg-white/2 dark:ring-white/5",+ className,+ )}+ {...props}+ >+ <AnimatedHeight holdHeight={holdHeight}>{children}</AnimatedHeight>+ </div>+ );+}diff --git a/apps/web/src/hooks/useTheme.test.ts b/apps/web/src/hooks/useTheme.test.tsindex 11cac880654..ab87388ff29 100644--- a/apps/web/src/hooks/useTheme.test.ts+++ b/apps/web/src/hooks/useTheme.test.ts@@ -204,204 +204,3 @@ describe("theme failure handling", () => {}});});--describe("onboarding theme", () => {- it("clears custom palettes and restores the latest selected theme", async () => {- const storage = createStorage();- const classes = new Set<string>();- const styleValues = new Map<string, string>();- const root = {- classList: {- add: (name: string) => classes.add(name),- contains: (name: string) => classes.has(name),- remove: (name: string) => classes.delete(name),- toggle: (name: string, force?: boolean) => {- const next = force ?? !classes.has(name);- if (next) classes.add(name);- else classes.delete(name);- return next;- },- },- dataset: {} as Record<string, string>,- offsetHeight: 0,- style: {- backgroundColor: "",- removeProperty: (name: string) => styleValues.delete(name),- setProperty: (name: string, value: string) => styleValues.set(name, value),- },- };- vi.doMock("react", () => ({- useCallback: <A>(callback: A) => callback,- useEffect: () => undefined,- useSyncExternalStore: (- subscribe: (listener: () => void) => () => void,- getSnapshot: () => unknown,- ) => {- subscribe(() => undefined);- return getSnapshot();- },- }));- vi.stubGlobal("window", {- addEventListener: () => undefined,- localStorage: storage,- matchMedia: () => ({- matches: false,- addEventListener: () => undefined,- removeEventListener: () => undefined,- }),- removeEventListener: () => undefined,- });- vi.stubGlobal("document", {- body: { style: { backgroundColor: "" } },- createElement: () => ({ name: "", setAttribute: () => undefined }),- documentElement: root,- head: { append: () => undefined },- querySelector: () => null,- querySelectorAll: () => [],- });- vi.stubGlobal("getComputedStyle", () => ({- backgroundColor: "rgb(0, 0, 0)",- getPropertyValue: () => "",- }));- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {- callback(0);- return 0;- });-- const { EMBER_THEME, installCustomTheme } = await import("../themePalette");- const firstTheme = installCustomTheme({- ...EMBER_THEME,- id: "first-custom",- label: "First Custom",- });- const secondTheme = installCustomTheme({- ...EMBER_THEME,- id: "second-custom",- label: "Second Custom",- colors: { ...EMBER_THEME.colors, error: "#123456" },- });- storage.setItem("t3code:theme", firstTheme.id);-- const { mountOnboardingTheme, useTheme } = await import("./useTheme");- expect(root.dataset.themeId).toBe(firstTheme.id);- expect(styleValues.get("--app-theme-error")).toBe(firstTheme.colors.error);-- const cleanup = mountOnboardingTheme();- expect(root.dataset.themeId).toBeUndefined();- expect(styleValues.size).toBe(0);-- expect(useTheme().setTheme(secondTheme.id)).toBe(true);- expect(root.dataset.themeId).toBeUndefined();- expect(styleValues.size).toBe(0);-- cleanup();- expect(root.dataset.themeId).toBe(secondTheme.id);- expect(styleValues.get("--app-theme-error")).toBe(secondTheme.colors.error);- });-- it("follows the saved appearance and restores the latest saved theme", async () => {- const storage = createStorage();- storage.setItem("t3code:theme", "dark");- const classes = new Set<string>();- const styleValues = new Map<string, string>();- const style = {- backgroundColor: "",- removeProperty: (name: string) => styleValues.delete(name),- setProperty: (name: string, value: string) => styleValues.set(name, value),- };- const root = {- classList: {- add: (name: string) => classes.add(name),- contains: (name: string) => classes.has(name),- remove: (name: string) => classes.delete(name),- toggle: (name: string, force?: boolean) => {- const next = force ?? !classes.has(name);- if (next) classes.add(name);- else classes.delete(name);- return next;- },- },- dataset: {} as Record<string, string>,- offsetHeight: 0,- style,- };- const body = { style: { backgroundColor: "" } };- let storageHandler: ((event: StorageEvent) => void) | undefined;- const setDesktopTheme = vi.fn().mockResolvedValue(undefined);- vi.doMock("react", () => ({- useCallback: <A>(callback: A) => callback,- useEffect: () => undefined,- useSyncExternalStore: (- subscribe: (listener: () => void) => () => void,- getSnapshot: () => unknown,- ) => {- subscribe(() => undefined);- return getSnapshot();- },- }));- vi.stubGlobal("window", {- addEventListener: (type: string, listener: (event: StorageEvent) => void) => {- if (type === "storage") storageHandler = listener;- },- localStorage: storage,- matchMedia: () => ({- matches: false,- addEventListener: () => undefined,- removeEventListener: () => undefined,- }),- removeEventListener: () => undefined,- desktopBridge: { setTheme: setDesktopTheme },- });- vi.stubGlobal("document", {- body,- createElement: () => ({ name: "", setAttribute: () => undefined }),- documentElement: root,- head: { append: () => undefined },- querySelector: () => null,- querySelectorAll: () => [],- });- vi.stubGlobal("getComputedStyle", () => ({- backgroundColor:- root.dataset.onboardingSurface !== undefined && classes.has("dark")- ? "rgb(0, 0, 0)"- : classes.has("dark")- ? "rgb(10, 10, 10)"- : "rgb(255, 255, 255)",- getPropertyValue: () => "",- }));- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {- callback(0);- return 0;- });-- const { mountOnboardingTheme, useTheme } = await import("./useTheme");- expect(useTheme().resolvedTheme).toBe("dark");- const cleanup = mountOnboardingTheme();-- // A dark preference pins the wizard to true black.- expect(root.dataset.onboardingSurface).toBe("");- expect(classes.has("dark")).toBe(true);- expect(root.style.backgroundColor).toBe("#000");- expect(body.style.backgroundColor).toBe("#000");- expect(useTheme().resolvedTheme).toBe("dark");- expect(setDesktopTheme).toHaveBeenLastCalledWith("dark");-- // A light preference switches the wizard to the default light palette.- storage.setItem("t3code:theme", "light");- storageHandler?.({ key: "t3code:theme" } as StorageEvent);- expect(classes.has("dark")).toBe(false);- expect(root.style.backgroundColor).toBe("rgb(255, 255, 255)");- expect(body.style.backgroundColor).toBe("rgb(255, 255, 255)");- expect(useTheme().resolvedTheme).toBe("light");- expect(setDesktopTheme).toHaveBeenLastCalledWith("light");-- cleanup();- expect(root.dataset.onboardingSurface).toBeUndefined();- expect(classes.has("dark")).toBe(false);- expect(root.style.backgroundColor).toBe("rgb(255, 255, 255)");- expect(body.style.backgroundColor).toBe("rgb(255, 255, 255)");- expect(storage.getItem("t3code:theme")).toBe("light");- expect(useTheme().resolvedTheme).toBe("light");- expect(setDesktopTheme).toHaveBeenLastCalledWith("light");- });-});diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.tsindex 3c3436eccf4..4eaa46286d8 100644--- a/apps/web/src/hooks/useTheme.ts+++ b/apps/web/src/hooks/useTheme.ts@@ -99,13 +99,6 @@ function themeHalvesSignature(halves: ThemeHalves | null): string {return `${halves?.light ?? ""}|${halves?.dark ?? ""}`;}-function isOnboardingThemeActive(): boolean {- return (- typeof document !== "undefined" &&- document.documentElement.dataset?.onboardingSurface !== undefined- );-}-const THEME_COLOR_META_NAME = "theme-color";const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;@@ -300,22 +293,15 @@ function resolveBrowserChromeSurface(): HTMLElement {export function syncBrowserChromeTheme() {if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;- const onboardingActive = isOnboardingThemeActive();const rootStyles = getComputedStyle(document.documentElement);- const themeChromeColor =- !onboardingActive && document.documentElement.dataset.themeId- ? normalizeThemeColor(rootStyles.getPropertyValue("--app-chrome-background"))- : null;+ const themeChromeColor = document.documentElement.dataset.themeId+ ? normalizeThemeColor(rootStyles.getPropertyValue("--app-chrome-background"))+ : null;const surfaceColor = normalizeThemeColor(getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,);const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);- // Dark onboarding pins a true-black canvas; light onboarding uses the- // default light palette and reads it back from the document like the app.- const backgroundColor =- onboardingActive && document.documentElement.classList.contains("dark")- ? "#000"- : (themeChromeColor ?? surfaceColor ?? fallbackColor);+ const backgroundColor = themeChromeColor ?? surfaceColor ?? fallbackColor;if (!backgroundColor) return;document.documentElement.style.backgroundColor = backgroundColor;@@ -336,13 +322,8 @@ export function syncBrowserChromeTheme() {function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview = true } = {}) {if (typeof document === "undefined" || typeof window === "undefined") return;- const onboardingActive = isOnboardingThemeActive();// Keep the editor's draft visible until an explicit refresh restores the selection.- if (- preservePreview &&- !onboardingActive &&- document.documentElement.dataset?.themeId === THEME_PREVIEW_ID- ) {+ if (preservePreview && document.documentElement.dataset?.themeId === THEME_PREVIEW_ID) {return;}const appearanceMode = readAppearanceModePreference(theme);@@ -370,11 +351,7 @@ function applyTheme(theme: Theme, { suppressTransitions = false, preservePreviewappearanceMode,themeHalves,);- // Onboarding follows the saved light/dark appearance but never applies a- // custom palette, so the wizard keeps its fixed neutral tokens.- if (!onboardingActive) {- applyThemePalette(resolveThemeHalf(theme, themeHalves, resolvedAppearance), resolvedAppearance);- }+ applyThemePalette(resolveThemeHalf(theme, themeHalves, resolvedAppearance), resolvedAppearance);document.documentElement.classList.toggle("dark", resolvedAppearance === "dark");lastAppliedTheme = { theme, systemDark, followSystem, appearanceMode, themeHalves };syncBrowserChromeTheme();@@ -388,32 +365,6 @@ function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview}}-/**- * Own the document-wide palette used by the first-run wizard and its portals.- * The wizard follows the saved light or dark appearance (and system changes)- * but drops any custom theme palette until the returned cleanup runs.- */-export function mountOnboardingTheme(): () => void {- if (typeof document === "undefined" || typeof window === "undefined") return () => {};-- const root = document.documentElement;- // "system" is a reserved id with no palette, so this clears theme variables.- applyThemePalette("system");- root.dataset.onboardingSurface = "";- lastAppliedTheme = null;- applyTheme(getStored(), { preservePreview: false });- emitChange();-- return () => {- delete root.dataset.onboardingSurface;- root.style.backgroundColor = "";- document.body.style.backgroundColor = "";- lastAppliedTheme = null;- applyTheme(getStored(), { suppressTransitions: true, preservePreview: false });- emitChange();- };-}-export async function syncDesktopThemePreference(bridge: DesktopThemeBridge,theme: Theme,diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 55eaa990f29..a0d7b2c1684 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -609,6 +609,18 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil}@layer components {+ /* AnimatedHeight owns resizing for its contents. Nested collapsibles must+ expose their final layout immediately, otherwise each animation frame+ restarts the parent's transition and the dialog trails behind its content. */+ [data-slot="animated-height"] [data-slot="collapsible-panel"] {+ height: auto !important;+ transition: none !important;+ }++ [data-slot="animated-height"] [data-slot="collapsible-panel"][data-closed] {+ display: none;+ }+/* Each maintainer palette gives the same line art its own material: rosevellum, forest drafting paper, marine cyanotype, copper, and violet ink.These colors stay deliberately deep at the top edge so the white stage@@ -1184,43 +1196,6 @@ html[data-theme-id]:not([data-theme-id=""]) {--terminal-selection-background: var(--app-theme-terminal-selection-background);}-/* The first-run flow owns the whole document so portaled menus and tooltips- use the same fixed palette as the wizard. Light onboarding uses the default- light palette from :root above. Dark onboarding pins a true-black palette.- This follows the theme mapping so saved custom themes cannot override it- while onboarding is mounted. */-html[data-onboarding-surface]:root {- @variant dark {- color-scheme: dark;- --accent: #262626;- --accent-foreground: #fff;- --appearance-contrast-target: #fff;- --app-chrome-background: #000;- --background: #000;- --border: #262626;- --card: #000;- --card-foreground: #fff;- --destructive: var(--color-red-400);- --foreground: #fff;- --icon-muted: #a1a1aa;- --input: #262626;- --muted: #171717;- --muted-foreground: #a1a1aa;- --placeholder: #71717a;- --popover: #171717;- --popover-foreground: #fff;- --ring: #737373;- --secondary: #171717;- --secondary-foreground: #fff;- --secondary-label: #a1a1aa;- --success-foreground: var(--color-emerald-400);- --terminal-background: #000;- --terminal-cursor: #fff;- --terminal-foreground: #fff;- --terminal-selection-background: rgb(255 255 255 / 20%);- }-}-/* Theme-token dependency probes are restored synchronously, before paint. Keeptransitions from observing the temporary sentinel color in between. */html[data-theme-token-probe],@@ -1424,8 +1399,7 @@ html[data-theme-id="t3-chat"] [data-app-sidebar] {/* Recompute contrast wherever a subtree owns its own semantic color palette. */:root,-[data-app-sidebar],-[data-onboarding-surface] {+[data-app-sidebar] {--contrast-toolbar-foreground: color-mix(in oklab,color-mix(diff --git a/apps/web/src/onboarding/projectImport.logic.test.ts b/apps/web/src/onboarding/projectImport.logic.test.tsindex 07028abd28b..58264759b82 100644--- a/apps/web/src/onboarding/projectImport.logic.test.ts+++ b/apps/web/src/onboarding/projectImport.logic.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";import {partitionOnboardingProjects,+ onboardingProjectKey,resolveOnboardingLandingProject,resolveOnboardingProjectId,} from "./projectImport.logic";@@ -243,3 +244,23 @@ describe("resolveOnboardingLandingProject", () => {).toBe("current");});});++describe("projects on multiple computers", () => {+ it("keeps identical paths independent when selecting a landing project after partial imports", () => {+ const first = onboardingProjectKey(EnvironmentId.make("first"), "/code/app");+ const second = onboardingProjectKey(EnvironmentId.make("second"), "/code/app");+ const completed = new Map([[first, "first-project"]]);+ expect(completed.has(second)).toBe(false);+ expect(resolveOnboardingLandingProject([second], completed, completed)).toBeUndefined();+ completed.set(second, "second-project");+ expect(resolveOnboardingLandingProject([second, first], completed, completed)).toBe(+ "second-project",+ );+ });++ it("preserves computer identity when choosing recent projects", () => {+ const first = { ...candidate("/code/app"), environmentId: "first" };+ const second = { ...candidate("/code/app"), environmentId: "second" };+ expect(partitionOnboardingProjects([first, second], now).recent).toEqual([first, second]);+ });+});diff --git a/apps/web/src/onboarding/projectImport.logic.ts b/apps/web/src/onboarding/projectImport.logic.tsindex d723b911b66..962fe1e0abd 100644--- a/apps/web/src/onboarding/projectImport.logic.ts+++ b/apps/web/src/onboarding/projectImport.logic.ts@@ -4,8 +4,8 @@ import type { AgentSessionProjectCandidate, EnvironmentId, ProjectId } from "@t3const RECENT_PROJECT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;/** Existing projects still need their agent history imported, so every scan candidate is offered. */-export function partitionOnboardingProjects(- candidates: ReadonlyArray<AgentSessionProjectCandidate>,+export function partitionOnboardingProjects<T extends AgentSessionProjectCandidate>(+ candidates: ReadonlyArray<T>,now = Date.now(),) {const cutoff = now - RECENT_PROJECT_WINDOW_MS;@@ -53,3 +53,8 @@ export function resolveOnboardingLandingProject<T>(}return undefined;}++/** Paths identify projects only within the computer that owns them. */+export function onboardingProjectKey(environmentId: EnvironmentId, path: string): string {+ return JSON.stringify([environmentId, path]);+}diff --git a/apps/web/src/onboarding/useProjectScans.ts b/apps/web/src/onboarding/useProjectScans.tsnew file mode 100644index 00000000000..fc039293048--- /dev/null+++ b/apps/web/src/onboarding/useProjectScans.ts@@ -0,0 +1,31 @@+import { RegistryContext, useAtomValue } from "@effect/atom-react";+import type { EnvironmentId } from "@t3tools/contracts";+import * as Option from "effect/Option";+import { AsyncResult, Atom } from "effect/unstable/reactivity";+import { useContext, useMemo } from "react";++import { agentSessionScan } from "../state/agentSessions";+import { formatEnvironmentQueryError } from "../state/query";++/** Subscribe to each selected computer without coupling their failures or refreshes. */+export function useProjectScans(environmentIds: readonly EnvironmentId[]) {+ const registry = useContext(RegistryContext);+ const scansAtom = useMemo(+ () =>+ Atom.make((get) =>+ environmentIds.map((environmentId) => {+ const atom = agentSessionScan({ environmentId, input: {} });+ const result = get(atom);+ return {+ environmentId,+ data: Option.getOrNull(AsyncResult.value(result)),+ error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,+ isPending: result.waiting || result._tag === "Initial",+ refresh: () => registry.refresh(atom),+ };+ }),+ ),+ [environmentIds, registry],+ );+ return useAtomValue(scansAtom);+}diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex 12cdd946f6c..f42a49304fd 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -124,15 +124,23 @@ function RootRouteView() {);}- // The welcome wizard is full-screen like /pair, but keeps toasts so its- // connect/import actions can report failures.+ // Show onboarding over the workspace, keeping automatic thread navigation+ // and other startup dialogs suspended until setup finishes.if (pathname === "/welcome") {return (<ToastProvider>- <DocumentTitleSync />- <ContrastAppearanceSync />- <FontAppearanceSync />- <Outlet />+ <AnchoredToastProvider>+ <DocumentTitleSync />+ <ContrastAppearanceSync />+ <EnvironmentThemeSync />+ <GlassAppearanceSync />+ <FontAppearanceSync />+ <CommandPalette>+ <AppSidebarLayout>+ <Outlet />+ </AppSidebarLayout>+ </CommandPalette>+ </AnchoredToastProvider></ToastProvider>);}diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsxindex 0fd9fc92945..e6bc867e982 100644--- a/apps/web/src/routes/_chat.index.tsx+++ b/apps/web/src/routes/_chat.index.tsx@@ -2,9 +2,9 @@ import { RefreshIcon } from "~/components/ui/refresh-icon";import { scopeProjectRef } from "@t3tools/client-runtime/environment";import { createFileRoute, Link } from "@tanstack/react-router";import { LinkIcon, PlusIcon } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";-import { openCommandPalette } from "../commandPaletteBus";+import { NoProjectsHero } from "../components/NoProjectsHero";import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";import { Button } from "../components/ui/button";import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";@@ -107,35 +107,6 @@ function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {);}-function NoProjectsHero() {- const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);-- return (- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">- <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">- <Empty className="flex-1">- <div className="w-full max-w-lg px-8 py-12">- <EmptyHeader className="max-w-none">- <EmptyTitle className="text-foreground text-2xl sm:text-3xl">- What should we work on?- </EmptyTitle>- <EmptyDescription className="mt-2 text-sm text-muted-foreground/78">- Add a project to start your first thread.- </EmptyDescription>- <div className="mt-6 flex justify-center">- <Button size="sm" onClick={openAddProject}>- <PlusIcon className="size-4" />- Add project- </Button>- </div>- </EmptyHeader>- </div>- </Empty>- </div>- </SidebarInset>- );-}-export const Route = createFileRoute("/_chat/")({component: ChatIndexRouteView,});diff --git a/apps/web/src/routes/welcome.tsx b/apps/web/src/routes/welcome.tsxindex 10caa4dd46f..eb5d4975ab2 100644--- a/apps/web/src/routes/welcome.tsx+++ b/apps/web/src/routes/welcome.tsx@@ -1,14 +1,11 @@-import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";+import { createFileRoute, redirect, useLocation, useNavigate } from "@tanstack/react-router";+import { useState } from "react";+import { NoProjectsHero } from "../components/NoProjectsHero";import { WelcomeWizard } from "../components/onboarding/WelcomeWizard";import { useNewThreadHandler } from "../hooks/useHandleNewThread";-/**- * First-run welcome wizard. Full-screen, outside the sidebar shell (the root- * route mounts this path bare, like /pair). Reached only via the first-run- * gate on the index route; visiting it directly after onboarding is harmless —- * finishing again just refreshes the completion flag.- */+/** Onboarding overlays the workspace. Visiting /welcome reopens setup. */export const Route = createFileRoute("/welcome")({beforeLoad: ({ context }) => {const { authGateState } = context;@@ -22,6 +19,10 @@ export const Route = createFileRoute("/welcome")({function WelcomeRouteView() {const { authGateState } = Route.useRouteContext();const navigate = useNavigate();+ // The root shell can remount this pending outlet after the location changes.+ // Never reopen setup while the destination route is still loading.+ const isWelcomeRoute = useLocation({ select: (location) => location.pathname === "/welcome" });+ const [dismissed, setDismissed] = useState(false);const openNewThread = useNewThreadHandler();// An authenticated gate means a primary server is serving this app —// desktop, `npx t3`, or a dev server — and that server is "this machine"@@ -29,17 +30,23 @@ function WelcomeRouteView() {// local server to offer.const localAvailable = authGateState.status === "authenticated";return (- <WelcomeWizard- localAvailable={localAvailable}- onDone={(projectRef) => {- if (projectRef !== undefined) {- void openNewThread(projectRef, { replace: true }).catch(() => {+ <>+ <NoProjectsHero />+ {isWelcomeRoute && !dismissed ? (+ <WelcomeWizard+ localAvailable={localAvailable}+ onDone={(projectRef) => {+ setDismissed(true);+ if (projectRef !== undefined) {+ void openNewThread(projectRef, { replace: true }).catch(() => {+ void navigate({ to: "/", replace: true });+ });+ return;+ }void navigate({ to: "/", replace: true });- });- return;- }- void navigate({ to: "/", replace: true });- }}- />+ }}+ />+ ) : null}+ </>);}diff --git a/docs/user/welcome-wizard.md b/docs/user/welcome-wizard.mdindex 2534c118edd..b169a7b7f25 100644--- a/docs/user/welcome-wizard.md+++ b/docs/user/welcome-wizard.md@@ -3,18 +3,28 @@T3 Code shows a setup flow when you open a new installation or connect to thehosted app for the first time. Existing workspaces skip this flow.-## Choose a connection+## Connect your computers++Select one or more computers to set up. If you opened T3 Code directly from a+server or the desktop app, that computer is already connected and selected.+It is identified by its name, which may differ from the device running your+browser.++You can add more computers before continuing:-- **This computer** runs agents on the computer that hosts T3 Code. It does not- require an account.- **T3 Connect** connects computers that are signed in to your account. Run`npx t3 connect` on each computer you want to add, then start T3 Code or run`npx t3 serve` so the computer stays available.-- **Pair a server** connects directly to a server on your network or tailnet.+- **Add a computer** connects directly to a server on your network or tailnet.Start the server with `npx t3 serve`, then run `npx t3 pair --tailscale` andpaste the pairing link. You can also run `npx t3 serve --host <address>` anduse `npx t3 pair` when the server is already reachable on your network.+Saved computers and computers discovered through T3 Connect are selected by+default. Uncheck any you do not want to set up; this does not disconnect them.+Continue when your selected computers are connected. Setup checks+agents across the selected computers, then offers project import grouped by computer.+If T3 Code cannot confirm the workspace during startup, the setup flow shows**Still connecting** instead of opening the app. Select **Reload** to try again.@@ -24,7 +34,7 @@ unreadable settings with defaults.## Check your agents-T3 Code checks the selected computer for Claude Code and Codex. If an agent is+T3 Code checks each selected computer for Claude Code and Codex. If an agent isnot installed or signed in, select its action to open a terminal with thecorrect command ready to run. Install uses the vendor's standalone installer,which does not need Node or npm and keeps **Update now** working in Settings.@@ -37,7 +47,7 @@ terminal metadata while the terminal process can use them.## Import your projectsT3 Code finds directories that Claude Code or Codex has used. The default-selection includes projects active within the last 30 days. Select **Choose**+selection includes projects active within the last 30 days. Use the checkboxesto include older projects or change the selection.A large or malformed history can reach the scan limit. T3 Code keeps the@@ -60,5 +70,5 @@ with up to 100,000 input records. Run import again to continue a large batch.Completed conversations are not imported again. You can continue without theremaining history.-You can skip agent setup and project import. Select **Back** to return to a-previous step.+You can continue without configuring agents or importing projects, or return to an earlier step+using the setup progress bar. Navigation pauses while an import is running.