Skip to content

The agent that grows with you

36.4 KB
Raw Blame
import type { ModelOptionProvider } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useEffect, useMemo, useRef, useState } from 'react'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Codicon } from '@/components/ui/codicon'
import { Input } from '@/components/ui/input'
import { Progress } from '@/components/ui/progress'
import { getGlobalModelOptions } from '@/hermes'
import { useI18n } from '@/i18n'
import { Check, ChevronDown, ChevronLeft, KeyRound, Loader2 } from '@/lib/icons'
import { isSubmitEnter } from '@/lib/ime'
import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'
import { cn } from '@/lib/utils'
import { $desktopBoot, type DesktopBootState } from '@/store/boot'
import { $freeTierStatus, FREE_TIER_MODEL, freeTierSetupFailure } from '@/store/free-tier'
import { openFreeTierSignIn } from '@/store/free-tier-sign-in'
import { $setupReadyTick } from '@/store/live-sync'
import { $localModelsEnabled } from '@/store/local-models-flag'
import {
  $desktopOnboarding,
  ackFreeTierIntro,
  clearFreeTierIntro,
  clearPendingProviderOAuth,
  closeManualOnboarding,
  confirmOnboardingModel,
  DEFAULT_MANUAL_ONBOARDING_REASON,
  DEFAULT_ONBOARDING_REASON,
  dismissFirstRunOnboarding,
  type OnboardingContext,
  peekPendingProviderOAuth,
  refreshOnboarding,
  saveOnboardingApiKey,
  setOnboardingMode,
  startManualOnboarding,
  startProviderOAuth
} from '@/store/onboarding'
import { $onboardingSurfaces, onboardingSurfaceActive } from '@/store/onboarding-presence'
import type { OAuthProvider } from '@/types/hermes'

import { DocsLink, FlowPanel, Status } from './flow'
import { FreeTierSetupNotice } from './free-tier-setup-notice'
import { DecodedLabel } from './glyph'
import {
  FeaturedProviderRow,
  FireworksProviderRow,
  LocalModelsProviderRow,
  OpenRouterProviderRow,
  ProviderRow,
  sortProviders
} from './providers'

export {
  FeaturedProviderRow,
  FireworksProviderRow,
  KeyProviderRow,
  LocalModelsProviderRow,
  OpenRouterProviderRow,
  ProviderRow,
  providerTitle,
  sortProviders
} from './providers'

import { $gateway, activeGatewayConnectionId } from '@/store/gateway'
import { captureOnboardingScope, requestOnboardingGateway } from '@/store/onboarding-scope'

interface DesktopOnboardingOverlayProps {
  enabled: boolean
  onCompleted?: () => void
  profile: string
  requestGateway: OnboardingContext['requestGateway']
}

export interface ApiKeyOption {
  description?: string
  docsUrl: string
  envKey: string
  id: string
  name: string
  placeholder?: string
  short?: string
}

// Curated order mirrors CANONICAL_PROVIDERS: Fireworks sits #2 overall (after
// Nous Portal OAuth), ahead of OpenRouter and the rest of the key catalog.
const API_KEY_OPTIONS: ApiKeyOption[] = [
  {
    id: 'fireworks',
    name: 'Fireworks AI',
    envKey: 'FIREWORKS_API_KEY',
    docsUrl: 'https://app.fireworks.ai/settings/users/api-keys'
  },
  {
    id: 'openrouter',
    name: 'OpenRouter',
    envKey: 'OPENROUTER_API_KEY',
    docsUrl: 'https://openrouter.ai/keys'
  },
  {
    id: 'openai',
    name: 'OpenAI',
    envKey: 'OPENAI_API_KEY',
    docsUrl: 'https://platform.openai.com/api-keys'
  },
  {
    id: 'gemini',
    name: 'Google Gemini',
    envKey: 'GEMINI_API_KEY',
    docsUrl: 'https://aistudio.google.com/app/apikey'
  },
  {
    id: 'xai',
    name: 'xAI Grok',
    envKey: 'XAI_API_KEY',
    docsUrl: 'https://console.x.ai/'
  },
  {
    id: 'local',
    name: 'Local / custom endpoint',
    envKey: 'OPENAI_BASE_URL',
    docsUrl: 'https://github.com/NousResearch/hermes-agent#bring-your-own-endpoint',
    placeholder: 'http://127.0.0.1:8000/v1'
  }
]

