Skip to content

The agent that grows with you

51.8 KB
Raw Blame
import { isGatewayReauthRequired } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useEffect, useRef, useState } from 'react'

import { RemoteSetupFields } from '@/components/remote-setup/fields'
import { useRemoteSetup } from '@/components/remote-setup/use-remote-setup'
import { Button } from '@/components/ui/button'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Tip } from '@/components/ui/tooltip'
import type {
  DesktopCloudAgent,
  DesktopCloudOrg,
  DesktopConnectionConfigInput,
  DesktopRegistryConnection
} from '@/global'
import { useI18n } from '@/i18n'
import { reestablishCloudAgentSession } from '@/lib/cloud-agent-session'
import { ExternalLink } from '@/lib/external-link'
import { hostHas } from '@/lib/host-capabilities'
import {
  AlertCircle,
  Check,
  Cloud,
  FileText,
  Globe,
  HelpCircle,
  Loader2,
  LogIn,
  Monitor,
  RefreshCw,
  Terminal
} from '@/lib/icons'
import { coerceRemoteUrlScheme } from '@/lib/remote-url'
import { selectableCardClass } from '@/lib/selectable-card'
import { cn } from '@/lib/utils'
import {
  $activeConnectionId,
  $connectionsRegistry,
  refreshConnectionsRegistry,
  selectConnection
} from '@/store/connections'
import { managedUpdatesSupported } from '@/store/managed-updates'
import { notify, notifyError, readableError } from '@/store/notifications'

import { cloudTeamChanged, reconnectMovedCloudAgent } from './cloud-team-change'
import { ConnectionsRegistrySection } from './connections-registry'
import { CONTROL_TEXT } from './constants'
import { KeychainEncryptionSetting, useKeychainEncryption } from './keychain-encryption-setting'
import { ManagedUpdatesSection } from './managed-updates-section'
import { EmptyState, ListRow, Pill, SettingsContent, SettingsSkeleton } from './primitives'
import { SETTING_IDS, settingElementId } from './settings-manifest'
import { enrichSelectedSshHost, selectSshHost } from './ssh-host-selection'
import { useSettingDeepLink } from './use-setting-deep-link'
import { WebappGatewaySettings } from './webapp-gateway-settings'

type Mode = 'local' | 'remote' | 'cloud' | 'ssh'
type AuthMode = 'oauth' | 'token'
// Hermes Cloud discovery lifecycle for the cloud-mode panel.
type CloudDiscoverStatus = 'idle' | 'loading' | 'done' | 'error'

export interface GatewaySettingsState {
  envOverride: boolean
  mode: Mode
  remoteAuthMode: AuthMode
  remoteOauthConnected: boolean
  remoteTokenPreview: string | null
  remoteTokenSet: boolean
  // Whether OS-keychain-backed encryption (Electron safeStorage) is available.
  // Default true so we never gate on a value we haven't hydrated yet.
  secureTokenStorage: boolean
  // Whether the currently-persisted remote token is stored as plain text on
  // disk (opted-in on a machine without secure storage). Drives the warning banner.
  remoteTokenPlainText: boolean
  remoteUrl: string
  cloudOrg: string
  sshHost: string
  sshUser: string
  sshPort: number | null
  sshKeyPath: string
  sshRemoteHermesPath: string
  sshRemoteProfile: string
}

const SSH_HOST_CUSTOM = '__custom__'

const EMPTY_STATE: GatewaySettingsState = {
  envOverride: false,
  mode: 'local',
  remoteAuthMode: 'token',
  remoteOauthConnected: false,
  remoteTokenPreview: null,
  remoteTokenSet: false,
  secureTokenStorage: true,
  remoteTokenPlainText: false,
  remoteUrl: '',
  cloudOrg: '',
  sshHost: '',
  sshUser: '',
  sshPort: null,
  sshKeyPath: '',
  sshRemoteHermesPath: '',
  sshRemoteProfile: ''
}

export function normalizeGatewaySettingsState(
  config: Partial<GatewaySettingsState> | null | undefined
): GatewaySettingsState {
  if (!config || typeof config !== 'object') {
    return { ...EMPTY_STATE }
  }

  const defined = Object.fromEntries(Object.entries(config).filter(([, value]) => value != null))

  return { ...EMPTY_STATE, ...defined }
}

export function savedCloudConnectionUrl(config: Pick<GatewaySettingsState, 'mode' | 'remoteUrl'>): string {
  return config.mode === 'cloud' ? config.remoteUrl.trim().replace(/\/+$/, '').toLowerCase() : ''
}

function ModeCard({
  active,
  description,
  disabled,
  hint,
  icon: Icon,
  onSelect,
  title
}: {
  active: boolean
  description: string
  disabled?: boolean
  hint?: string
  icon: typeof Monitor
  onSelect: () => void
  title: string
}) {
  return (
    <button
      className={cn(
        'flex h-full min-h-0 w-full flex-col p-3 text-left disabled:cursor-not-allowed disabled:opacity-50',
        selectableCardClass({ active, prominent: true })
      )}
      disabled={disabled}
      onClick={onSelect}
      type="button"
    >
      <div className="flex items-center gap-1.5">
        <Icon className="size-3.5 shrink-0 text-muted-foreground" />
        <span className="min-w-0 text-[length:var(--conversation-text-font-size)] font-medium">{title}</span>
        {hint ? (
          <Tip label={hint}>
            <span
              className="grid size-3.5 shrink-0 cursor-help place-items-center text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)"
              onClick={event => event.stopPropagation()}
            >
              <HelpCircle className="size-3.5" />
            </span>
          </Tip>
        ) : null}
        {active ? <Check className="ml-auto size-3.5 shrink-0 text-primary" /> : null}
      </div>
      <p className="mt-1.5 flex-1 text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">
        {description}
      </p>
    </button>
  )
}

interface GatewaySettingsProps {
  embedded?: boolean
  subpage?: string
}

