Skip to content

The agent that grows with you

54.9 KB
Raw Blame
import type { ModelOptionProvider } from '@hermes/shared'
import { atom } from 'nanostores'

import { invalidateAllConnectors } from '@/app/capabilities/connectors/data/keys'
import {
  cancelOAuthSession,
  getGlobalModelOptions,
  getRecommendedDefaultModel,
  listOAuthProviders,
  OAUTH_LONG_POLL_SECONDS,
  pollOAuthSession,
  type ProfileScope,
  setEnvVar,
  startOAuthLogin,
  submitOAuthCode,
  validateProviderCredential
} from '@/hermes'
import { translateNow } from '@/i18n'
import { writeClipboardText } from '@/lib/clipboard'
import { restOfLongPollGap } from '@/lib/long-poll'
import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'
import { evaluateRuntimeReadiness, type RuntimeReadinessResult } from '@/lib/runtime-readiness'
import { readKey, writeKey } from '@/lib/storage'
import {
  $freeTierStatus,
  ackFreeTierNotice,
  freeTierReadyPending,
  refreshFreeTierStatus,
  setFreeTierRoute
} from '@/store/free-tier'
import { followHandoff, handoffStillMoving } from '@/store/free-tier-sign-in'
import { $gatewayBootGeneration } from '@/store/live-sync'
import { $localModelsEnabled } from '@/store/local-models-flag'
import { setMainModelAssignment } from '@/store/model-assignment'
import { dismissNotification, notify, notifyError } from '@/store/notifications'
import { afterOnboardingSurfaceClear, onboardingSurfaceOpen } from '@/store/onboarding-presence'
import { captureOnboardingScope, type OnboardingScope } from '@/store/onboarding-scope'
import { requestRoute } from '@/store/recovery-requests'
import { setModelPickerOpen } from '@/store/session'
import type { AppHandoffStatus, OAuthPollResponse, OAuthProvider, OAuthStartResponse } from '@/types/hermes'

type PkceStart = Extract<OAuthStartResponse, { flow: 'pkce' }>
type DeviceStart = Extract<OAuthStartResponse, { flow: 'device_code' }>

export type OnboardingMode = 'apikey' | 'oauth'

export interface OnboardingSignedIn {
  email: null | string
  handoff: AppHandoffStatus | null
}

function signedInFrom(result: OAuthPollResponse): OnboardingSignedIn | undefined {
  const email = result.account_email ?? null
  const handoff = result.handoff_status ?? null

  return email || handoff ? { email, handoff } : undefined
}

export type OnboardingFlow =
  | { status: 'idle' }
  | { provider: OAuthProvider; status: 'starting' }
  | { code: string; provider: OAuthProvider; start: PkceStart; status: 'awaiting_user' }
  | { copied: boolean; provider: OAuthProvider; start: DeviceStart; status: 'polling' }
  | { provider: OAuthProvider; start: OAuthStartResponse; status: 'submitting' }
  | { copied: boolean; provider: OAuthProvider; status: 'external_pending' }
  | { provider: OAuthProvider; status: 'success' }
  | {
      // After successful credential acquisition, before completing
      // onboarding: show the user which model they're getting and let
      // them change it. providerSlug is the model.options slug for the
      // just-authenticated provider (used to persist the chosen model
      // via /api/model/set). The change-model UI uses the existing
      // ModelPickerDialog, which fetches its own model list from
      // /api/model/options — no need to cache the list here.
      currentModel: string
      label: string
      providerSlug: string
      saving: boolean
      // A Nous sign-in's account and what the free tier's apps did, shown on the screen it happened on.
      signedIn?: OnboardingSignedIn
      status: 'confirming_model'
    }
  | { detail?: string; message: string; provider?: OAuthProvider; start?: OAuthStartResponse; status: 'error' }

export interface DesktopOnboardingState {
  /** null until the first runtime check resolves. Seeded from localStorage so
   *  returning users skip the boot overlay entirely instead of flashing it
   *  every reload. */
  configured: boolean | null
  flow: OnboardingFlow
  mode: OnboardingMode
  providers: null | OAuthProvider[]
  reason: null | string
  requested: boolean
  /** True when the user explicitly chose "I'll choose a provider later" on the
   *  first-run picker. Persisted to localStorage so the blocking overlay never
   *  re-nags on subsequent launches — the user can connect a provider any time
   *  from Settings → Providers (or the model picker's "Add provider"). Distinct
   *  from `configured`: the app still has no usable provider, so chat won't work
   *  until one is connected; we just stop forcing the choice up front. */
  firstRunSkipped: boolean
  /** True when the user explicitly opened the provider selector to add /
   *  switch providers from an already-configured app (e.g. via the model
   *  picker's "Add provider" button). Forces the overlay to show the picker
   *  even when configured === true, and adds a close affordance. */
  manual: boolean
  targetScope?: OnboardingScope
  /** True when the overlay was opened specifically to configure a local /
   *  custom OpenAI-compatible endpoint (e.g. from Settings → Model's "Set up
   *  custom endpoint"). Forces the API-key form with the local option
   *  preselected instead of the OAuth picker. */
  localEndpoint: boolean
  /** True when the backend still owes this user the one-time free-tier
   *  introduction AND the free tier is what carries inference. It makes the
   *  overlay show its "Hermes is ready" screen once even though the app is
   *  configured. The backend's `notice_pending` flag is the only source of
   *  truth — there is no renderer latch — so an ack clears it everywhere. */
  freeTierReady: boolean
}

export interface OnboardingContext {
  onCompleted?: () => void
  profile?: string
  scope?: OnboardingScope
  requestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>
}

const CONFIGURED_CACHE_KEY = 'hermes-desktop-onboarded-v1'
const SKIP_CACHE_KEY = 'hermes-onboarding-skipped-v1'
const COPY_FLASH_MS = 1500
export const DEFAULT_ONBOARDING_REASON = 'No inference provider is configured.'
export const DEFAULT_MANUAL_ONBOARDING_REASON = 'Add or switch inference provider.'

function readCachedConfigured(): boolean | null {
  if (typeof window === 'undefined') {
    return null
  }

  try {
    return window.localStorage.getItem(CONFIGURED_CACHE_KEY) === '1' ? true : null
  } catch {
    return null
  }
}

function writeCachedConfigured(value: boolean) {
  if (typeof window === 'undefined') {
    return
  }

  try {
    if (value) {
      window.localStorage.setItem(CONFIGURED_CACHE_KEY, '1')
    } else {
      window.localStorage.removeItem(CONFIGURED_CACHE_KEY)
    }
  } catch {
    // localStorage unavailable — degrade silently.
  }
}

// Through the storage choke point: the skip is a machine-level preference,
// so every browser and origin of this machine honours it (#145600).
function readCachedSkipped(): boolean {
  return typeof window !== 'undefined' && readKey(SKIP_CACHE_KEY) === '1'
}