// Build the FULL API-key provider catalog from the backend model options so the
// onboarding / Providers key form lists every `api_key` provider `hermes model`
// knows about — not just the hand-curated five. Curated entries keep their
// richer copy + placeholders and float to the top (recommended defaults); every
// other api_key provider is appended with a generic "paste {KEY}" affordance.
// OAuth / external providers are intentionally excluded here — they go through
// the OAuth picker / sign-in flow, not a pasted key.
function useApiKeyCatalog(scope: OnboardingContext['scope']): ApiKeyOption[] {
  const [rows, setRows] = useState<ModelOptionProvider[]>([])

  useEffect(() => {
    let cancelled = false

    // Best-effort — on failure the curated defaults still render. Wrapped in
    // Promise.resolve().then so a synchronous throw (e.g. no desktop bridge in
    // tests) is funneled into the same .catch instead of escaping.
    void Promise.resolve()
      .then(() => getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false }, scope))
      .then(res => {
        if (!cancelled) {
          setRows(res.providers ?? [])
        }
      })
      .catch(() => {
        // Ignore — fall back to the curated API_KEY_OPTIONS only.
      })

    return () => {
      cancelled = true
    }
  }, [scope])

  return useMemo(() => {
    const curatedByEnv = new Map(API_KEY_OPTIONS.map(o => [o.envKey, o]))
    const derived: ApiKeyOption[] = []
    const seenEnv = new Set<string>(API_KEY_OPTIONS.map(o => o.envKey))

    for (const row of rows) {
      // Only api_key providers can be activated with a pasted key. Skip OAuth /
      // external / managed flows and anything missing an env var to write to.
      if (row.auth_type && row.auth_type !== 'api_key') {
        continue
      }

      const envKey = row.key_env

      if (!envKey || seenEnv.has(envKey)) {
        continue
      }

      seenEnv.add(envKey)
      derived.push({
        id: row.slug,
        name: row.name,
        envKey,
        description: `Direct API access to ${row.name}.`,
        docsUrl: ''
      })
    }

    // Curated first (recommended order), then the rest alphabetically so the
    // long tail is scannable.
    derived.sort((a, b) => a.name.localeCompare(b.name))

    return [...API_KEY_OPTIONS.filter(o => curatedByEnv.has(o.envKey)), ...derived]
  }, [rows])
}

// Exit choreography, mirroring the gateway "connecting" overlay's timing:
// text-out (360ms: CONNECTED fades down, rest scrambles+fades) → hold (300ms)
// → surface-out (520ms, held back by [transition-delay:660ms]). Finalize after.
const ONBOARDING_EXIT_MS = 1180