export function GatewaySettings({ embedded = false, subpage }: GatewaySettingsProps = {}) {
  useSettingDeepLink('gateway', page => subpage === undefined || page === subpage)

  if (!hostHas('gatewayManagement')) {
    return <WebappGatewaySettings embedded={embedded} />
  }

  // Recovery always keeps the complete connection form, regardless of a
  // settings destination. Other tasks never mount that form or its probes.
  if (!embedded && subpage === 'devices') {
    return (
      <SettingsContent>
        <ConnectionsRegistrySection />
      </SettingsContent>
    )
  }

  if (!embedded && subpage === 'managed-updates') {
    return <GatewayManagedUpdates />
  }

  return <GatewayConnectionSettings embedded={embedded} standalone={subpage !== undefined} />
}

function GatewayManagedUpdates() {
  const { t } = useI18n()
  const registry = useStore($connectionsRegistry)
  const [loading, setLoading] = useState(true)
  const [failed, setFailed] = useState(false)
  const supported = managedUpdatesSupported()

  useEffect(() => {
    if (!supported) {
      return
    }

    let active = true
    void refreshConnectionsRegistry()
      .catch(() => {
        if (active) {
          setFailed(true)
        }
      })
      .finally(() => {
        if (active) {
          setLoading(false)
        }
      })

    return () => {
      active = false
    }
  }, [supported])

  if (supported && loading) {
    return <SettingsSkeleton sections={[{ heading: true, rows: 3 }]} />
  }

  const hasSsh = registry?.connections.some(connection => connection.kind === 'ssh')

  return (
    <SettingsContent>
      {supported && !failed && hasSsh ? (
        <ManagedUpdatesSection />
      ) : (
        <EmptyState
          description={
            !supported
              ? t.settings.subpages.gatewayManagedUpdatesUnavailable
              : failed
                ? t.settings.gateway.failedLoad
                : t.settings.subpages.gatewayManagedUpdatesEmpty
          }
          title={t.settings.managedUpdates.title}
        />
      )}
    </SettingsContent>
  )
}