function writeCachedSkipped(value: boolean) {
  if (typeof window !== 'undefined') {
    writeKey(SKIP_CACHE_KEY, value ? '1' : null)
  }
}

const INITIAL: DesktopOnboardingState = {
  configured: readCachedConfigured(),
  flow: { status: 'idle' },
  mode: 'oauth',
  providers: null,
  reason: null,
  requested: false,
  firstRunSkipped: readCachedSkipped(),
  manual: false,
  localEndpoint: false,
  freeTierReady: false
}

export const $desktopOnboarding = atom<DesktopOnboardingState>(INITIAL)

let flowGeneration = 0
let flowScope: OnboardingScope | undefined
let providersRefreshPromise: null | Promise<void> = null

const errMessage = (e: unknown) => (e instanceof Error ? e.message : String(e))

function captureContext(ctx: OnboardingContext): OnboardingContext & { scope: OnboardingScope } {
  return { ...ctx, scope: captureOnboardingScope(ctx.scope ?? ctx.profile) }
}

// One plain sentence for every way a provider sign-in can fail (start, poll,
// code exchange); the raw error text rides along as `detail` (desktop-09).
function signInDidNotFinish(provider: OAuthProvider, raw: unknown): { message: string; detail?: string } {
  const detail = raw instanceof Error ? errMessage(raw) : typeof raw === 'string' ? raw.trim() : ''

  return { message: translateNow('onboarding.signInDidNotFinish', provider.name), detail: detail || undefined }
}

const patch = (update: Partial<DesktopOnboardingState>) =>
  $desktopOnboarding.set({ ...$desktopOnboarding.get(), ...update })

const setFlow = (flow: OnboardingFlow) => patch(flow.status === 'idle' ? { flow } : { flow, reason: null })

const sessionIdFor = (flow: OnboardingFlow) => ('start' in flow && flow.start ? flow.start.session_id : undefined)

// The poll loop itself ends with its flow (see `pollSession`); only the expiry floor is a timer.
function clearPoll() {
  clearPollExpiry()
}

let pollExpiryTimer: number | null = null

function clearPollExpiry() {
  if (pollExpiryTimer !== null) {
    window.clearTimeout(pollExpiryTimer)
    pollExpiryTimer = null
  }
}

/** Lapse a device-code session locally when its window expires, instead of
 * polling a dead session forever. Uses the flow's own `expires_in`; the
 * backend poller may still flip the session to error first, and its message
 * (surfaced by `pollSession`) is preferred whenever it arrives in time. */
function schedulePollExpiry(start: DeviceStart, onExpire: () => void) {
  clearPollExpiry()
  const ttlMs = Math.max(1, Number(start.expires_in) || 0) * 1000
  pollExpiryTimer = window.setTimeout(() => {
    pollExpiryTimer = null
    onExpire()
  }, ttlMs)
}

async function checkRuntime(ctx: OnboardingContext, requestedProvider?: string): Promise<RuntimeReadinessResult> {
  return evaluateRuntimeReadiness(ctx.requestGateway, {
    defaultReason: DEFAULT_ONBOARDING_REASON,
    requestedProvider,
    unknownReady: false
  })
}

function shouldPreserveConfiguredOnFallback(runtime: RuntimeReadinessResult, state: DesktopOnboardingState): boolean {
  // Non-authoritative transport fallback only: NEITHER probe answered, so the
  // round carries no evidence either way and must never be written down as
  // "unconfigured". This used to require an in-memory `configured === true`,
  // which on a cold launch can only come from the onboarded cache — the very
  // cache an earlier fallback had already deleted. One readiness round that
  // lost the race to a cold/queued backend therefore re-armed the blocking
  // first-run picker on EVERY launch afterwards, on installs with a perfectly
  // good provider. `configured === null` (still unknown) now also holds: the
  // overlay keeps its "starting" header until a probe actually answers.
  return runtime.source === 'fallback' && state.configured !== false && !state.requested
}

// How long after the last boot-generation bump a runtime_check ok:false is
// treated as a boot race rather than a verdict. The backend announces
// `setup.ready` when its boot bootstrap finishes resolving the inference
// route; external secret sources (BWS-backed .env) hydrate a few seconds
// AFTER the port opens, so an answered ok:false inside this window names a
// hydration gap, not a missing credential (#124939). Sized to comfortably
// cover the observed ~2-5 s hydration while staying short enough that a real
// misconfiguration surfaces on the next ambient refresh.
const BOOT_RACE_GRACE_MS = 15_000

// Timestamp of the last `$gatewayBootGeneration` bump (setup.ready from the
// active source, or a gateway switch/wipe). Null until the first bump, so a
// steady-state session long after boot never treats an ok:false as a race.
let lastBootGenerationAt: number | null = null

$gatewayBootGeneration.listen(() => {
  lastBootGenerationAt = Date.now()
})

/** Test/dev seam: forget any witnessed boot, so the next round is judged as
 *  steady-state. Mirrors how a real session far from boot behaves. */
export function resetBootRaceWindowForTests(): void {
  lastBootGenerationAt = null
}

function isInsideBootRaceWindow(): boolean {
  return lastBootGenerationAt !== null && Date.now() - lastBootGenerationAt < BOOT_RACE_GRACE_MS
}

function shouldPreserveConfiguredOnBootRace(runtime: RuntimeReadinessResult, state: DesktopOnboardingState): boolean {
  // The probes ANSWERED this time, but the round ran inside the backend's boot
  // window: the runtime_check resolved a route whose external secret source
  // (BWS) had not hydrated yet and reported ok:false for it. That is a
  // retryable not-ready, not an auth verdict — downgrading configured:false
  // here was the flash of "No usable credentials found for openrouter" on
  // every update restart of a fully configured install (#124939). The state
  // must already be configured (verified earlier or the durable cache) so a
  // genuinely unconfigured install still enters onboarding on boot.
  return (
    runtime.source === 'runtime_check' &&
    !runtime.ready &&
    state.configured === true &&
    !state.requested &&
    isInsideBootRaceWindow()
  )
}

// The selected model is the managed local runtime and its server is down (Desktop closed and took
// its server with it, still loading, or switched off). The provider IS set up, and provider sign-in
// cannot start a local server, so this never opens onboarding: the app stays usable, the status bar
// reads "inference unavailable", and a notice names the cause with the way forward.
const LOCAL_RUNTIME_UNAVAILABLE = 'local_runtime_unavailable'
const LOCAL_MODELS_ROUTE = '/settings?tab=providers&pview=local'

const LOCAL_RUNTIME_NOTICE_ID = 'local-runtime-unavailable'