export function DesktopOnboardingOverlay({
  enabled,
  onCompleted,
  profile,
  requestGateway
}: DesktopOnboardingOverlayProps) {
  const { t } = useI18n()
  const onboarding = useStore($desktopOnboarding)
  const boot = useStore($desktopBoot)
  useStore($onboardingSurfaces)
  const onCompletedRef = useRef(onCompleted)
  onCompletedRef.current = onCompleted
  useStore($gateway)
  const connectionId = activeGatewayConnectionId()

  const scope = useMemo(
    () => onboarding.targetScope ?? captureOnboardingScope({ connectionId, profile }),
    [onboarding.targetScope, profile, connectionId]
  )

  // Async flows retain the initiating route even after the overlay closes.
  const ctx = useMemo<OnboardingContext>(
    () => ({
      scope,
      profile: scope.profile ?? undefined,
      requestGateway:
        scope.connectionId || (scope.profile && onboarding.targetScope)
          ? (method, params) => requestOnboardingGateway(scope, method, params)
          : requestGateway,
      onCompleted: () => onCompletedRef.current?.()
    }),
    [onboarding.targetScope, scope, requestGateway]
  )

  // Cinematic exit on "Begin": dissolve the panel + overlay (revealing the chat
  // behind), THEN finalize so the unmount lands after the fade — mirrors the
  // connecting overlay's exit choreography instead of cutting instantly.
  const [leaving, setLeaving] = useState(false)

  const finalizeOnboarding = () => {
    if (leaving) {
      return
    }

    const reduce = typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches

    if (reduce) {
      void confirmOnboardingModel(ctx)

      return
    }

    setLeaving(true)
    window.setTimeout(() => void confirmOnboardingModel(ctx), ONBOARDING_EXIT_MS)
  }

  // The free-tier intro's three doors share one exit: consume the notice, play
  // the same dissolve, then run whatever the door opens onto. `after` runs at
  // the END so a sign-in dialog or provider picker never appears behind a
  // still-fading overlay.
  const dismissFreeTierIntro = async (after?: () => void) => {
    if (leaving) {
      return
    }

    // The screen is keyed on the backend's notice flag: only a recorded ack takes it down.
    // A failed ack leaves it in place for another try rather than hiding the only notice.
    if (!(await ackFreeTierIntro(ctx))) {
      return
    }

    const reduce = typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches

    if (reduce) {
      clearFreeTierIntro()
      after?.()

      return
    }

    setLeaving(true)
    window.setTimeout(() => {
      setLeaving(false)
      clearFreeTierIntro()
      after?.()
    }, ONBOARDING_EXIT_MS)
  }

  useEffect(() => {
    if (enabled || onboarding.requested) {
      void refreshOnboarding(ctx)
    }
  }, [ctx, enabled, onboarding.requested])

  // The boot bootstrap re-announces `setup.ready` when a background retry of
  // the free-tier set-up succeeds after a failed first attempt. A picker that
  // is up only because that set-up failed re-checks readiness and gives way
  // on its own. An untouched picker only: a manual open, a provider flow in
  // progress, or the API-key form (which leaves the flow idle while the user
  // types) is left alone, and the check is repeated after the readiness
  // round so a key form opened in the meantime survives too.
  useEffect(
    () =>
      $setupReadyTick.listen(() => {
        const untouched = () => {
          const current = $desktopOnboarding.get()

          return (
            // `!== true` rather than `=== false`: an UNRESOLVED readiness state
            // (a boot round whose probes both timed out) is left at `null`
            // instead of being written down as unconfigured, and it needs this
            // tick to settle too — otherwise the overlay sits on its
            // "starting" header with nothing left to re-check it.
            !current.manual &&
            current.configured !== true &&
            current.flow.status === 'idle' &&
            current.mode === 'oauth' &&
            !current.localEndpoint
          )
        }

        if (untouched()) {
          void refreshOnboarding(ctx, untouched)
        }
      }),
    [ctx]
  )
  const freeTierStatus = useStore($freeTierStatus)
  const setupFailure = !onboarding.manual ? freeTierSetupFailure(freeTierStatus) : null

  // When the Providers settings page asked to connect a specific provider, the
  // store stashed its id. Once the provider list has loaded and we're back at
  // an idle picker, launch that exact OAuth flow so the user lands directly in
  // sign-in instead of the picker they just came from.
  useEffect(() => {
    if (!onboarding.manual || onboarding.providers === null || onboarding.flow.status !== 'idle') {
      return
    }

    const pendingId = peekPendingProviderOAuth()

    if (!pendingId) {
      return
    }

    const provider = onboarding.providers.find(p => p.id === pendingId)

    if (provider) {
      // Only clear once we've committed to launching it, so a failed/empty
      // provider fetch doesn't silently drop the hand-off.
      clearPendingProviderOAuth()
      void startProviderOAuth(provider, ctx)
    } else if (onboarding.providers.length > 0) {
      // The list loaded but the id isn't a real provider — drop the stale
      // hand-off. An empty list means the fetch isn't ready yet, so keep it
      // and let a later refresh retry.
      clearPendingProviderOAuth()
    }
  }, [ctx, onboarding.flow.status, onboarding.manual, onboarding.providers])

  if (!onboarding.manual && onboardingSurfaceActive()) {
    return null
  }

  // Mount from frame 1 so we replace the boot overlay seamlessly. The
  // configured field stays null until the runtime check resolves; only then
  // do we know whether to dismiss (true) or surface the picker (false).
  // EXCEPTION: manual mode (user opened the selector from a working app to
  // add/switch a provider) shows the overlay regardless of configured state.
  if (onboarding.configured === true && !onboarding.manual && !onboarding.freeTierReady) {
    return null
  }

  // The user chose "I'll choose a provider later" on first run. Stay out of the
  // way on every subsequent launch — they re-enter via Settings → Providers
  // (manual mode), which sets manual=true and bypasses this gate.
  // `requested` also outranks the skip: it is only ever set when the user hit a
  // REAL credential wall (the submit-time deferred warning, a stream that
  // reported a provider setup error), never by a passive readiness round. Now
  // that the skip is durable, without this a genuinely broken provider could
  // leave the user with a prompt that silently refuses to send and no picker.
  if (onboarding.firstRunSkipped && !onboarding.requested && !onboarding.manual && !onboarding.freeTierReady) {
    return null
  }

  const { flow } = onboarding
  // Show the launch reason only when it's a meaningful, caller-supplied prompt —
  // suppress the generic defaults (useless noise) and provider-setup errors
  // (those are surfaced by FlowPanel, not as a banner).
  const rawReason = onboarding.reason?.trim() || null

  // When the free tier itself failed to set up, its own notice explains the
  // picker; the runtime check's technical reason ("No usable credentials
  // found for nous.") would only restate it in the wrong words.
  const reason =
    rawReason &&
    !setupFailure &&
    !isProviderSetupErrorMessage(rawReason) &&
    rawReason !== DEFAULT_ONBOARDING_REASON &&
    rawReason !== DEFAULT_MANUAL_ONBOARDING_REASON
      ? rawReason
      : null

  // In manual mode the app is already configured, so the flow is "ready"
  // immediately — no runtime gate needed. Otherwise wait for the readiness
  // check (configured === false) before showing the picker.
  // The free-tier intro owns the overlay while it is up: the app is already
  // configured, so there is no picker to show and no runtime gate to wait on.
  // A manual open (the user asked for the picker) outranks it.
  const freeTierIntro = onboarding.freeTierReady && !onboarding.manual && flow.status === 'idle'
  const ready = freeTierIntro || onboarding.manual || (enabled && onboarding.configured === false)
  const showPicker = !freeTierIntro && (flow.status === 'idle' || flow.status === 'success')
  // The final "you're in" screen drops the card chrome and floats centered on
  // the surface — same bare, cinematic treatment as the connecting overlay.
  const bare = ready && (freeTierIntro || (!showPicker && flow.status === 'confirming_model'))

  return (
    <div
      className={cn(
        'fixed inset-0 z-(--z-onboarding) flex items-center justify-center bg-(--ui-chat-surface-background) p-6 transition-opacity duration-[520ms] ease-out',
        // On the bare confirm screen, hold the surface (text-out + hold) so the
        // per-element exit plays before it dissolves.
        bare && leaving ? '[transition-delay:660ms]' : '',
        leaving ? 'pointer-events-none opacity-0' : 'opacity-100'
      )}
      // Masks the whole app until onboarding finishes — must stay filled under
      // window glass or the shell shows through. Contract:
      // `[data-glass-opaque]` in styles.css.
      data-glass-opaque=""
    >
      <div
        className={cn(
          'relative w-full max-w-[45rem] transition-all duration-500 ease-out',
          bare
            ? ''
            : 'overflow-hidden rounded-xl border border-(--stroke-nous) bg-(--ui-chat-bubble-background) shadow-nous',
          // Bare confirm screen orchestrates its own per-element exit; the
          // carded states use the simple lift/blur dissolve.
          leaving && !bare
            ? '-translate-y-1 scale-[0.985] opacity-0 blur-[2px]'
            : 'translate-y-0 scale-100 opacity-100 blur-0'
        )}
      >
        {showPicker || !ready ? <Header /> : null}
        {onboarding.manual ? (
          <Button
            aria-label={t.common.close}
            className="absolute right-3 top-3 z-10 text-(--ui-text-tertiary) hover:bg-(--chrome-action-hover) hover:text-foreground"
            onClick={() => closeManualOnboarding()}
            size="icon-sm"
            variant="ghost"
          >
            <Codicon name="close" size="1rem" />
          </Button>
        ) : null}
        <div className="grid gap-3 p-5">
          {reason ? <ReasonNotice reason={reason} /> : null}
          {ready && showPicker && !freeTierIntro && !onboarding.manual ? <FreeTierSetupNotice ctx={ctx} /> : null}
          {ready ? (
            freeTierIntro ? (
              <FreeTierReadyPanel leaving={leaving} onDismiss={dismissFreeTierIntro} />
            ) : showPicker ? (
              <Picker ctx={ctx} />
            ) : (
              <FlowPanel ctx={ctx} flow={flow} leaving={leaving} onBegin={finalizeOnboarding} />
            )
          ) : (
            <Preparing boot={boot} />
          )}
        </div>
      </div>
    </div>
  )
}