// `embedded` trims the page chrome for reuse inside the boot-failure recovery
// card: the outer title/intro, the "Save for next restart" action, and the
// Diagnostics row are redundant there (the card owns its header + a single
// reconnect action), so only the connection controls render.
function GatewayConnectionSettings({ embedded, standalone }: { embedded: boolean; standalone: boolean }) {
  const { t } = useI18n()
  const g = t.settings.gateway
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [testing, setTesting] = useState(false)
  const [state, setState] = useState<GatewaySettingsState>(EMPTY_STATE)

  const remote = useRemoteSetup({
    host: 'settings',
    enabled: !loading && state.mode === 'remote',
    beforeOAuthLogin: async (payload: DesktopConnectionConfigInput): Promise<void> => {
      await window.hermesDesktop.saveConnectionConfig(payload)
    },
    onNotice: notify
  })

  const [lastTest, setLastTest] = useState<null | string>(null)
  const [sshHostSuggestions, setSshHostSuggestions] = useState<string[]>([])
  const [sshCustomHost, setSshCustomHost] = useState(false)
  const sshResolveSeq = useRef(0)
  const sshTestSeq = useRef(0)
  const saveSeq = useRef(0)
  const saveOwner = useRef<number | null>(null)
  const signingSeq = useRef(0)
  const cloudConnectSeq = useRef(0)
  const contextSeq = useRef(0)
  const registry = useStore($connectionsRegistry)
  const activeConnectionId = useStore($activeConnectionId)
  const savedCloudConnections = registry?.connections.filter(connection => connection.kind === 'cloud') ?? []

  useEffect(() => {
    void refreshConnectionsRegistry().catch(err => notifyError(err, g.failedLoad))
  }, [g.failedLoad])

  // Read here rather than in the row, so the flag is in hand by the time the
  // loading skeleton gives way and the toggle paints its real state.
  const keychainEncryption = useKeychainEncryption()

  const acceptSavedConfig = (config: GatewaySettingsState): void => {
    const normalized = normalizeGatewaySettingsState(config)

    setState(normalized)
    remote.reset({
      url: normalized.remoteUrl,
      authMode: normalized.remoteAuthMode,
      oauthConnected: normalized.remoteOauthConnected,
      tokenSet: normalized.remoteTokenSet,
      tokenPreview: normalized.remoteTokenPreview
    })
  }

  // When set, the plain-text opt-in dialog is open; `apply` remembers whether
  // the gated action was Save-for-restart (false) or Save-and-reconnect (true)
  // so confirm resumes the right one.
  const [plainTextConfirm, setPlainTextConfirm] = useState<null | { apply: boolean }>(null)

  // --- Hermes Cloud (cloud mode) state ---
  // One portal session powers discovery + the silent per-agent cascade. These
  // track the cloud panel: whether we're signed in, the discovered agent list,
  // and which agent is mid-connect.
  const [cloudSignedIn, setCloudSignedIn] = useState(false)
  const [cloudSigningIn, setCloudSigningIn] = useState(false)
  const [cloudAgents, setCloudAgents] = useState<DesktopCloudAgent[]>([])
  const [cloudDiscover, setCloudDiscover] = useState<CloudDiscoverStatus>('idle')
  const [cloudConnectingId, setCloudConnectingId] = useState<null | string>(null)
  // Multi-org users: when discovery returns needsOrgSelection, we hold the org
  // list here and show a picker. `cloudOrg` is the chosen org slug/id (null =
  // not yet chosen / single-org user).
  const [cloudOrgs, setCloudOrgs] = useState<DesktopCloudOrg[]>([])
  const [cloudOrg, setCloudOrgState] = useState<null | string>(null)
  // Mirror the selected org into a ref so connect reads the CURRENT value, not a
  // value captured in a stale render closure. discoverCloud() resolves the org
  // asynchronously (from the NAS response) and a user can click Connect in the
  // same render tick; without the ref, connectCloudAgent could persist a null
  // org even though discovery just resolved one. Always set both together.
  const cloudOrgRef = useRef<null | string>(null)

  const setCloudOrg = (value: null | string) => {
    cloudOrgRef.current = value
    setCloudOrgState(value)
  }

  useEffect(() => {
    let cancelled = false
    const desktop = window.hermesDesktop

    if (!desktop?.getConnectionConfig) {
      setLoading(false)

      return () => void (cancelled = true)
    }

    setLoading(true)

    desktop
      .getConnectionConfig(null)
      .then(config => {
        if (cancelled) {
          return
        }

        acceptSavedConfig(config)
      })
      .catch(err => notifyError(err, g.failedLoad))
      .finally(() => {
        if (!cancelled) {
          setLoading(false)
        }
      })

    return () => void (cancelled = true)
    // eslint-disable-next-line react-hooks/exhaustive-deps -- load once on mount; copy is stable
  }, [])

  // Debounced probe of the entered remote URL. Only runs in remote mode with a
  // syntactically plausible URL. The probe result drives whether we render the
  // OAuth login button or the session-token entry box. The effective auth mode
  // prefers a fresh probe result over the saved value.
  const trimmedUrl = coerceRemoteUrlScheme(state.remoteUrl)

  const savedAgent = (agent: DesktopCloudAgent) => {
    const dashboardUrl = agent.dashboardUrl

    if (!dashboardUrl) {
      return undefined
    }

    const target = savedCloudConnectionUrl({ mode: 'cloud', remoteUrl: dashboardUrl })

    return registry?.connections.find(
      (connection): connection is DesktopRegistryConnection & { url: string } =>
        (connection.kind === 'cloud' || connection.kind === 'remote') &&
        typeof connection.url === 'string' &&
        savedCloudConnectionUrl({ mode: 'cloud', remoteUrl: connection.url }) === target
    )
  }

  const isConnectedAgent = (agent: DesktopCloudAgent) =>
    savedAgent(agent)?.id === activeConnectionId && !cloudTeamChanged(savedAgent(agent), cloudOrg)

  // A saved cloud connection's gateway session can lapse while the app sits
  // on a local-primary device — the dial then rejects with a reauth-shaped
  // error whose copy points here ("Open Settings → Gateway and sign in
  // again"), yet nothing else in Settings re-authenticates a cloud row. Run
  // the one recovery that exists for this state — drop the lapsed cookies,
  // ensure the portal session, silent-cascade the agent — then retry the
  // switch once. Everything else stays a plain failed switch.
  const selectSavedCloudWithReauth = async (id: string, dashboardUrl?: string) => {
    try {
      await selectConnection(id)
    } catch (error) {
      if (!isGatewayReauthRequired(error)) {
        throw error
      }

      const desktop = window.hermesDesktop

      // Cloud registry URLs are the persisted agent dashboardUrl. Keep saved
      // rows usable without discovery, but never run the cascade against ''.
      if (!desktop?.cloud || !dashboardUrl) {
        throw error
      }

      const outcome = await reestablishCloudAgentSession(desktop, dashboardUrl)

      if (outcome !== 'connected') {
        notify({
          kind: 'warning',
          title: t.boot.failure.signInIncompleteTitle,
          message: t.boot.failure.signInIncompleteMessage
        })

        throw error
      }

      await selectConnection(id)
    }
  }

  const activateSavedCloud = async (id: string, dashboardUrl?: string) => {
    setCloudConnectingId(id)

    try {
      await selectSavedCloudWithReauth(id, dashboardUrl)
    } catch (err) {
      notifyError(err, g.cloudConnectFailed)
    } finally {
      setCloudConnectingId(null)
    }
  }

  useEffect(() => {
    // One-directional: a saved host that isn't in the suggestions must render
    // the free-text input (rehydration). Never force custom OFF here — that
    // instantly snapped the just-clicked-Custom (empty-host) input back to the
    // dropdown, making a raw-IP host impossible to type. The way back to the
    // dropdown is the input's onBlur (empty host + suggestions).
    if (state.sshHost && !sshHostSuggestions.includes(state.sshHost)) {
      setSshCustomHost(true)
    }
  }, [state.sshHost, sshHostSuggestions])

  useEffect(() => {
    if (state.mode !== 'ssh' || !window.hermesDesktop?.sshConfigHosts) {
      return
    }

    let cancelled = false
    void window.hermesDesktop
      .sshConfigHosts()
      .then(result => {
        if (!cancelled) {
          setSshHostSuggestions(result.hosts)
        }
      })
      .catch(() => {
        if (!cancelled) {
          setSshHostSuggestions([])
        }
      })

    return () => void (cancelled = true)
  }, [state.mode])

  // eslint-disable-next-line no-restricted-syntax -- monotonic request-sequence counters, not an atom mirror
  useEffect(() => {
    contextSeq.current += 1
    sshTestSeq.current += 1
    saveSeq.current += 1
    signingSeq.current += 1
    cloudConnectSeq.current += 1
    setLastTest(null)
  }, [
    state.mode,
    remote.credentials.url,
    remote.credentials.token,
    remote.credentials.authMode,
    state.sshHost,
    state.sshUser,
    state.sshPort,
    state.sshKeyPath,
    state.sshRemoteHermesPath,
    state.sshRemoteProfile
  ])

  const payload = (allowPlainTextToken?: boolean): DesktopConnectionConfigInput => ({
    ...(state.mode === 'remote'
      ? remote.payload
      : {
          mode: state.mode,
          remoteAuthMode: state.remoteAuthMode,
          remoteUrl: coerceRemoteUrlScheme(state.remoteUrl),
          sshHost: state.sshHost.trim(),
          // Send an explicit '' for cleared fields. Main merges with `??`, so
          // `undefined` means "inherit the saved value" and a cleared Identity
          // file (or User) could never be removed once saved: the form kept
          // refilling the stale path, and the stale key path made the v1 SSH
          // route's identity differ from the registered gateway's, leaving
          // the window unscoped.
          sshUser: state.sshUser.trim(),
          sshPort: state.sshPort,
          sshKeyPath: state.sshKeyPath.trim(),
          sshRemoteHermesPath: state.sshRemoteHermesPath.trim(),
          // A blank clears an existing remote-profile mapping.
          sshRemoteProfile: state.sshRemoteProfile.trim()
        }),
    ...(allowPlainTextToken ? { allowPlainTextToken: true } : {})
  })

  // A pending Save/Apply would write a NEW token to disk in plain text when
  // we're on a remote-like connection using token auth, the user typed a token,
  // and this machine has no OS keyring (safeStorage unavailable). In that case
  // we must get an explicit opt-in before persisting.
  const wouldPersistPlainTextToken =
    state.mode === 'remote' &&
    remote.credentials.authMode === 'token' &&
    Boolean(remote.credentials.token.trim()) &&
    state.secureTokenStorage === false

  const performSave = async (apply: boolean, allowPlainTextToken: boolean): Promise<void> => {
    const seq = ++saveSeq.current
    saveOwner.current = seq
    setSaving(true)

    try {
      const next = apply
        ? await window.hermesDesktop.applyConnectionConfig(payload(allowPlainTextToken))
        : await window.hermesDesktop.saveConnectionConfig(payload(allowPlainTextToken))

      if (seq !== saveSeq.current) {
        return
      }

      acceptSavedConfig(next)
      notify({
        kind: 'success',
        title: apply ? g.restartingTitle : g.savedTitle,
        message: apply ? g.restartingMessage : g.savedMessage
      })
    } catch (err) {
      if (seq !== saveSeq.current) {
        return
      }

      // The plain-text opt-in path runs inside ConfirmDialog's onConfirm, which
      // keeps the dialog open with an inline error when it throws — rethrow a
      // readable message there so a failed save can't play the success beat.
      if (allowPlainTextToken) {
        throw new Error(readableError(err, apply ? g.applyFailed : g.saveFailed).message)
      }

      const sshError = err && typeof err === 'object' && 'sshError' in err ? String(err.sshError) : ''

      const errors = {
        'auth-failed': g.sshErrAuth,
        'hermes-not-found': g.sshErrNotInstalled,
        'host-key-changed': g.sshErrHostKey,
        'interactive-auth': g.sshErrInteractiveAuth,
        timeout: g.sshErrTimeout,
        unreachable: g.sshErrUnreachable,
        'unsupported-platform': g.sshErrPlatform,
        'update-required': g.sshErrUpdateRequired
      }

      if (state.mode === 'ssh' && sshError) {
        notify({
          kind: 'error',
          title: apply ? g.applyFailed : g.saveFailed,
          message: (errors as Record<string, string>)[sshError] || readableError(err, g.sshErrUnknown).message
        })
      } else {
        notifyError(err, apply ? g.applyFailed : g.saveFailed)
      }
    } finally {
      // A stale response cannot replace the draft, but its request must release busy state.
      if (seq === saveOwner.current) {
        saveOwner.current = null
        setSaving(false)
      }
    }
  }

  const save = async (apply: boolean): Promise<void> => {
    if (state.mode === 'remote' && !remote.canCommit) {
      notify({
        kind: 'warning',
        title: g.incompleteTitle,
        message: remote.credentials.authMode === 'oauth' ? g.incompleteSignIn : g.incompleteToken
      })

      return
    }

    // Defer to the opt-in dialog; confirm resumes with allowPlainTextToken.
    if (wouldPersistPlainTextToken) {
      setPlainTextConfirm({ apply })

      return
    }

    await performSave(apply, false)
  }

  // --- Hermes Cloud handlers ---

  // Pull the discovered agent list over the shared portal session. Tolerant of
  // a lapsed session: a needsCloudLogin error flips us back to signed-out.
  // `org` scopes discovery for multi-org users; when discovery comes back with
  // needsOrgSelection we surface the org list and show a picker instead.
  const discoverCloud = async (org?: string) => {
    const desktop = window.hermesDesktop
    const seq = contextSeq.current

    if (!desktop?.cloud) {
      return
    }

    setCloudDiscover('loading')

    try {
      const result = await desktop.cloud.discover(org)

      if (seq !== contextSeq.current) {
        return
      }

      if ('needsOrgSelection' in result && result.needsOrgSelection) {
        // Multi-org user with no org chosen yet: show the picker. Don't clear a
        // previously-chosen org list on a refresh.
        setCloudOrgs(result.orgs)
        setCloudOrg(null)
        setCloudAgents([])
        setCloudDiscover('done')

        return
      }

      // Single org (or org now chosen): we have agents.
      setCloudAgents('agents' in result ? result.agents : [])

      // Record the org AUTHORITATIVELY from the response (NAS echoes the org the
      // list was scoped to), falling back to the org we requested. This is what
      // gets persisted on connect, so it must be set even on single-membership
      // auto-resolve where no picker ran and no `org` arg was passed.
      const resolvedOrgRef = 'org' in result && result.org ? (result.org.slug ?? result.org.id) : null

      if (resolvedOrgRef) {
        setCloudOrg(resolvedOrgRef)
      } else if (org) {
        setCloudOrg(org)
      }

      setCloudDiscover('done')
    } catch (err) {
      if (seq !== contextSeq.current) {
        return
      }

      setCloudAgents([])
      setCloudDiscover('error')

      // A lapsed/absent portal session means we're effectively signed out.
      if (err && typeof err === 'object' && 'needsCloudLogin' in err) {
        setCloudSignedIn(false)
      }

      notifyError(err, g.cloudDiscoverFailed)
    }
  }

  // User picked an org from the multi-org picker: remember it and re-run
  // discovery scoped to it.
  const selectCloudOrg = (org: DesktopCloudOrg) => {
    const ref = org.slug ?? org.id
    setCloudOrg(ref)
    void discoverCloud(ref)
  }

  // "Change org": clear the selected org and re-discover with no org arg. A
  // multi-org user gets NAS's 409 → the picker; a single-org user auto-resolves
  // back to their one org. Also clear the agent list so the current org's
  // agents don't linger under the picker while discovery re-runs.
  const changeCloudOrg = () => {
    setCloudOrg(null)
    setCloudAgents([])
    void discoverCloud()
  }

  // On entering cloud mode, read the portal session status and
  // auto-discover when already signed in, so the picker is populated on open.
  useEffect(() => {
    if (state.mode !== 'cloud') {
      return
    }

    const desktop = window.hermesDesktop

    if (!desktop?.cloud) {
      return
    }

    let cancelled = false
    desktop.cloud
      .status()
      .then(status => {
        if (cancelled) {
          return
        }

        setCloudSignedIn(status.signedIn)

        if (status.signedIn) {
          // Restore the persisted org (if any) so we reopen straight into that
          // org's agent list instead of the picker; discoverCloud(org) also
          // records it as the selected org. Empty → normal discovery (single-org
          // resolves automatically; multi-org shows the picker).
          const savedOrg = state.cloudOrg || ''

          if (savedOrg) {
            setCloudOrg(savedOrg)
          }

          void discoverCloud(savedOrg || undefined)
        } else {
          setCloudAgents([])
          setCloudOrgs([])
          setCloudOrg(null)
          setCloudDiscover('idle')
        }
      })
      .catch(() => {
        if (!cancelled) {
          setCloudSignedIn(false)
        }
      })

    return () => void (cancelled = true)
    // eslint-disable-next-line react-hooks/exhaustive-deps -- reload on mode change only
  }, [state.mode])

  const cloudSignIn = async () => {
    const desktop = window.hermesDesktop
    const seq = ++signingSeq.current

    if (!desktop?.cloud) {
      return
    }

    setCloudSigningIn(true)

    try {
      const result = await desktop.cloud.login()

      if (seq !== signingSeq.current) {
        return
      }

      setCloudSignedIn(result.signedIn)

      if (result.signedIn) {
        await discoverCloud()
      }
    } catch (err) {
      if (seq === signingSeq.current) {
        notifyError(err, g.cloudSignInFailed)
      }
    } finally {
      if (seq === signingSeq.current) {
        setCloudSigningIn(false)
      }
    }
  }

  const cloudSignOut = async () => {
    const desktop = window.hermesDesktop
    const seq = ++signingSeq.current

    if (!desktop?.cloud) {
      return
    }

    setCloudSigningIn(true)

    try {
      await desktop.cloud.logout()

      if (seq !== signingSeq.current) {
        return
      }

      setCloudSignedIn(false)
      setCloudAgents([])
      setCloudOrgs([])
      setCloudOrg(null)
      setCloudDiscover('idle')
      notify({ kind: 'success', title: g.cloudSignedOutTitle, message: g.cloudSignedOutMessage })
    } catch (err) {
      if (seq === signingSeq.current) {
        notifyError(err, g.signOutFailed)
      }
    } finally {
      if (seq === signingSeq.current) {
        setCloudSigningIn(false)
      }
    }
  }

  // Select a discovered agent: drive the silent per-agent cascade (no second
  // prompt — the shared portal session auto-approves), then persist a cloud-mode
  // connection pointed at its dashboardUrl and apply it (soft-reconnects in place).
  const connectCloudAgent = async (agent: DesktopCloudAgent) => {
    const seq = contextSeq.current

    if (!agent.dashboardUrl) {
      return
    }

    const desktop = window.hermesDesktop

    if (!desktop?.cloud) {
      return
    }

    setCloudConnectingId(agent.id)

    const warnSignInIncomplete = () =>
      notify({
        kind: 'warning',
        title: t.boot.failure.signInIncompleteTitle,
        message: t.boot.failure.signInIncompleteMessage
      })

    try {
      // Saved sources keep their identity, credentials and default gateway.
      // The activation path reuses healthy sockets and validates auth on a new dial.
      const saved = savedAgent(agent)

      if (saved) {
        const org = cloudOrgRef.current

        if (org && cloudTeamChanged(saved, org)) {
          const reconnected = await reconnectMovedCloudAgent(desktop, saved, org, () => seq === contextSeq.current)

          if (seq !== contextSeq.current) {
            return
          }

          if (!reconnected) {
            warnSignInIncomplete()

            return
          }

          await refreshConnectionsRegistry()
        }

        await selectSavedCloudWithReauth(saved.id, agent.dashboardUrl)

        return
      }

      const result = await desktop.cloud.agentSignIn(agent.dashboardUrl)

      if (seq !== contextSeq.current) {
        return
      }

      if (!result.connected) {
        warnSignInIncomplete()

        return
      }

      // Persist a cloud-mode connection (remote-shaped, oauth) and soft-reconnect.
      // Include the selected org so Settings reopens into the same org + instance.
      // Read the REF (not the cloudOrg state) so a just-resolved org from
      // discovery in this same render tick is captured, not a stale null.
      const next = await desktop.applyConnectionConfig({
        mode: 'cloud',
        remoteAuthMode: 'oauth',
        remoteUrl: agent.dashboardUrl,
        cloudOrg: cloudOrgRef.current ?? undefined,
        cloudName: agent.name
      })

      if (seq !== contextSeq.current) {
        return
      }

      acceptSavedConfig(next)
      await refreshConnectionsRegistry()
      notify({ kind: 'success', title: g.cloudConnectedTitle, message: g.cloudConnectedTo(agent.name) })
    } catch (err) {
      if (seq !== contextSeq.current) {
        return
      }

      if (err && typeof err === 'object' && 'needsCloudLogin' in err) {
        setCloudSignedIn(false)
      }

      notifyError(err, g.cloudConnectFailed)
    } finally {
      if (seq === contextSeq.current) {
        setCloudConnectingId(null)
      }
    }
  }

  const resolveSshHost = async (host: string) => {
    if (!host || !window.hermesDesktop?.sshResolveHost) {
      return
    }

    const seq = ++sshResolveSeq.current

    try {
      const resolved = await window.hermesDesktop.sshResolveHost(host)

      if (seq !== sshResolveSeq.current) {
        return
      }

      setState(current => enrichSelectedSshHost(current, host, resolved))
    } catch {
      return
    }
  }

  const selectHost = (value: string) => {
    if (value === SSH_HOST_CUSTOM) {
      setSshCustomHost(true)
      setState(current => selectSshHost(current, ''))

      return
    }

    setSshCustomHost(false)
    setState(current => selectSshHost(current, value))
    void resolveSshHost(value)
  }

  const testSsh = async () => {
    const seq = ++sshTestSeq.current

    if (!state.sshHost.trim()) {
      notify({ kind: 'warning', title: g.incompleteTitle, message: g.sshIncompleteHost })

      return
    }

    setTesting(true)
    setLastTest(null)

    try {
      const result = await window.hermesDesktop.testConnectionConfig(payload())

      if (seq !== sshTestSeq.current) {
        return
      }

      if (!result.reachable) {
        const errors = {
          'auth-failed': g.sshErrAuth,
          'hermes-not-found': g.sshErrNotInstalled,
          'host-key-changed': g.sshErrHostKey,
          'interactive-auth': g.sshErrInteractiveAuth,
          timeout: g.sshErrTimeout,
          unreachable: g.sshErrUnreachable,
          'unsupported-platform': g.sshErrPlatform,
          'update-required': g.sshErrUpdateRequired,
          unknown: g.sshErrUnknown
        }

        // An unclassified failure carries its own cause (the remote probe's error); the generic copy would hide it.
        throw new Error(
          (result.sshError && result.sshError !== 'unknown' && errors[result.sshError]) ||
            result.error ||
            g.sshErrUnknown
        )
      }

      const message = g.sshReachable(result.host || state.sshHost, result.remotePlatform || '?')
      setLastTest(message)
      notify({ kind: 'success', title: g.reachableTitle, message })
    } catch (err) {
      if (seq === sshTestSeq.current) {
        notifyError(err, g.testFailed)
      }
    } finally {
      if (seq === sshTestSeq.current) {
        setTesting(false)
      }
    }
  }

  if (loading) {
    return (
      <SettingsSkeleton
        sections={[
          { heading: true, rows: 3 },
          { heading: true, rows: 3 }
        ]}
      />
    )
  }

  if (!window.hermesDesktop?.getConnectionConfig) {
    return <EmptyState description={g.unavailableDesc} title={g.unavailableTitle} />
  }

  return (
    <SettingsContent bare={embedded}>
      {embedded || standalone ? null : (
        <div className="mb-5">
          <div className="flex items-center gap-2 text-[length:var(--conversation-text-font-size)] font-medium">
            <Globe className="size-4 text-muted-foreground" />
            {g.title}
            {state.envOverride ? <Pill tone="primary">{g.envOverride}</Pill> : null}
          </div>
          <p className="mt-2 max-w-2xl text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">
            {g.intro}
          </p>
        </div>
      )}

      {state.envOverride ? (
        <div className="mb-5 flex items-start gap-2 rounded-xl border border-destructive/30 bg-destructive/10 px-3 py-2.5 text-[length:var(--conversation-caption-font-size)] text-destructive">
          <AlertCircle className="mt-0.5 size-4 shrink-0" />
          <div>
            <div className="font-medium">{g.envOverrideTitle}</div>
            <div className="mt-1 leading-5">{g.envOverrideDesc}</div>
          </div>
        </div>
      ) : null}

      <div className="mb-5 grid gap-2" id={settingElementId(SETTING_IDS.gateway.connectionMode)}>
        <div className="text-[length:var(--conversation-caption-font-size)] font-medium text-(--ui-text-secondary)">
          {g.modeTitle}
        </div>
        <div className="grid auto-rows-fr grid-cols-1 gap-2 sm:grid-cols-2 min-[72rem]:grid-cols-4">
          <ModeCard
            active={state.mode === 'local'}
            description={g.localDesc}
            disabled={state.envOverride}
            icon={Monitor}
            onSelect={() => setState(current => ({ ...current, mode: 'local' }))}
            title={g.localTitle}
          />
          <ModeCard
            active={state.mode === 'cloud'}
            description={g.cloudDesc}
            disabled={state.envOverride}
            icon={Cloud}
            onSelect={() => setState(current => ({ ...current, mode: 'cloud' }))}
            title={g.cloudTitle}
          />
          <ModeCard
            active={state.mode === 'remote'}
            description={g.remoteDesc}
            disabled={state.envOverride}
            hint={g.remoteAuthHint}
            icon={Globe}
            onSelect={() => setState(current => ({ ...current, mode: 'remote' }))}
            title={g.remoteTitle}
          />
          <ModeCard
            active={state.mode === 'ssh'}
            description={g.sshDesc}
            disabled={state.envOverride}
            hint={g.sshTrustHint}
            icon={Terminal}
            onSelect={() => setState(current => ({ ...current, mode: 'ssh' }))}
            title={g.sshTitle}
          />
        </div>
      </div>

      {/* Hermes Cloud panel: one portal sign-in, then a discovered-agent picker
          whose selection drives the silent per-agent cascade + a cloud
          connection. Replaces the URL/token form while in cloud mode. */}
      {state.mode === 'cloud' && !state.envOverride ? (
        <div className="mt-5 grid gap-1">
          {savedCloudConnections.length > 0 ? (
            <div className="mb-4 grid gap-1">
              <div className="text-[length:var(--conversation-caption-font-size)] font-medium text-(--ui-text-secondary)">
                {g.cloudSavedTitle}
              </div>
              <p className="mb-2 text-xs text-muted-foreground">{g.cloudSavedDesc}</p>
              {savedCloudConnections.map(connection => (
                <div data-slot="saved-cloud-gateway" key={connection.id}>
                  <ListRow
                    action={
                      activeConnectionId === connection.id ? (
                        <Pill tone="primary">
                          <Check className="size-3" />
                          {g.cloudActive}
                        </Pill>
                      ) : (
                        <Button
                          disabled={cloudConnectingId !== null}
                          onClick={() => void activateSavedCloud(connection.id, connection.url)}
                          size="sm"
                          variant="outline"
                        >
                          {cloudConnectingId === connection.id ? <Loader2 className="animate-spin" /> : null}
                          {g.cloudUseSaved}
                        </Button>
                      )
                    }
                    description={connection.url}
                    title={connection.label}
                  />
                </div>
              ))}
            </div>
          ) : null}
          <ListRow
            action={
              cloudSignedIn ? (
                <div className="flex items-center gap-2">
                  <Pill tone="primary">
                    <Check className="size-3" /> {g.cloudSignedIn}
                  </Pill>
                  <Button disabled={cloudSigningIn} onClick={() => void cloudSignOut()} variant="outline">
                    {cloudSigningIn ? <Loader2 className="animate-spin" /> : null}
                    {g.signOut}
                  </Button>
                </div>
              ) : (
                <Button disabled={cloudSigningIn} onClick={() => void cloudSignIn()}>
                  {cloudSigningIn ? <Loader2 className="animate-spin" /> : <LogIn />}
                  {g.cloudSignIn}
                </Button>
              )
            }
            description={cloudSignedIn ? g.cloudSignedInDesc : g.cloudNeedsSignIn}
            title={g.cloudSignInTitle}
          />

          {cloudSignedIn ? (
            cloudOrgs.length > 0 && !cloudOrg ? (
              // Multi-org user who hasn't picked an org yet: show the org picker
              // instead of the agent list. Selecting one re-runs discovery
              // scoped to it.
              <div className="mt-3">
                <div className="mb-2 text-[length:var(--conversation-caption-font-size)] font-medium text-(--ui-text-secondary)">
                  {g.cloudOrgPickerTitle}
                </div>
                <div className="grid gap-1">
                  {cloudOrgs.map(orgEntry => (
                    <ListRow
                      action={
                        <Button onClick={() => selectCloudOrg(orgEntry)} size="sm">
                          {g.cloudOrgSelect}
                        </Button>
                      }
                      description={g.cloudOrgRole(orgEntry.role)}
                      key={orgEntry.id}
                      title={orgEntry.name}
                    />
                  ))}
                </div>
              </div>
            ) : (
              <div className="mt-3">
                <div className="mb-2 flex items-center justify-between">
                  <div className="text-[length:var(--conversation-caption-font-size)] font-medium text-(--ui-text-secondary)">
                    {g.cloudAgentsTitle}
                  </div>
                  <div className="flex items-center gap-2">
                    {cloudOrg ? (
                      // Let the user switch orgs. Gating on cloudOrgs.length would
                      // hide this after a restore-open (which discovers straight
                      // into the saved org and never populates the org list). So
                      // show it whenever an org is selected: clicking clears the
                      // org and re-runs discovery with no org arg — a multi-org
                      // user gets the picker (NAS 409), a single-org user simply
                      // auto-resolves back to their one org (harmless).
                      <Button onClick={() => changeCloudOrg()} size="sm" variant="text">
                        {g.cloudOrgChange}
                      </Button>
                    ) : null}
                    <Button
                      disabled={cloudDiscover === 'loading'}
                      onClick={() => void discoverCloud(cloudOrg ?? undefined)}
                      size="sm"
                      variant="text"
                    >
                      {cloudDiscover === 'loading' ? <Loader2 className="animate-spin" /> : <RefreshCw />}
                      {g.cloudRefresh}
                    </Button>
                  </div>
                </div>

                {cloudDiscover === 'loading' ? (
                  <div className="flex items-center gap-2 py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
                    <Loader2 className="size-4 animate-spin" />
                    {g.cloudLoadingAgents}
                  </div>
                ) : cloudAgents.length === 0 ? (
                  <div className="flex items-start gap-2 py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
                    <AlertCircle className="mt-0.5 size-4 shrink-0" />
                    <span>
                      {g.cloudNoAgents.before}
                      <ExternalLink href="https://portal.nousresearch.com/agents" showExternalIcon={false}>
                        {g.cloudNoAgents.linkText}
                      </ExternalLink>
                      {g.cloudNoAgents.after}
                    </span>
                  </div>
                ) : (
                  <div className="grid gap-1">
                    {cloudAgents.map(agent => {
                      const connected = isConnectedAgent(agent)
                      const gatewayState = (agent.dashboardGatewayState ?? '').trim()
                      const hasKnownGatewayState = gatewayState.length > 0 && gatewayState.toLowerCase() !== 'unknown'

                      return (
                        <div
                          className={cn('rounded-md px-2', connected && 'bg-primary/5 ring-1 ring-primary/25')}
                          key={agent.id}
                        >
                          <ListRow
                            action={
                              connected ? (
                                <Pill tone="primary">
                                  <Check className="mr-1 inline size-3" />
                                  {g.cloudActive}
                                </Pill>
                              ) : (
                                <Button
                                  disabled={!agent.dashboardUrl || cloudConnectingId !== null}
                                  onClick={() => void connectCloudAgent(agent)}
                                  size="sm"
                                >
                                  {cloudConnectingId === agent.id ? <Loader2 className="animate-spin" /> : null}
                                  {agent.dashboardUrl
                                    ? cloudConnectingId === agent.id
                                      ? g.cloudConnecting
                                      : savedAgent(agent)
                                        ? g.cloudUseSaved
                                        : g.cloudConnect
                                    : g.cloudAgentProvisioning}
                                </Button>
                              )
                            }
                            description={hasKnownGatewayState ? g.cloudStatusLabel(gatewayState) : undefined}
                            title={savedAgent(agent)?.label || agent.name}
                          />
                        </div>
                      )
                    })}
                  </div>
                )}
              </div>
            )
          ) : null}
        </div>
      ) : null}

      {/* An env-pinned remote (HERMES_DESKTOP_REMOTE_URL) still renders this
          block: the override pins the URL/mode, but the browser SESSION is not
          env-owned — docs promise "you still sign in from the Gateway settings
          panel" (user-guide/desktop.md). Hiding it left a lapsed session with
          no sign-in anywhere in Settings, and the boot-recovery card routes
          every remote failure here, so "Use local gateway" became the only way
          back in (#114856). The URL input and Save/Test stay env-gated. */}
      {state.mode === 'remote' ? (
        <div className="mt-5">
          <RemoteSetupFields disabled={saving} setup={remote} urlDisabled={state.envOverride} />
          {remote.credentials.authMode === 'token' && state.remoteTokenPlainText ? (
            <div className="mt-2 text-sm text-destructive">
              <div className="font-medium">{g.plainTextStoredTitle}</div>
              <div>{g.plainTextStoredDesc}</div>
            </div>
          ) : null}
        </div>
      ) : null}

      {state.mode === 'ssh' && !state.envOverride ? (
        <div className="mt-5 grid gap-1">
          {sshHostSuggestions.length > 0 && !sshCustomHost ? (
            <ListRow
              action={
                <Select
                  onValueChange={selectHost}
                  // Only report an actual host here. Leaving the value at the
                  // empty string shows the placeholder; using SSH_HOST_CUSTOM
                  // while the dropdown is still rendered would make the FIRST
                  // "Custom" click a no-op (Radix suppresses onValueChange when
                  // a controlled value doesn't change), so the custom-host
                  // input would never mount without a round-trip through
                  // another option.
                  value={sshHostSuggestions.includes(state.sshHost) ? state.sshHost : ''}
                >
                  <SelectTrigger className={cn('h-8', CONTROL_TEXT)}>
                    <SelectValue placeholder={g.sshHostPick} />
                  </SelectTrigger>
                  <SelectContent>
                    {sshHostSuggestions.map(host => (
                      <SelectItem key={host} value={host}>
                        {host}
                      </SelectItem>
                    ))}
                    <SelectItem value={SSH_HOST_CUSTOM}>{g.sshHostCustom}</SelectItem>
                  </SelectContent>
                </Select>
              }
              description={g.sshHostPickDesc}
              title={g.sshHostPickTitle}
            />
          ) : (
            <ListRow
              action={
                <Input
                  autoFocus={sshCustomHost}
                  className={cn('h-8', CONTROL_TEXT)}
                  onBlur={() => {
                    // Empty host on blur with suggestions available = the user backed
                    // out of Custom; return to the dropdown.
                    if (!state.sshHost.trim() && sshHostSuggestions.length > 0) {
                      setSshCustomHost(false)

                      return
                    }

                    void resolveSshHost(state.sshHost)
                  }}
                  onChange={event => setState(current => selectSshHost(current, event.target.value))}
                  value={state.sshHost}
                />
              }
              description={g.sshHostDesc}
              title={g.sshHostTitle}
            />
          )}
          <ListRow
            action={
              <Input
                className={cn('h-8', CONTROL_TEXT)}
                onChange={event => setState(current => ({ ...current, sshUser: event.target.value }))}
                placeholder={g.sshUserPlaceholder}
                value={state.sshUser}
              />
            }
            description={g.sshUserDesc}
            title={g.sshUserTitle}
          />
          <ListRow
            action={
              <Input
                className={cn('h-8', CONTROL_TEXT)}
                inputMode="numeric"
                onChange={event =>
                  setState(current => ({ ...current, sshPort: event.target.value ? Number(event.target.value) : null }))
                }
                placeholder="22"
                value={state.sshPort ?? ''}
              />
            }
            description={g.sshPortDesc}
            title={g.sshPortTitle}
          />
          <ListRow
            action={
              <Input
                className={cn('h-8 font-mono', CONTROL_TEXT)}
                onChange={event => setState(current => ({ ...current, sshKeyPath: event.target.value }))}
                value={state.sshKeyPath}
              />
            }
            description={g.sshKeyDesc}
            title={g.sshKeyTitle}
          />
          <ListRow
            action={
              <Input
                className={cn('h-8 font-mono', CONTROL_TEXT)}
                onChange={event => setState(current => ({ ...current, sshRemoteHermesPath: event.target.value }))}
                placeholder={g.sshHermesPathPlaceholder}
                value={state.sshRemoteHermesPath}
              />
            }
            description={g.sshHermesPathDesc}
            title={g.sshHermesPathTitle}
          />
        </div>
      ) : null}

      {lastTest ? <div className="mt-4 text-xs text-primary">{lastTest}</div> : null}

      {/* Test/Save apply to local + remote. Cloud connects via the agent picker
          above (which applies a cloud connection on select), so its only
          bottom-row action would be redundant — hidden in cloud mode. */}
      {state.mode !== 'cloud' ? (
        <div className="mt-6 flex flex-wrap items-center justify-end gap-4">
          {state.mode === 'remote' ? (
            <Button
              className="mr-auto"
              disabled={state.envOverride || saving || remote.testing || !remote.canTest}
              onClick={() => void remote.test()}
              size="sm"
              variant="text"
            >
              {remote.testing ? <Loader2 className="animate-spin" /> : null}
              {g.testRemote}
            </Button>
          ) : state.mode === 'ssh' ? (
            <Button
              className="mr-auto"
              disabled={testing || !state.sshHost.trim()}
              onClick={() => void testSsh()}
              size="sm"
              variant="text"
            >
              {testing ? <Loader2 className="animate-spin" /> : null}
              {g.sshTestConnection}
            </Button>
          ) : null}
          {embedded ? null : (
            <Button
              disabled={state.envOverride || saving}
              onClick={() => void save(false)}
              size="sm"
              variant="textStrong"
            >
              {g.saveForRestart}
            </Button>
          )}
          <Button disabled={state.envOverride || saving} onClick={() => void save(true)} size="sm">
            {saving ? <Loader2 className="animate-spin" /> : null}
            {g.saveAndReconnect}
          </Button>
        </div>
      ) : null}

      {embedded ? null : (
        <div className="mt-6 grid gap-1">
          <KeychainEncryptionSetting keychain={keychainEncryption} />
          <ListRow
            action={
              <Button onClick={() => void window.hermesDesktop?.revealLogs()} size="sm" variant="textStrong">
                <FileText />
                {g.openLogs}
              </Button>
            }
            description={g.diagnosticsDesc}
            id={settingElementId(SETTING_IDS.gateway.diagnostics)}
            title={g.diagnostics}
          />
        </div>
      )}

      {/* Preserve the full legacy page outside subpage navigation, without
          mounting registry editors in connection-only or recovery views. */}
      {embedded || standalone ? null : (
        <>
          <ConnectionsRegistrySection />
          {/* Per-connection driver for the transactional managed SSH update
              engine (#95942). Renders only when SSH sources are registered and
              the Electron main exposes connections.updateManaged. */}
          <ManagedUpdatesSection />
        </>
      )}

      {/* Plain-text token opt-in: gated when secure storage is unavailable and a
          new token would be persisted. Confirm resumes the remembered save/apply. */}
      <ConfirmDialog
        confirmLabel={g.plainTextConfirmAction}
        description={g.plainTextConfirmDesc}
        destructive
        onClose={() => setPlainTextConfirm(null)}
        onConfirm={async () => {
          if (!plainTextConfirm) {
            return
          }

          await performSave(plainTextConfirm.apply, true)
        }}
        open={plainTextConfirm !== null}
        title={g.plainTextConfirmTitle}
      />
    </SettingsContent>
  )
}