function isLocalRuntimeDown(runtime: RuntimeReadinessResult, state: DesktopOnboardingState): boolean {
  return runtime.source === 'runtime_check' && runtime.errorCode === LOCAL_RUNTIME_UNAVAILABLE && !state.requested
}

/** True while the verdict is "the local model server is down": a server that is starting or being
 *  switched back on announces nothing to this window, so the readiness tracker keeps re-checking. */
export function isLocalRuntimeUnavailable(runtime: RuntimeReadinessResult | null): boolean {
  return runtime?.ready === false && runtime.errorCode === LOCAL_RUNTIME_UNAVAILABLE
}

/** Readiness answered ready: the server came up, so the notice raised while it was down goes. The
 *  onboarding exemption means no onboarding round runs on recovery to clear it there. */
export function settleLocalRuntimeNotice(runtime: RuntimeReadinessResult) {
  if (runtime.ready) {
    dismissNotification(LOCAL_RUNTIME_NOTICE_ID)
  }
}

// The Webapp has no Local models pane (the flag is Electron-only), so there the way forward it can
// offer is another model, and the sentence must not send the user to a pane they cannot open.
const WEBAPP_LOCAL_RUNTIME_DOWN =
  "The local model server isn't serving. Start it from the Hermes desktop app or `hermes model` in a terminal, or choose another model."

// Desktop has the pane, so its notice names it next to the button that opens it.
const DESKTOP_LOCAL_RUNTIME_DOWN =
  "The local model server isn't serving. It may still be starting, or it was turned off: check Settings → Providers → Local models, or choose another model."

function keepConfiguredWithLocalRuntimeDown(reason: string) {
  const pane = $localModelsEnabled.get()

  writeCachedConfigured(true)
  patch({ configured: true, reason })
  notify({
    action: pane
      ? { label: 'Open Local models', onClick: () => requestRoute(LOCAL_MODELS_ROUTE) }
      : { label: 'Choose another model', onClick: () => setModelPickerOpen(true) },
    id: LOCAL_RUNTIME_NOTICE_ID,
    kind: 'warning',
    message: pane ? DESKTOP_LOCAL_RUNTIME_DOWN : WEBAPP_LOCAL_RUNTIME_DOWN,
    title: 'Local model unavailable'
  })
}

function notifyReady(provider: string) {
  notify({ kind: 'success', title: 'Hermes is ready', message: `${provider} connected.` })
}

// Human-friendly labels for tools auto-routed through the Nous Tool Gateway,
// mirroring hermes_cli/nous_subscription._GATEWAY_TOOL_LABELS so the GUI and
// CLI describe the same thing.
const GATEWAY_TOOL_LABELS: Record<string, string> = {
  browser: 'browser automation',
  image_gen: 'image generation',
  tts: 'text-to-speech',
  video_gen: 'video generation',
  web: 'web search & extract'
}

// When switching to Nous auto-routes unconfigured tools through the Tool
// Gateway, tell the user which ones — same information the CLI prints. Silent
// when nothing changed (subscriber already configured, has own keys, etc.).
function notifyGatewayTools(tools: string[] | undefined) {
  if (!tools || tools.length === 0) {
    return
  }

  const labels = tools.map(t => GATEWAY_TOOL_LABELS[t] ?? t)
  const list = labels.length === 1 ? labels[0] : `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`

  notify({
    durationMs: 8000,
    kind: 'info',
    message: `${list} now run through your Nous subscription — no separate API keys needed.`,
    title: 'Tool Gateway enabled'
  })
}

// After credentials are persisted, ask the backend which provider+models
// are now authenticated. Pick the first curated model for the matching
// provider as a sensible default, persist it via /api/model/set, and
// transition to the model-confirmation step. If anything goes wrong
// fetching options (no providers returned, network error), the caller
// falls through to completing onboarding without showing the confirm
// card — the user gets the undefined-model auto-selection behaviour
// we had before, which works but is surprising. The confirm step is
// opportunistic polish, not a hard requirement for onboarding.
async function fetchProviderDefaultModel(
  preferredSlugs: string[],
  profile?: ProfileScope
): Promise<null | { providerSlug: string; defaultModel: string }> {
  let options

  try {
    options = await getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false }, profile)
  } catch {
    return null
  }

  const providers = options?.providers ?? []

  if (providers.length === 0) {
    return null
  }

  // Try each preferred slug (lowercased), fall back to the first provider
  // returned (model.options orders by recency / authenticated state, so
  // the just-authenticated provider is usually first anyway).
  const lower = preferredSlugs.map(s => s.toLowerCase())

  const matched =
    providers.find((p: ModelOptionProvider) => lower.includes(String(p.slug).toLowerCase())) ?? providers[0]

  const models = matched.models ?? []

  if (models.length === 0) {
    return null
  }

  // Re-login to the provider already in use (expired OAuth grant): keep the
  // model the user was on. Swapping in the provider's recommended default
  // would silently change what they're chatting with.
  const currentModel = String(options?.model ?? '')

  if (
    currentModel &&
    String(options?.provider ?? '').toLowerCase() === String(matched.slug).toLowerCase() &&
    models.map(String).includes(currentModel)
  ) {
    return { providerSlug: String(matched.slug), defaultModel: currentModel }
  }

  // Prefer the backend's recommended default — it mirrors the curation
  // `hermes model` does (for Nous it honors the user's free/paid tier, so a
  // free user gets a free model rather than a paid default like opus). Fall
  // back to the first curated model if the endpoint can't resolve one.
  let defaultModel = String(models[0])

  try {
    const recommended = await getRecommendedDefaultModel(String(matched.slug), profile)

    if (recommended.model && models.map(String).includes(recommended.model)) {
      defaultModel = recommended.model
    } else if (recommended.model) {
      // Recommended model isn't in the curated options list (e.g. a Portal
      // free-recommendation the picker list didn't include); trust it anyway.
      defaultModel = recommended.model
    }
  } catch {
    // Endpoint unavailable — keep models[0]. Non-fatal: the confirm card still
    // shows and the user can change it.
  }

  return {
    providerSlug: String(matched.slug),
    defaultModel
  }
}