/**
 * The one-time free-tier welcome, shown when the free tier is what serves this
 * user. Bare and centered like the model-confirm screen it stands in for: this
 * IS their "you're in" moment, so it names the route, its model and its price,
 * and offers the two ways out of it (a real account, or a provider of their
 * own) without making either the default.
 */
function FreeTierReadyPanel({
  leaving,
  onDismiss
}: {
  leaving: boolean
  onDismiss: (after?: () => void) => Promise<void>
}) {
  const { t } = useI18n()
  const copy = t.freeTier

  return (
    <div className="grid place-items-center gap-7 py-6 text-center">
      <DecodedLabel leaving={leaving} text={copy.readyTitle} />

      <div
        className={cn(
          'grid justify-items-center gap-1.5 transition duration-[360ms] ease-out',
          leaving ? 'opacity-0 saturate-0' : 'opacity-100 saturate-100'
        )}
      >
        <div className="flex items-center gap-2">
          <span className="font-mono text-[0.625rem] uppercase tracking-[0.2em] text-muted-foreground">
            {t.onboarding.defaultModel}
          </span>
          <Badge size="xs" variant="success">
            {t.onboarding.freeTier}
          </Badge>
        </div>
        <p className="font-mono text-base">{FREE_TIER_MODEL}</p>
        <p className="font-mono text-xs text-muted-foreground">{copy.readyCaption}</p>
      </div>

      <div
        className={cn(
          'grid justify-items-center gap-2 transition duration-[360ms] ease-out',
          leaving ? 'opacity-0 saturate-0' : 'opacity-100 saturate-100'
        )}
      >
        <Button onClick={() => void onDismiss()} type="button">
          {copy.begin}
        </Button>
        <Button onClick={() => void onDismiss(() => openFreeTierSignIn())} size="xs" type="button" variant="text">
          {copy.signInInstead}
        </Button>
        <Button
          onClick={() => void onDismiss(() => startManualOnboarding(null))}
          size="xs"
          type="button"
          variant="text"
        >
          {copy.otherProviders}
        </Button>
      </div>
    </div>
  )
}

// The launch reason is a prompt ("why am I seeing this"), not an error. Only
// rendered for meaningful caller-supplied reasons (defaults are filtered out
// upstream), so it never shows the generic "no provider configured" noise.
function ReasonNotice({ reason }: { reason: string }) {
  return (
    <div className="rounded-2xl border border-(--ui-stroke-tertiary) bg-(--ui-bg-tertiary)/40 px-4 py-3 text-sm text-muted-foreground">
      {reason}
    </div>
  )
}

function Preparing({ boot }: { boot: DesktopBootState }) {
  const { t } = useI18n()
  const progress = Math.max(2, Math.min(100, Math.round(boot.progress)))
  const hasError = Boolean(boot.error)
  const installing = boot.phase.startsWith('runtime.')

  return (
    <div className="grid gap-3" role="status">
      <p className="text-sm text-muted-foreground">
        {installing ? t.onboarding.preparingInstall : t.onboarding.starting}
      </p>
      <Progress
        aria-label={installing ? t.onboarding.preparingInstall : t.onboarding.starting}
        destructive={hasError}
        size="lg"
        value={progress / 100}
      />
      <div className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
        <span className="truncate">{boot.message}</span>
        <span>{progress}%</span>
      </div>
      {hasError ? <p className="text-xs text-destructive">{boot.error}</p> : null}
    </div>
  )
}

function Header() {
  const { t } = useI18n()

  return (
    <div className="bg-(--ui-chat-bubble-background) px-5 pt-5 pb-1">
      <h2 className="text-[0.9375rem] font-semibold tracking-tight">{t.onboarding.headerTitle}</h2>
      <p className="mt-1 max-w-xl text-[0.8125rem] leading-5 text-(--ui-text-tertiary)">{t.onboarding.headerDesc}</p>
    </div>
  )
}

export const FEATURED_ID = 'nous'

// Stand-in for the Nous row when the OAuth provider list could not be read
// (it failed or came back empty, which drops the picker onto the key form).
// Starting sign-in only needs the id; the backend's start reply decides the flow.
const NOUS_FALLBACK: OAuthProvider = {
  cli_command: 'hermes auth add nous',
  docs_url: 'https://portal.nousresearch.com',
  flow: 'device_code',
  id: FEATURED_ID,
  name: 'Nous Portal',
  status: { logged_in: false }
}

const SHOW_ALL_KEY = 'hermes-onboarding-show-all-v1'

const readShowAll = () => {
  try {
    return window.localStorage.getItem(SHOW_ALL_KEY) === '1'
  } catch {
    return false
  }
}

const persistShowAll = (value: boolean) => {
  try {
    window.localStorage.setItem(SHOW_ALL_KEY, value ? '1' : '0')
  } catch {
    // localStorage unavailable — degrade silently.
  }

  return value
}