// After OAuth/API-key success: reload the backend env, verify runtime,
// then either show the model-confirm step or fall straight through to
// completion if we can't determine a default.
//
// onFail receives the runtime-readiness `reason` from checkRuntime so
// the caller can fold it into a user-facing error — same contract as
// reloadAndConnect used to have (which this replaces).
async function completeWithModelConfirm(
  ctx: OnboardingContext,
  providerLabel: string,
  preferredSlugs: string[],
  onFail: (reason: null | string) => void,
  // When true, a failing runtime check no longer blocks progression — the
  // user is allowed through onboarding regardless. Used by the API-key path,
  // where we intentionally don't validate the key (it blocked too many users).
  ignoreRuntimeGate = false,
  signedIn?: OnboardingSignedIn
) {
  const generation = flowGeneration

  // Scoped readiness reads fresh credentials; reload.env only mutates the
  // launch process environment and cannot reload another profile safely.
  if (!ctx.scope?.profile) {
    await ctx.requestGateway('reload.env').catch(() => undefined)
  }

  // A sign-in can change the account the apps ride on.
  invalidateAllConnectors()

  if (generation !== flowGeneration) {
    return
  }

  const defaults = await fetchProviderDefaultModel(preferredSlugs, ctx.scope)

  if (generation !== flowGeneration) {
    return
  }

  // Manual connect (Settings / model picker "Add provider" on an already-
  // configured install): the global default must NOT change until the user
  // explicitly confirms a model on the confirm card. checkRuntime below
  // already passes preferredSlugs[0] as requestedProvider, so the runtime
  // gate can validate the just-connected provider without persisting first.
  // confirmOnboardingModel persists on Begin instead.
  const manual = $desktopOnboarding.get().manual

  if (defaults && !manual) {
    // First-run only: persist the chosen provider/model before the runtime
    // gate so a stale config provider (e.g. anthropic from a prior failed
    // setup) cannot make setup.runtime_check validate the wrong backend
    // after a fresh OAuth login. There's no prior default to protect here.
    try {
      const res = await setMainModelAssignment(
        {
          provider: defaults.providerSlug,
          model: defaults.defaultModel
        },
        ctx.scope,
        // Headless automated flow: nothing is mounted to click a guard
        // prompt, so fail with the message instead of hanging.
        { skipConfirmPrompt: true }
      )

      if (generation !== flowGeneration) {
        return
      }

      notifyGatewayTools(res.gateway_tools)
    } catch (error) {
      if (generation !== flowGeneration) {
        return
      }

      onFail(error instanceof Error ? error.message : 'Hermes could not save the selected model.')

      return
    }
  }

  const runtime = await checkRuntime(ctx, preferredSlugs[0])

  if (generation !== flowGeneration) {
    return
  }

  if (!runtime.ready && !ignoreRuntimeGate) {
    onFail(runtime.reason)

    return
  }

  if (!defaults) {
    // Couldn't get a sensible default — proceed without confirm step.
    notifyReady(providerLabel)
    completeDesktopOnboarding(true)
    ctx.onCompleted?.()

    return
  }

  setFlow({
    status: 'confirming_model',
    providerSlug: defaults.providerSlug,
    currentModel: defaults.defaultModel,
    label: providerLabel,
    saving: false,
    signedIn
  })

  void followSignedInMove(signedIn, generation, ctx.scope)
}

// Keep the confirm screen's line about the moving apps current until the move settles or the screen goes.
async function followSignedInMove(signedIn: OnboardingSignedIn | undefined, generation: number, scope?: ProfileScope) {
  const moving = signedIn?.handoff

  if (!signedIn || !moving || !handoffStillMoving(moving)) {
    return
  }

  const shown = () => {
    const { flow } = $desktopOnboarding.get()

    return generation === flowGeneration && flow.status === 'confirming_model' ? flow : null
  }

  const publish = (handoff: AppHandoffStatus) => {
    const flow = shown()

    if (flow) {
      setFlow({ ...flow, signedIn: { email: signedIn.email, handoff } })
    }
  }

  await followHandoff(moving, () => shown() !== null, publish, scope)
}

function providerResolutionFailure(reason: null | string) {
  const detail = reason?.trim()

  return detail
    ? `Connected, but Hermes still cannot resolve a usable provider. ${detail}`
    : 'Connected, but Hermes still cannot resolve a usable provider.'
}

/** Re-read the OAuth provider list into the onboarding cache. Exported so a
 *  flow that changes a provider's auth state outside onboarding (a free-tier
 *  sign-in) can keep the cached rows honest instead of leaving the picker
 *  describing the previous identity. */
export async function refreshOnboardingProviders() {
  await refreshProviders()
}

async function refreshProviders() {
  if (providersRefreshPromise) {
    await providersRefreshPromise

    return
  }

  const generation = flowGeneration
  providersRefreshPromise = (async () => {
    try {
      const { providers } = await listOAuthProviders($desktopOnboarding.get().targetScope)

      if (generation !== flowGeneration) {
        return
      }

      patch({ mode: providers.length > 0 ? 'oauth' : 'apikey', providers })
    } catch {
      if (generation !== flowGeneration) {
        return
      }

      patch({ mode: 'apikey', providers: [] })
    } finally {
      if (generation === flowGeneration) {
        providersRefreshPromise = null
      }
    }
  })()

  await providersRefreshPromise
}

export function requestDesktopOnboarding(reason = DEFAULT_ONBOARDING_REASON) {
  // Not over first-run onboarding. The free account may still be in
  // the making, and a credential probe that fires meanwhile would drop the
  // provider picker over it; onboarding hands over to the picker
  // itself when the account fails.
  afterOnboardingSurfaceClear(() => patch({ reason: reason.trim() || DEFAULT_ONBOARDING_REASON, requested: true }))
}

/** Credential warning delivered passively (session create/activate/resume
 *  runtime info, stream heartbeats) — e.g. right after switching to a
 *  profile that has no provider configured. Popping the blocking onboarding
 *  overlay here punishes merely LOOKING at an unconfigured profile, so the
 *  warning is deferred instead: stashed until the user actually tries to
 *  chat, where the submit path consumes it and opens onboarding before the
 *  doomed send. The latest warning wins; a session event without a warning
 *  clears the stash (the profile became configured, or the user switched
 *  back to a healthy one). */
let pendingCredentialWarning: null | string = null

export function requestDesktopOnboardingForCredentialWarning(reason: null | string | undefined) {
  const warning = reason?.trim()

  // Stash while the due check is still undecided: submit consumes it later. Drop only under an open onboarding.
  if (!warning || !isProviderSetupErrorMessage(warning) || onboardingSurfaceOpen()) {
    pendingCredentialWarning = null

    return
  }

  pendingCredentialWarning = warning
}

/** Submit-time gate: returns the deferred credential warning (and clears it)
 *  so the caller can open onboarding instead of sending a prompt that the
 *  gateway already said will fail. Null when the active profile is healthy. */
export function consumePendingCredentialWarning(): null | string {
  const warning = pendingCredentialWarning

  pendingCredentialWarning = null

  return warning
}