export function Picker({ ctx }: { ctx: OnboardingContext }) {
  const { t } = useI18n()
  const { localEndpoint, manual, mode, providers } = useStore($desktopOnboarding)
  const [showAll, setShowAll] = useState(readShowAll)
  // Which key-form option to preselect when we flip to 'apikey' mode. The
  // OpenRouter row selects its key; the generic link lands on the first option.
  const [apiKeyInitialEnv, setApiKeyInitialEnv] = useState<string | undefined>(undefined)

  const openKeyForm = (envKey?: string) => {
    setApiKeyInitialEnv(envKey)
    setOnboardingMode('apikey')
  }

  const ordered = useMemo(() => (providers ? sortProviders(providers) : []), [providers])
  const hasOauth = ordered.length > 0
  const apiKeyOptions = useApiKeyCatalog(ctx.scope)
  const select = (p: OAuthProvider) => void startProviderOAuth(p, ctx)

  // localEndpoint forces the key form regardless of `mode` (which a manual
  // provider refresh may flip back to 'oauth'); it preselects the local option
  // and hides the "back to sign in" link since the user came specifically to
  // configure a custom endpoint. A list still loading (null) is not "no OAuth
  // providers": it waits below instead of flashing the key form.
  if (localEndpoint || mode === 'apikey' || (providers !== null && !hasOauth)) {
    return (
      <KeyFormStep
        apiKeyOptions={apiKeyOptions}
        ctx={ctx}
        hasOauth={hasOauth}
        initialEnvKey={apiKeyInitialEnv}
        localEndpoint={localEndpoint}
        manual={manual}
        onSelect={select}
        providers={ordered}
      />
    )
  }

  if (providers === null) {
    return <Status>{t.onboarding.lookingUpProviders}</Status>
  }

  const featured = ordered.find(p => p.id === FEATURED_ID) ?? null
  const rest = featured ? ordered.filter(p => p.id !== FEATURED_ID) : ordered
  // Collapse the secondary providers behind a disclosure whenever Nous Portal
  // is present to anchor the choice — otherwise show the full list. The
  // Fireworks/OpenRouter key rows always live behind the disclosure, so the
  // toggle is warranted even when there are no other OAuth providers.
  const collapsible = Boolean(featured)
  const showRest = !collapsible || showAll

  // "Run models locally" leaves the picker for Settings -> Providers ->
  // Local Models, where install/download live. First-run: persist the skip
  // (same contract as ChooseLaterLink) so the blocking overlay never
  // re-nags; manual mode just closes. window.location keeps this picker
  // router-independent (it renders outside the route tree on first run).
  const openLocalModels = () => {
    if (manual) {
      closeManualOnboarding()
    } else {
      dismissFirstRunOnboarding()
    }

    window.location.hash = '#/settings?tab=providers&pview=local'
  }

  return (
    <div className="grid gap-2">
      <div className="grid max-h-[60dvh] gap-2 overflow-y-auto p-1">
        {featured ? <FeaturedProviderRow onSelect={select} provider={featured} /> : null}
        {/* The no-account path: everything runs on this machine. Shipped
            behind the --local launch flag. (Fireworks moved into the
            expanded list on main.) */}
        {$localModelsEnabled.get() ? <LocalModelsProviderRow onClick={openLocalModels} /> : null}
        {showRest ? (
          <>
            {/* Fireworks leads the expanded list, matching CANONICAL_PROVIDERS
                (Nous → Fireworks), but stays hidden until the user opens it. */}
            <FireworksProviderRow onClick={() => openKeyForm('FIREWORKS_API_KEY')} />
            {rest.map(p => (
              <ProviderRow key={p.id} onSelect={select} provider={p} />
            ))}
            <OpenRouterProviderRow onClick={() => openKeyForm('OPENROUTER_API_KEY')} />
          </>
        ) : null}
      </div>
      {collapsible ? (
        <Button
          className="mt-1 self-center font-medium"
          onClick={() => setShowAll(persistShowAll(!showAll))}
          size="xs"
          type="button"
          variant="text"
        >
          {showAll ? t.onboarding.collapse : t.onboarding.otherProviders}
          <ChevronDown className={cn('size-3.5 transition', showAll && 'rotate-180')} />
        </Button>
      ) : null}
      <div className="flex items-center justify-between gap-3 pt-1">
        {/* First run only: let the user defer the choice and land in the app.
            In manual mode the overlay already has a close affordance, so the
            "choose later" escape would be redundant — hide it. */}
        {manual ? <span /> : <ChooseLaterLink />}
        <Button className="-mr-2 font-medium" onClick={() => openKeyForm()} size="xs" type="button" variant="text">
          {t.onboarding.haveApiKey}
        </Button>
      </div>
    </div>
  )
}