// Open the onboarding provider selector on demand from an already-configured
// app — e.g. the model picker's "Add provider" button. Reuses the entire
// onboarding flow (OAuth rows, API-key form, model-confirm) instead of
// duplicating provider UI. Sets manual=true so the overlay shows the picker
// even though configured===true, and refreshes the provider list.
export function startManualOnboarding(
  reason: null | string = DEFAULT_MANUAL_ONBOARDING_REASON,
  profile?: ProfileScope
) {
  cancelOnboardingFlow()
  providersRefreshPromise = null
  patch({
    manual: true,
    targetScope: captureOnboardingScope(profile),
    providers: null,
    requested: true,
    localEndpoint: false,
    // The picker replaces the free-tier ready screen when the user asked for it.
    freeTierReady: false,
    // `null` opts out of the prompt banner entirely (e.g. when the user already
    // picked a specific provider and we auto-start its sign-in).
    reason: reason ? reason.trim() || DEFAULT_ONBOARDING_REASON : null,
    flow: { status: 'idle' }
  })
  void refreshProviders()
}

// Open the onboarding overlay directly on the local / custom endpoint form
// (URL + optional API key), bypassing the OAuth picker. Used by Settings →
// Model's "Set up custom endpoint" so it lands on a form that can actually
// configure the endpoint instead of dead-ending on the OAuth provider list
// (`custom` is not an OAuth provider, so the generic manual flow would just
// re-show the picker — the original "booted back to the first screen" loop).
export function startManualLocalEndpoint(reason: null | string = null, profile?: ProfileScope) {
  cancelOnboardingFlow()
  pendingProviderOAuthId = null
  patch({
    manual: true,
    targetScope: captureOnboardingScope(profile),
    providers: null,
    requested: true,
    localEndpoint: true,
    mode: 'apikey',
    reason: reason ? reason.trim() || DEFAULT_ONBOARDING_REASON : null,
    flow: { status: 'idle' }
  })
}

// One-shot hand-off used when the dedicated Providers settings page launches a
// specific provider's sign-in: we open the manual onboarding overlay AND
// remember which provider to start, so the overlay drives that exact OAuth
// flow instead of re-showing the picker the user just clicked through.
// Module-level (not store state) because it's consumed immediately on the next
// overlay render and never needs to persist or re-render anything itself.
let pendingProviderOAuthId: null | string = null

export function startManualProviderOAuth(providerId: string, profile?: ProfileScope) {
  pendingProviderOAuthId = providerId
  startManualOnboarding(null, profile)
}

// Read the pending provider id without clearing it. The overlay only clears it
// (via clearPendingProviderOAuth) once it has actually launched that provider,
// so a transient empty/failed provider fetch doesn't drop the hand-off and the
// deep-link can still auto-start after the list loads.
export function peekPendingProviderOAuth(): null | string {
  return pendingProviderOAuthId
}

export function clearPendingProviderOAuth() {
  pendingProviderOAuthId = null
}

// Dismiss a manually-opened provider selector without touching the existing
// (working) configuration. Only valid in the manual path — the unconfigured
// first-run flow has no close affordance because the app can't run yet.
export function closeManualOnboarding() {
  cancelOnboardingFlow()
  providersRefreshPromise = null
  pendingProviderOAuthId = null

  patch({
    targetScope: undefined,
    manual: false,
    requested: false,
    localEndpoint: false,
    freeTierReady: false,
    flow: { status: 'idle' }
  })
}

/** `connected` marks the completion paths where a provider sign-in / key save
 *  in THIS flow is what finished onboarding. Only those make an earlier
 *  "choose later" moot. A passive readiness round must leave the skip alone:
 *  clearing it there erased the user's explicit decision, so the next round
 *  that came back not-ready was free to raise the blocking picker again — the
 *  set/clear flip-flop behind "the setup screen returns on every launch". */
export function completeDesktopOnboarding(connected = false) {
  clearPoll()
  dismissNotification('runtime-not-ready')
  dismissNotification(LOCAL_RUNTIME_NOTICE_ID)
  writeCachedConfigured(true)

  if (connected) {
    writeCachedSkipped(false)
  }

  $desktopOnboarding.set({
    configured: true,
    flow: { status: 'idle' },
    mode: 'oauth',
    providers: null,
    reason: null,
    requested: false,
    firstRunSkipped: connected ? false : readCachedSkipped(),
    manual: false,
    localEndpoint: false,
    freeTierReady: false
  })
}

// "I'll choose a provider later" on the first-run picker. Persists the skip so
// the blocking overlay never re-nags on future launches, and dismisses it now
// so the user lands in the app. Chat won't work until a provider is connected
// (from Settings → Providers or the model picker's "Add provider") — this only
// stops forcing the choice up front. Distinct from completeDesktopOnboarding,
// which marks the app actually configured.
export function dismissFirstRunOnboarding() {
  clearPoll()
  writeCachedSkipped(true)
  patch({
    firstRunSkipped: true,
    requested: false,
    manual: false,
    localEndpoint: false,
    freeTierReady: false,
    flow: { status: 'idle' }
  })
}

export function setOnboardingMode(mode: OnboardingMode) {
  patch({ mode })
}

/**
 * `stillWanted`, when given, is re-asked after the readiness round: a background
 * caller (the `setup.ready` listener) passes it so a user action that started
 * during the round — opening the API-key form, picking a provider — is never
 * dismissed by a late "ready".
 */
export async function refreshOnboarding(ctx: OnboardingContext, stillWanted?: () => boolean) {
  // Manual mode (user opened the selector from a working app): never
  // auto-dismiss on runtime-ready — the whole point is to let them add /
  // switch a provider while already configured. Just ensure the provider
  // list is loaded and show the picker.
  if ($desktopOnboarding.get().manual) {
    await refreshProviders()

    return false
  }

  // A boot-race round (see shouldPreserveConfiguredOnBootRace) is recognized
  // from the module-level boot-generation clock, so there is nothing to
  // seed here — the round below just reads it.
  const runtime = await checkRuntime(ctx)

  if (stillWanted && !stillWanted()) {
    return false
  }

  if (runtime.ready) {
    completeDesktopOnboarding()
    await applyFreeTierIntro(ctx, runtime)
    ctx.onCompleted?.()

    return true
  }

  const state = $desktopOnboarding.get()

  if (shouldPreserveConfiguredOnFallback(runtime, state)) {
    // Gateway probes timed out — don't downgrade to the blocking onboarding
    // overlay or claim an error verdict. Only a previously VERIFIED install
    // losing its backend is worth telling the user about; an unknown state is
    // just a round that landed before the backend could answer, and a notice
    // on every cold launch would be noise. Use the temporary informational
    // notice with a stable id, so repeated calls during an outage dedup and
    // recovery clears it early.
    if (state.configured === true) {
      notify({
        id: 'runtime-not-ready',
        kind: 'info',
        title: 'Runtime not ready',
        message:
          'Hermes Desktop could not verify the running backend on startup. Some features may be unavailable until the gateway is reachable.'
      })
    }

    return false
  }

  const reason = runtime.reason || state.reason || DEFAULT_ONBOARDING_REASON

  if (isLocalRuntimeDown(runtime, state)) {
    keepConfiguredWithLocalRuntimeDown(reason)

    return false
  }

  if (shouldPreserveConfiguredOnBootRace(runtime, state)) {
    // The backend answered inside its boot window with a not-ready that is
    // explained by external secrets still hydrating (#124939). Do not write
    // the downgrade: the durable cache stays configured and the setup.ready
    // tick (or the next ambient refresh) re-checks once the route is real.
    return false
  }

  writeCachedConfigured(false)
  patch({ configured: false, reason })

  if (state.providers !== null && !state.requested) {
    return false
  }

  await refreshProviders()

  return false
}

/**
 * Ask the backend whether the one-time free-tier introduction is still owed,
 * and if so which shape it takes. Pull-based on purpose: the flag lives on the
 * identity, so a second window (or a reinstall against the same home) shows the
 * intro exactly once between them.
 *
 * The runtime check's route flag picks the shape. When the free tier is the
 * route inference runs on, the overlay stays up on a ready screen — this is
 * their first launch and they have nothing else. When a provider of their own
 * carries inference, the overlay is not warranted: the composer strip (keyed on
 * the same notice flag) offers the free models without interrupting.
 */
async function applyFreeTierIntro(ctx: OnboardingContext, runtime: RuntimeReadinessResult) {
  setFreeTierRoute(runtime.freeTier)
  await refreshFreeTierStatus(ctx.requestGateway)

  // The onboarding intro is the introduction: opening it acks the notice
  // (store/onboarding-run.ts). Read the status when the overlay is free, not
  // now, so that ack is honoured.
  afterOnboardingSurfaceClear(() => {
    if (freeTierReadyPending($freeTierStatus.get(), runtime.freeTier ?? null)) {
      patch({ freeTierReady: true })
    }
  })
}

/** "Begin" / "Sign in instead" / "Other providers" all consume the notice — the
 *  user has seen it. Returns whether the backend recorded it: on a failed write
 *  the ready screen stays up, because the flag it is keyed on is still pending. */
export async function ackFreeTierIntro(ctx: OnboardingContext): Promise<boolean> {
  return ackFreeTierNotice(ctx.requestGateway)
}

/** Take the ready screen down. Separate from the ack because the overlay plays
 *  its exit BEFORE unmounting — clearing the flag up front would cut the fade. */
export function clearFreeTierIntro() {
  patch({ freeTierReady: false })
}

// Open a sign-in URL via the desktop bridge, falling back to window.open
// when the bridge isn't present (e.g. the web dashboard / dev preview) so
// the flow never silently stalls in a waiting state. Mirrors the pattern in
// apps/desktop/src/app/artifacts/index.tsx.
async function openSignInUrl(url: string) {
  if (window.hermesDesktop?.openExternal) {
    try {
      await window.hermesDesktop.openExternal(url)

      return
    } catch {
      // Bridge present but failed (no OS handler, user denied, etc.). Fall
      // through to window.open so the sign-in URL still opens and the flow
      // doesn't strand a pending OAuth session in a waiting state.
    }
  }

  window.open(url, '_blank', 'noopener,noreferrer')
}

export async function startProviderOAuth(provider: OAuthProvider, ctx: OnboardingContext) {
  ctx = captureContext(ctx)
  const generation = flowGeneration
  flowScope = ctx.scope
  clearPoll()

  if (provider.flow === 'external') {
    setFlow({ status: 'external_pending', provider, copied: false })

    return
  }

  setFlow({ status: 'starting', provider })

  try {
    const start = await startOAuthLogin(provider.id, ctx.scope)

    if (generation !== flowGeneration) {
      void cancelOAuthSession(start.session_id, ctx.scope).catch(() => undefined)

      return
    }

    const browserUrl = start.flow === 'device_code' ? start.verification_url : start.auth_url
    await openSignInUrl(browserUrl)

    if (generation !== flowGeneration) {
      void cancelOAuthSession(start.session_id, ctx.scope).catch(() => undefined)

      return
    }

    if (start.flow === 'pkce') {
      setFlow({ status: 'awaiting_user', provider, start, code: '' })

      return
    }

    setFlow({ status: 'polling', provider, start, copied: false })
    schedulePollExpiry(start, () =>
      setFlow({
        status: 'error',
        provider,
        start,
        message: translateNow('onboarding.signInExpired')
      })
    )
    void pollSession(provider, start, ctx, generation)
  } catch (error) {
    if (generation !== flowGeneration) {
      return
    }

    setFlow({ status: 'error', provider, ...signInDidNotFinish(provider, error) })
  }
}

// Long-poll a session-backed device-code flow until it resolves. The loop ends with its flow: a
// cancel, a newer flow, or the local expiry floor all move the flow off this session's `polling`.
async function pollSession(provider: OAuthProvider, start: DeviceStart, ctx: OnboardingContext, generation: number) {
  const live = () => {
    const { flow } = $desktopOnboarding.get()

    return generation === flowGeneration && flow.status === 'polling' && sessionIdFor(flow) === start.session_id
  }

  try {
    for (;;) {
      const askedAt = Date.now()
      const result = await pollOAuthSession(provider.id, start.session_id, ctx.scope, OAUTH_LONG_POLL_SECONDS)

      if (!live()) {
        return
      }

      if (result.status === 'approved') {
        clearPoll()
        setFlow({ status: 'success', provider })
        await completeWithModelConfirm(
          ctx,
          provider.name,
          [provider.id],
          reason => setFlow({ status: 'error', provider, message: providerResolutionFailure(reason) }),
          false,
          signedInFrom(result)
        )

        return
      }

      if (result.status !== 'pending') {
        clearPoll()
        setFlow({
          status: 'error',
          provider,
          start,
          ...signInDidNotFinish(provider, result.error_message || result.status)
        })

        return
      }

      await restOfLongPollGap(askedAt)

      if (!live()) {
        return
      }
    }
  } catch (error) {
    if (!live()) {
      return
    }

    clearPoll()
    setFlow({ status: 'error', provider, start, ...signInDidNotFinish(provider, error) })
  }
}

export function setOnboardingCode(code: string) {
  const { flow } = $desktopOnboarding.get()

  if (flow.status === 'awaiting_user') {
    setFlow({ ...flow, code })
  }
}