// The API-key step of the picker. Nous stays reachable from it, including when
// the provider list failed to load and there is no picker to go back to; the
// custom-endpoint form (localEndpoint) is a deliberate destination and skips it.
function KeyFormStep({
  apiKeyOptions,
  ctx,
  hasOauth,
  initialEnvKey,
  localEndpoint,
  manual,
  onSelect,
  providers
}: {
  apiKeyOptions: ApiKeyOption[]
  ctx: OnboardingContext
  hasOauth: boolean
  initialEnvKey?: string
  localEndpoint: boolean
  manual: boolean
  onSelect: (provider: OAuthProvider) => void
  providers: OAuthProvider[]
}) {
  const nous = localEndpoint ? null : (providers.find(p => p.id === FEATURED_ID) ?? NOUS_FALLBACK)

  return (
    <div className="grid gap-3">
      {nous ? <FeaturedProviderRow onSelect={onSelect} provider={nous} /> : null}
      <ApiKeyForm
        canGoBack={hasOauth && !localEndpoint}
        initialEnvKey={localEndpoint ? 'OPENAI_BASE_URL' : initialEnvKey}
        onBack={() => setOnboardingMode('oauth')}
        onSave={(envKey, value, name, apiKey, modelName) =>
          saveOnboardingApiKey(envKey, value, name, ctx, apiKey, modelName)
        }
        options={apiKeyOptions}
      />
      {manual ? null : (
        <div className="flex justify-center pt-1">
          <ChooseLaterLink />
        </div>
      )}
    </div>
  )
}

// "I'll choose a provider later" — dismisses the first-run picker and persists
// the skip so it never re-nags. The user connects a provider any time from
// Settings → Providers. Rendered only on the unconfigured first-run flow.
function ChooseLaterLink() {
  const { t } = useI18n()

  return (
    <Button className="font-medium" onClick={() => dismissFirstRunOnboarding()} size="xs" type="button" variant="text">
      {t.onboarding.chooseLater}
    </Button>
  )
}

// Presentational two-column key picker. Onboarding feeds it its curated
// options + a ctx-bound save; the Providers settings page feeds it the full
// provider catalog + a setEnvVar-backed save (plus `isSet`/`onClear` so it can
// double as a manage surface). Keep it free of store/ctx coupling so both
// surfaces render the identical form.
export function ApiKeyForm({
  canGoBack,
  initialEnvKey,
  isSet,
  onBack,
  onClear,
  onSave,
  options = API_KEY_OPTIONS,
  redactedValue
}: {
  canGoBack: boolean
  /** Preselect a specific option by env key (e.g. 'OPENAI_BASE_URL' to land on
   *  the local / custom endpoint form). Falls back to the first option. */
  initialEnvKey?: string
  isSet?: (envKey: string) => boolean
  onBack: () => void
  onClear?: (envKey: string) => void
  onSave: (
    envKey: string,
    value: string,
    name: string,
    apiKey?: string,
    modelName?: string
  ) => Promise<{ message?: string; needsModelInput?: boolean; ok: boolean }>
  options?: ApiKeyOption[]
  redactedValue?: (envKey: string) => null | string | undefined
}) {
  const { t } = useI18n()

  const [option, setOption] = useState<ApiKeyOption>(() => options.find(o => o.envKey === initialEnvKey) ?? options[0])

  const [value, setValue] = useState('')
  // Optional endpoint API key, only used by the local / custom endpoint option
  // (whose `value` is the base URL). Cleared whenever the option changes.
  const [localKey, setLocalKey] = useState('')
  // Optional manual model name, only used by the local / custom endpoint
  // option when the previous probe came back with zero /v1/models entries.
  // The input is hidden until the save call asks for it (needsModelInput), so
  // the happy path (discovery finds a model) stays uncluttered.
  const [modelName, setModelName] = useState('')
  const [showModelInput, setShowModelInput] = useState(false)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<null | string>(null)
  // `options` can change at runtime when callers filter the catalog (e.g. the
  // Providers page wiring its search into this grid). Keep the selection valid
  // by snapping back to the first remaining option when the current one drops.
  useEffect(() => {
    if (options.length > 0 && !options.some(o => o.envKey === option.envKey)) {
      setOption(options[0])
      setValue('')
      setLocalKey('')
      setModelName('')
      setShowModelInput(false)
      setError(null)
    }
  }, [option.envKey, options])
  // The catalog grid can be tall, leaving the entry field far below the fold.
  // On selection we scroll the field into view and focus it so it's always
  // obvious where to paste next.
  const entryRef = useRef<HTMLDivElement>(null)

  const pick = (o: ApiKeyOption) => {
    setOption(o)
    setValue('')
    setLocalKey('')
    setModelName('')
    setShowModelInput(false)
    setError(null)
    requestAnimationFrame(() => {
      entryRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
      entryRef.current?.querySelector('input')?.focus()
    })
  }

  const isLocal = option.envKey === 'OPENAI_BASE_URL'
  const alreadySet = isSet?.(option.envKey) ?? false
  // When set, surface the backend's redacted value (e.g. "sk-12…wxyz") as the
  // placeholder so users can eyeball that the right key is in place.
  const currentRedacted = alreadySet ? (redactedValue?.(option.envKey) ?? null) : null
  // Only require a non-empty value — no length/format validation, so a short
  // or unusual key can't block the user from continuing. When the manual model
  // input is showing, also require it to be filled (a saved endpoint without a
  // model is still broken from the runtime's POV).
  const canSave = value.trim().length >= 1 && (!isLocal || !showModelInput || modelName.trim().length >= 1)
  const optionCopy = t.onboarding.apiKeyOptions[option.id]
  const optionDescription = optionCopy?.description ?? option.description

  const submit = async () => {
    if (!canSave || saving) {
      return
    }

    setSaving(true)
    setError(null)

    const result = await onSave(
      option.envKey,
      value,
      option.name,
      isLocal ? localKey : undefined,
      isLocal && showModelInput ? modelName : undefined
    )

    if (result.ok) {
      setValue('')
      setLocalKey('')
      setModelName('')
      setShowModelInput(false)
    } else {
      setError(result.message ?? t.onboarding.couldNotSave)

      // The save handler asks the wizard to reveal a manual model-name input
      // when the endpoint didn't enumerate any models at /v1/models — the path
      // for OpenAI-compatible SaaS (Cohere, auth-gated gateways, …) that
      // doesn't serve a discovery catalog in the OpenAI shape.
      if (result.needsModelInput) {
        setShowModelInput(true)
      }
    }

    setSaving(false)
  }

  return (
    <div className="grid gap-4">
      {canGoBack ? (
        <Button className="-mt-1 self-start font-medium" onClick={onBack} size="xs" type="button" variant="text">
          <ChevronLeft className="size-3" />
          {t.onboarding.backToSignIn}
        </Button>
      ) : null}

      <div className="grid max-h-[42dvh] gap-2 overflow-y-auto p-1 sm:grid-cols-2">
        {options.map(o => (
          <button
            className={cn(
              'rounded-2xl border bg-background/60 p-3 text-left transition hover:bg-accent/50',
              option.envKey === o.envKey ? 'border-primary ring-2 ring-primary/20' : 'border-transparent'
            )}
            key={o.envKey}
            onClick={() => pick(o)}
            type="button"
          >
            <div className="flex items-center justify-between gap-2">
              <span className="text-sm font-medium">{o.name}</span>
              {isSet?.(o.envKey) ? <Check className="size-3.5 text-muted-foreground" /> : null}
            </div>
            {(t.onboarding.apiKeyOptions[o.id]?.short ?? o.short) ? (
              <p className="mt-1 text-xs text-muted-foreground">{t.onboarding.apiKeyOptions[o.id]?.short ?? o.short}</p>
            ) : null}
          </button>
        ))}
      </div>

      <div className="grid scroll-mt-4 gap-2" ref={entryRef}>
        <div className="flex items-center justify-between gap-3">
          <p className="text-sm leading-6 text-muted-foreground">{optionDescription}</p>
          {option.docsUrl ? <DocsLink href={option.docsUrl}>{t.onboarding.getKey}</DocsLink> : null}
        </div>
        <Input
          autoComplete="off"
          autoFocus
          className="font-mono"
          onChange={e => setValue(e.target.value)}
          onKeyDown={e => isSubmitEnter(e) && void submit()}
          placeholder={
            currentRedacted ??
            (alreadySet ? t.onboarding.replaceCurrent : option.placeholder || t.onboarding.pasteApiKey)
          }
          type={isLocal ? 'text' : 'password'}
          value={value}
        />
        {isLocal ? (
          <Input
            autoComplete="off"
            className="font-mono"
            onChange={e => setLocalKey(e.target.value)}
            onKeyDown={e => isSubmitEnter(e) && void submit()}
            placeholder={t.onboarding.localApiKeyPlaceholder}
            type="password"
            value={localKey}
          />
        ) : null}
        {isLocal && showModelInput ? (
          <Input
            autoComplete="off"
            autoFocus
            className="font-mono"
            onChange={e => setModelName(e.target.value)}
            onKeyDown={e => isSubmitEnter(e) && void submit()}
            placeholder={t.onboarding.localModelNamePlaceholder}
            value={modelName}
          />
        ) : null}
        {error ? <p className="text-xs text-destructive">{error}</p> : null}
      </div>

      <div className="flex items-center justify-between gap-3">
        <div>
          {alreadySet && onClear ? (
            <Button onClick={() => onClear(option.envKey)} size="sm" variant="ghost">
              {t.common.remove}
            </Button>
          ) : null}
        </div>
        <Button disabled={!canSave || saving} onClick={() => void submit()}>
          {saving ? <Loader2 className="animate-spin" /> : <KeyRound />}
          {saving ? t.onboarding.connecting : alreadySet ? t.onboarding.update : t.common.connect}
        </Button>
      </div>
    </div>
  )
}