export async function submitOnboardingCode(ctx: OnboardingContext) {
  ctx = captureContext(ctx)
  const generation = flowGeneration
  flowScope = ctx.scope
  const { flow } = $desktopOnboarding.get()

  if (flow.status !== 'awaiting_user' || !flow.code.trim()) {
    return
  }

  const { provider, start, code } = flow
  setFlow({ status: 'submitting', provider, start })

  try {
    const resp = await submitOAuthCode(provider.id, start.session_id, code.trim(), ctx.scope)

    if (generation !== flowGeneration) {
      return
    }

    if (resp.ok && resp.status === 'approved') {
      setFlow({ status: 'success', provider })
      await completeWithModelConfirm(ctx, provider.name, [provider.id], reason =>
        setFlow({
          status: 'error',
          provider,
          message: providerResolutionFailure(reason)
        })
      )
    } else {
      setFlow({ status: 'error', provider, start, ...signInDidNotFinish(provider, resp.message) })
    }
  } catch (error) {
    if (generation !== flowGeneration) {
      return
    }

    setFlow({ status: 'error', provider, start, ...signInDidNotFinish(provider, error) })
  }
}

export function cancelOnboardingFlow() {
  flowGeneration++
  clearPoll()
  const sessionId = sessionIdFor($desktopOnboarding.get().flow)

  if (sessionId) {
    cancelOAuthSession(sessionId, flowScope ?? $desktopOnboarding.get().targetScope).catch(() => undefined)
  }

  flowScope = undefined
  setFlow({ status: 'idle' })
}

async function copyAndFlash(text: string, predicate: (flow: OnboardingFlow) => boolean) {
  try {
    await writeClipboardText(text)
  } catch {
    return
  }

  const { flow } = $desktopOnboarding.get()

  if (!predicate(flow) || !('copied' in flow)) {
    return
  }

  setFlow({ ...flow, copied: true })
  window.setTimeout(() => {
    const current = $desktopOnboarding.get().flow

    if (predicate(current) && 'copied' in current) {
      setFlow({ ...current, copied: false })
    }
  }, COPY_FLASH_MS)
}

export async function copyDeviceCode() {
  const { flow } = $desktopOnboarding.get()

  if (flow.status !== 'polling') {
    return
  }

  const sid = flow.start.session_id
  await copyAndFlash(flow.start.user_code, f => f.status === 'polling' && f.start.session_id === sid)
}

export async function copyExternalCommand() {
  const { flow } = $desktopOnboarding.get()

  if (flow.status !== 'external_pending') {
    return
  }

  const id = flow.provider.id
  await copyAndFlash(flow.provider.cli_command, f => f.status === 'external_pending' && f.provider.id === id)
}

export async function recheckExternalSignin(ctx: OnboardingContext) {
  ctx = captureContext(ctx)
  flowScope = ctx.scope
  const { flow } = $desktopOnboarding.get()

  if (flow.status !== 'external_pending') {
    return
  }

  const { provider } = flow
  await completeWithModelConfirm(ctx, provider.name, [provider.id], reason =>
    setFlow({
      status: 'error',
      provider,
      message:
        reason?.trim() ||
        `Hermes still cannot reach ${provider.name}. Run \`${provider.cli_command}\` in a terminal first.`
    })
  )
}

export async function saveOnboardingApiKey(
  envKey: string,
  value: string,
  label: string,
  ctx: OnboardingContext,
  // Optional endpoint key — only meaningful for the "Local / custom endpoint"
  // option, whose primary `value` is the base URL. Ignored for plain API-key
  // providers (their key IS `value`).
  endpointApiKey?: string,
  // Optional manual model name — only meaningful for the "Local / custom
  // endpoint" option when /v1/models discovery returns an empty list (e.g.
  // Cohere's OpenAI-compatible endpoint, which serves no OpenAI-shaped model
  // catalog). Mirrors the runtime's `discover_models: false` + explicit
  // `models:` config path. Ignored for plain API-key providers.
  modelName?: string
) {
  ctx = captureContext(ctx)
  const generation = flowGeneration
  flowScope = ctx.scope
  const trimmed = value.trim()

  if (!trimmed) {
    return { ok: false, message: 'Enter a value first.' }
  }

  // The "Local / custom endpoint" option carries a base URL (in `value`) plus
  // an optional API key. It must be wired into config (provider=custom +
  // base_url + model + api_key), not dropped into .env — runtime resolution
  // ignores OPENAI_BASE_URL.
  if (envKey === 'OPENAI_BASE_URL') {
    return saveOnboardingLocalEndpoint(trimmed, endpointApiKey?.trim() ?? '', ctx, modelName)
  }

  // No key validation here on purpose: we previously live-probed the key and
  // hard-blocked on a runtime check after saving, which rejected too many
  // legitimate users (corporate proxies, regional blocks, flaky/rate-limited
  // provider probes, self-hosted endpoints). We now save the value as-is and
  // let the user proceed; an actually-bad key surfaces later at chat time.
  try {
    await setEnvVar(envKey, trimmed, ctx.scope, { providerSetup: true })

    if (generation !== flowGeneration) {
      return { ok: false }
    }

    // For API-key flows we don't have a definitive provider id (the
    // user picked which API key they're entering, but the corresponding
    // backend slug — e.g. OPENROUTER_API_KEY → "openrouter" — is the
    // env-key prefix stripped). Pass a couple of likely candidates;
    // fetchProviderDefaultModel falls back to the first authenticated
    // provider returned by /api/model/options if none match.
    const slugCandidates = [envKey.replace(/_API_KEY$/, '').toLowerCase(), label.toLowerCase()]
    // ignoreRuntimeGate=true: never block onboarding on the runtime check.
    await completeWithModelConfirm(ctx, label, slugCandidates, () => undefined, true)

    return { ok: true }
  } catch (error) {
    notifyError(error, `Could not save ${label}`)

    return { ok: false, message: errMessage(error) }
  }
}

// Configure a local / self-hosted OpenAI-compatible endpoint (vLLM, llama.cpp,
// Ollama, …). Unlike API-key providers, a local endpoint is defined by its URL
// and usually needs NO key. The runtime resolver reads model.base_url from
// config (it ignores the OPENAI_BASE_URL env var), so we persist
// provider=custom + base_url + model via /api/model/set rather than dropping an
// env var that resolution never consults.
//
// The model is auto-discovered from the endpoint's /v1/models (surfaced by the
// validate probe). The optional API key is forwarded to the probe (so hosted
// endpoints that gate /v1/models behind auth still enumerate models) and
// persisted to model.api_key so the runtime can authenticate.
//
// If discovery returns no models — common for OpenAI-compatible SaaS that
// doesn't expose a /v1/models catalog in the OpenAI shape (Cohere's
// compatibility endpoint, auth-gated gateways, etc.) — we return
// `{ ok: false, needsModelInput: true, message }` so the wizard can reveal a
// manual model-name input. The runtime already supports this case via
// `discover_models: false` + an explicit `models:` list; the wizard was the
// only layer still hard-failing. A non-empty `modelName` argument is used
// verbatim instead of the discovered list.
//
// We deliberately don't route through completeWithModelConfirm: that path
// re-assigns the model from /api/model/options WITHOUT a base_url, which would
// wipe the base_url we just wrote. We have a concrete model already, so we
// verify the runtime directly and finish.
export async function saveOnboardingLocalEndpoint(
  baseUrl: string,
  apiKey: string,
  ctx: OnboardingContext,
  // Manual model name from the wizard. When non-empty it is persisted verbatim
  // — the same semantics as `discover_models: false` + an explicit `models:`
  // list in config.yaml.
  modelName?: string
) {
  ctx = captureContext(ctx)
  const generation = flowGeneration
  flowScope = ctx.scope
  const url = baseUrl.trim()
  const key = apiKey.trim()
  const manualModel = modelName?.trim() ?? ''

  if (!url) {
    return { ok: false, message: 'Enter the endpoint URL first.' }
  }

  // Probe connectivity + discover the served models. Any HTTP response proves
  // the endpoint is up; an unreachable probe hard-blocks because we can't
  // resolve a model to route to.
  let model = ''
  // The probe tries the URL as entered and its /v1 variant; persist the one that answered —
  // the runtime POSTs {base_url}/chat/completions verbatim, so a bare host root that only
  // "detected" via /v1/models would 404 every chat (#65488).
  let resolvedUrl = url

  try {
    const probe = await validateProviderCredential('OPENAI_BASE_URL', url, key, ctx.scope)

    if (generation !== flowGeneration) {
      return { ok: false }
    }

    if (!probe.ok && probe.reachable) {
      return { ok: false, message: probe.message || 'Could not reach that endpoint.' }
    }

    if (!probe.reachable) {
      return { ok: false, message: probe.message || `Could not reach ${url}.` }
    }

    model = (probe.models?.[0] ?? '').trim()
    resolvedUrl = probe.resolved_base_url?.trim() || url
  } catch {
    return { ok: false, message: `Could not reach ${url}.` }
  }

  // Prefer the user-supplied model name when present; fall back to discovery.
  if (manualModel) {
    model = manualModel
  }

  if (!model) {
    // Probe succeeded but the endpoint didn't enumerate any models. The
    // endpoint likely *has* models — we just can't discover them through an
    // OpenAI-shaped /v1/models response. Signal the wizard to reveal a manual
    // model-name input rather than hard-failing; `needsModelInput` is the
    // discriminator the form reads.
    return {
      ok: false,
      needsModelInput: true,
      message: `Connected to ${url}, but it didn't enumerate any models at /v1/models. Enter a model name below (e.g. command-a-plus-05-2026) to continue.`
    }
  }

  try {
    await setMainModelAssignment({ provider: 'custom', model, base_url: resolvedUrl, api_key: key }, ctx.scope)

    if (generation !== flowGeneration) {
      return { ok: false }
    }

    if (!ctx.scope?.profile) {
      await ctx.requestGateway('reload.env').catch(() => undefined)
    }

    if (generation !== flowGeneration) {
      return { ok: false }
    }

    const runtime = await checkRuntime(ctx)

    if (generation !== flowGeneration) {
      return { ok: false }
    }

    if (!runtime.ready) {
      const detail = (runtime.reason ?? '').trim()

      return { ok: false, message: detail || `Saved, but Hermes still cannot reach ${resolvedUrl}.` }
    }

    notifyReady('Local / custom endpoint')
    completeDesktopOnboarding(true)
    ctx.onCompleted?.()

    return { ok: true }
  } catch (error) {
    notifyError(error, 'Could not save local endpoint')

    return { ok: false, message: errMessage(error) }
  }
}

// User picked a different model from the dropdown on the confirm card.
// Persists immediately so the displayed value is always what's on disk.
//
// The picker can surface models from ANY configured provider, not just the
// one the user just authenticated. The selection therefore carries the
// model's real provider slug — persist against that, or a foreign model
// gets paired with the sign-in provider (config says provider A serves a
// model only provider B has; chat errors "provider doesn't have the
// selected model"). Also keep the flow's providerSlug/label in sync so the
// confirm card shows the provider that actually serves the picked model.
export async function setOnboardingModel(model: string, providerSlug: string, label?: string) {
  const generation = flowGeneration
  const { flow } = $desktopOnboarding.get()

  if (flow.status !== 'confirming_model') {
    return
  }

  // The picker may not know the provider's display name yet (catalog still
  // loading); keep the current label rather than blanking the card.
  const displayLabel = label || flow.label

  // Optimistic update so the dropdown feels instant; revert on failure.
  const previous = { currentModel: flow.currentModel, label: flow.label, providerSlug: flow.providerSlug }
  setFlow({ ...flow, currentModel: model, providerSlug, label: displayLabel, saving: true })

  try {
    await setMainModelAssignment(
      {
        provider: providerSlug,
        model
      },
      flowScope ?? $desktopOnboarding.get().targetScope
    )

    if (generation !== flowGeneration) {
      return
    }

    const current = $desktopOnboarding.get().flow

    if (current.status === 'confirming_model') {
      setFlow({ ...current, currentModel: model, providerSlug, label: displayLabel, saving: false })
    }
  } catch (error) {
    if (generation !== flowGeneration) {
      return
    }

    notifyError(error, 'Could not change model')
    const current = $desktopOnboarding.get().flow

    if (current.status === 'confirming_model') {
      setFlow({ ...current, ...previous, saving: false })
    }
  }
}

// User clicked "Start chatting" on the confirm card. First-run: the model
// was already persisted by completeWithModelConfirm (or by setOnboardingModel
// if they changed it), so this only marks onboarding done. Manual connect
// (Settings / "Add provider"): completeWithModelConfirm deliberately skipped
// the persist so the previous default survives a dismiss, so this is where
// the picked model finally gets written — the user just confirmed it.
export async function confirmOnboardingModel(ctx: OnboardingContext) {
  const { flow, manual } = $desktopOnboarding.get()

  if (flow.status !== 'confirming_model') {
    return
  }

  if (manual) {
    // Best-effort: the overlay is already on its way out (cinematic exit
    // choreography in the caller isn't gated on this), so a failure here is
    // reported and swallowed rather than left blocking — same as the rest of
    // this file's non-blocking gateway calls. The alternative (silently
    // keeping the previous default) is still safer than the bug this fixes.
    try {
      const res = await setMainModelAssignment({ provider: flow.providerSlug, model: flow.currentModel }, undefined, {
        skipConfirmPrompt: true
      })

      notifyGatewayTools(res.gateway_tools)
    } catch (error) {
      notifyError(error, 'Could not save the selected model.')
    }
  }

  // No success toast here: the confirm-model screen already showed "<provider>
  // connected." notifyReady is reserved for completion paths that SKIP this
  // screen (no-default fallthrough, local endpoint) so feedback isn't lost.
  completeDesktopOnboarding(true)
  ctx.onCompleted?.()
}