Skip to content

The agent that grows with you

50.3 KB
Raw Blame
/**
 * Desktop self-update store. Tracks distance from the configured branch,
 * surfaces it as an ambient pill, and orchestrates the apply flow.
 */

import { updateDebt } from '@hermes/shared'
import { atom } from 'nanostores'

import { CANONICAL_GATEWAY_PROTOCOL } from '@/api/canonical-protocol'
import { $apiRequestScope, connectionScoped, profileScoped } from '@/api/client'
import type {
  DesktopUpdateApplyOptions,
  DesktopUpdateApplyResult,
  DesktopUpdateProgress,
  DesktopUpdateStage,
  DesktopUpdateStatus,
  DesktopVersionInfo,
  HermesConnection
} from '@/global'
import { checkHermesUpdate, getActionStatus, updateHermes } from '@/hermes'
import { translateNow } from '@/i18n'
import { persistString, storedString } from '@/lib/storage'
import { $connectionsRegistry, refreshConnectionsRegistry } from '@/store/connections'
import { reconnectGateway } from '@/store/gateway-reconnect'
import { dismissNotification, notify } from '@/store/notifications'
import { $connection } from '@/store/session'
import type { BackendUpdateCheckResponse, UpdateReceiptSummary } from '@/types/hermes'

/** Keyed per retired-channel revision: a new retirement (or a revision bump on
 *  the same channel) re-shows the notice, a plain re-check never does. */
const DISCONTINUED_DISMISS_KEY = 'hermes:discontinued-notice-dismissed-for'
const DISCONTINUED_TOAST_ID = 'desktop-build-discontinued'

export interface UpdateApplyState {
  applying: boolean
  stage: DesktopUpdateStage
  message: string
  percent: number | null
  error: string | null
  /** When the stage is 'manual': the exact command the user should run
   *  (CLI install with no staged updater). */
  command: string | null

  log: readonly { stage: DesktopUpdateStage; message: string; at: number }[]
}

const IDLE: UpdateApplyState = {
  applying: false,
  stage: 'idle',
  message: '',
  percent: null,
  error: null,
  command: null,
  log: []
}

export const $desktopVersion = atom<DesktopVersionInfo | null>(null)
export const $updateApply = atom<UpdateApplyState>(IDLE)
export const $updateChecking = atom<boolean>(false)
export const $updateOverlayOpen = atom<boolean>(false)
export const $updateStatus = atom<DesktopUpdateStatus | null>(null)

// Client and backend are independently updatable; each keeps its own state.
export const $backendUpdateStatus = atom<DesktopUpdateStatus | null>(null)
export const $backendUpdateApply = atom<UpdateApplyState>(IDLE)
export const $backendUpdateChecking = atom<boolean>(false)

export type UpdateTarget = 'client' | 'backend'
export const $updateOverlayTarget = atom<UpdateTarget>('client')

export const setUpdateOverlayOpen = (open: boolean) => $updateOverlayOpen.set(open)

export const openUpdateOverlayFor = (target: UpdateTarget): void => {
  $updateOverlayTarget.set(target)
  $updateOverlayOpen.set(true)
  void (target === 'backend' ? checkBackendUpdates({ force: true }) : checkUpdates({ force: true }))
}

export const resetUpdateApplyState = () => {
  $updateApply.set(IDLE)
  $backendUpdateApply.set(IDLE)
}

const UPDATE_TOAST_ID = 'desktop-update-available'
// Time-based snooze instead of per-sha dismissal: this repo lands ~100 commits
// a day, so a "don't show this exact sha again" guard re-popped the toast on
// every new commit. We instead suppress the toast for a cooldown window that
// (re)starts whenever the user closes it.
const UPDATE_TOAST_SNOOZE_KEY = 'hermes:update-toast-snooze-until'
const UPDATE_TOAST_COOLDOWN_MS = 24 * 60 * 60 * 1000

function snoozeUpdateToast(): void {
  persistString(UPDATE_TOAST_SNOOZE_KEY, String(Date.now() + UPDATE_TOAST_COOLDOWN_MS))
}

function isUpdateToastSnoozed(): boolean {
  const until = Number(storedString(UPDATE_TOAST_SNOOZE_KEY) || 0)

  return Number.isFinite(until) && Date.now() < until
}

// Must match tui_gateway's DESKTOP_BACKEND_CONTRACT that this build was written
// against. Legacy backends report their own value in session runtime info; a
// lower value (or none — a pre-GUI checkout) means the backend is older than
// this GUI, a higher value means this GUI is older than the backend. Both
// directions are GUI<->backend skew and both warn — an old GUI silently
// driving a newer backend is just as broken as the reverse, it only fails
// further from the cause. Canonical gateways identify their distinct wire
// protocol instead. That value does not claim the legacy API features listed
// below.
// v2: requires the file.attach RPC (remote-gateway non-image file upload).
// v3: requires approvals.mode config RPCs and session.info reconciliation.
// v4: requires explicit Fast-off session creation and session-scoped Fast edits.
// v5: requires raised WebSocket frame size for large one-shot file.attach.
// v6: requires key-addressed plugins.manage rows (keyless rows render
//     read-only in Settings → Plugins).
// v7: requires JSON-RPC server->client requests for every blocking prompt
//     (approval/clarify/sudo/secret/vault/MCP setup); a v6 backend's
//     `<kind>.request` notifications would never render a card.
export const REQUIRED_BACKEND_CONTRACT = 8
const SKEW_TOAST_ID = 'backend-contract-skew'
const GUI_SKEW_TOAST_ID = 'gui-contract-skew'
// The contract check runs on every session.resume (applyRuntimeInfo), so
// without a snooze the warning re-popped on every thread the user opened, even
// right after they closed it. Mirror the update toast: persist a cooldown when
// the user dismisses it. It still reminds again after the window if the skew
// persists, and clears immediately once the two sides align.
const SKEW_TOAST_SNOOZE_KEY = 'hermes:backend-skew-toast-snooze-until'
const GUI_SKEW_TOAST_SNOOZE_KEY = 'hermes:gui-skew-toast-snooze-until'
const SKEW_TOAST_COOLDOWN_MS = 24 * 60 * 60 * 1000

function snoozeSkewToast(): void {
  persistString(SKEW_TOAST_SNOOZE_KEY, String(Date.now() + SKEW_TOAST_COOLDOWN_MS))
}

function isSkewToastSnoozed(): boolean {
  const until = Number(storedString(SKEW_TOAST_SNOOZE_KEY) || 0)

  return Number.isFinite(until) && Date.now() < until
}

function snoozeGuiSkewToast(): void {
  persistString(GUI_SKEW_TOAST_SNOOZE_KEY, String(Date.now() + SKEW_TOAST_COOLDOWN_MS))
}

function isGuiSkewToastSnoozed(): boolean {
  const until = Number(storedString(GUI_SKEW_TOAST_SNOOZE_KEY) || 0)

  return Number.isFinite(until) && Date.now() < until
}

const INSTALL_METHOD_TOAST_ID = 'install-method-not-supported'
// Same time-based snooze pattern as the update/skew toasts: the warning is
// re-derived from every session.info (session.create/resume/activate all
// route through applyRuntimeInfo), so without a snooze it would re-pop on
// every session switch even right after the user dismissed it.
const INSTALL_METHOD_TOAST_SNOOZE_KEY = 'hermes:install-method-toast-snooze-until'
const INSTALL_METHOD_TOAST_COOLDOWN_MS = 24 * 60 * 60 * 1000

function snoozeInstallMethodToast(): void {
  persistString(INSTALL_METHOD_TOAST_SNOOZE_KEY, String(Date.now() + INSTALL_METHOD_TOAST_COOLDOWN_MS))
}

function isInstallMethodToastSnoozed(): boolean {
  const until = Number(storedString(INSTALL_METHOD_TOAST_SNOOZE_KEY) || 0)

  return Number.isFinite(until) && Date.now() < until
}

/**
 * Guard against GUI<->backend contract skew in either direction. A backend
 * that predates this GUI's contract (e.g. a bb/gui-built app pointed at a
 * `main` checkout) gets a "backend out of date" warning with a one-click
 * align that runs the normal backend update flow. A backend *ahead* of this
 * GUI's contract (typically a long-running app that survived a backend
 * update without relaunching) gets the reverse "app out of date" warning
 * pointing at the client update flow. Without the reverse check an old GUI
 * silently drives a newer backend and fails cryptically downstream.
 *
 * Runs on every session open; closing a toast snoozes it for a cooldown so it
 * doesn't nag on every thread switch.
 */
export function reportBackendContract(contract: number | undefined, protocol?: string): void {
  // A canonical gateway speaks exactly the protocol this build targets. An
  // unknown explicit protocol must not fall back to a legacy version claim, so
  // it reads as an out-of-date backend.
  const reported =
    protocol === undefined ? (contract ?? 0) : protocol === CANONICAL_GATEWAY_PROTOCOL ? REQUIRED_BACKEND_CONTRACT : 0

  if (reported >= REQUIRED_BACKEND_CONTRACT) {
    dismissNotification(SKEW_TOAST_ID)
    // Backend caught up — forget any prior snooze so a future regression warns
    // immediately rather than staying silent for the rest of the window.
    persistString(SKEW_TOAST_SNOOZE_KEY, null)
  }

  if (reported <= REQUIRED_BACKEND_CONTRACT) {
    dismissNotification(GUI_SKEW_TOAST_ID)
    // GUI caught up (or the backend rolled back) — same reset for the reverse
    // direction.
    persistString(GUI_SKEW_TOAST_SNOOZE_KEY, null)
  }

  if (reported < REQUIRED_BACKEND_CONTRACT) {
    if (isSkewToastSnoozed()) {
      return
    }

    notify({
      action: {
        label: translateNow('notifications.updateHermes'),
        onClick: () => {
          snoozeSkewToast()
          void applyBackendUpdate()
        }
      },
      durationMs: 0,
      id: SKEW_TOAST_ID,
      kind: 'warning',
      message: translateNow('notifications.backendOutOfDateMessage'),
      onDismiss: () => snoozeSkewToast(),
      title: translateNow('notifications.backendOutOfDateTitle')
    })

    return
  }

  if (reported > REQUIRED_BACKEND_CONTRACT) {
    if (isGuiSkewToastSnoozed()) {
      return
    }

    notify({
      action: {
        label: translateNow('notifications.updateDesktopApp'),
        onClick: () => {
          snoozeGuiSkewToast()
          openUpdateOverlayFor('client')
        }
      },
      durationMs: 0,
      id: GUI_SKEW_TOAST_ID,
      kind: 'warning',
      message: translateNow('notifications.desktopOutOfDateMessage'),
      onDismiss: () => snoozeGuiSkewToast(),
      title: translateNow('notifications.desktopOutOfDateTitle')
    })
  }
}

export function reportInstallMethodWarning(message: string | undefined): void {
  if (!message) {
    dismissNotification(INSTALL_METHOD_TOAST_ID)

    return
  }

  if (isInstallMethodToastSnoozed()) {
    return
  }

  notify({
    durationMs: 0,
    id: INSTALL_METHOD_TOAST_ID,
    kind: 'warning',
    message,
    onDismiss: () => snoozeInstallMethodToast(),
    title: translateNow('notifications.installMethodUnsupportedTitle')
  })
}

/**
 * Fire a toast when an update is available, at most once per cooldown window.
 * Closing the toast — dismissing it or opening the updates window from it —
 * (re)starts the cooldown, so a busy upstream branch doesn't re-spam the user
 * on every new commit. The snooze is persisted, so it survives relaunches too.
 *
 * `target` is the target whose status produced this toast. The overlay has no
 * target switcher, so a client-status toast that opened the backend overlay
 * showed the user a machine they weren't told about, with no way back.
 */
export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null, target: UpdateTarget = 'client') {
  // Either signal means "update ready": behind > 0 (git checkout) or
  // updateAvailable (shallow clone, App Installer feed).
  if (!status || status.supported === false || status.error) {
    return
  }

  // The package update owner reports availability without a commit SHA.
  // Git checks must still identify their target commit; a native macOS
  // (electron-updater) check names its target by release tag instead.
  const hasTargetIdentity: boolean =
    Boolean(status.targetSha) ||
    Boolean(status.latestTag) ||
    status.mechanism === 'app-installer' ||
    status.mechanism === 'microsoft-store'

  if (!hasTargetIdentity) {
    return
  }

  const behind = typeof status.behind === 'number' ? status.behind : null

  if ((behind ?? 0) <= 0 && !status.updateAvailable) {
    return
  }

  if (isUpdateToastSnoozed()) {
    return
  }

  if ($updateApply.get().applying) {
    return
  }

  notify({
    action: {
      label: translateNow('notifications.seeWhatsNew'),
      onClick: () => {
        snoozeUpdateToast()
        openUpdateOverlayFor(target)
      }
    },
    durationMs: 0,
    icon: 'gift',
    id: UPDATE_TOAST_ID,
    kind: 'info',
    message:
      status.mechanism === 'app-installer'
        ? translateNow('notifications.updateReadyMessageAppInstaller')
        : behind !== null && behind > 0
          ? translateNow('notifications.updateReadyMessage', behind)
          : translateNow('notifications.updateReadyMessageUnknown'),
    onDismiss: () => snoozeUpdateToast(),
    title: translateNow('notifications.updateReadyTitle')
  })
}

/** Which retired-channel revision the discontinued notice was dismissed for. */
function discontinuedDismissKey(retirement: NonNullable<DesktopUpdateStatus['retirement']>): string {
  return `${retirement.destination}@${retirement.version}`
}

/** Persist the dismissal so plain re-checks never nag; a new retirement re-shows. */
export function dismissDiscontinuedNotice(retirement: NonNullable<DesktopUpdateStatus['retirement']>): void {
  persistString(DISCONTINUED_DISMISS_KEY, discontinuedDismissKey(retirement))
  dismissNotification(DISCONTINUED_TOAST_ID)
}

/**
 * The discontinued retirement tier surfaces as a warning toast on check — no
 * download is ever offered. Suppressed once dismissed for this channel
 * revision; a fresh retirement re-notifies.
 */
function maybeNotifyDiscontinued(retirement: NonNullable<DesktopUpdateStatus['retirement']>): void {
  if (retirement.state !== 'discontinued') {
    return
  }

  if (storedString(DISCONTINUED_DISMISS_KEY) === discontinuedDismissKey(retirement)) {
    return
  }

  notify({
    action: {
      label: translateNow('notifications.seeWhatsNew'),
      onClick: () => openUpdateOverlayFor('client')
    },
    durationMs: 0,
    icon: 'warning',
    id: DISCONTINUED_TOAST_ID,
    kind: 'warning',
    message: translateNow('updates.discontinuedBody'),
    onDismiss: () => dismissDiscontinuedNotice(retirement),
    title: translateNow('updates.discontinuedTitle')
  })
}

/** The target a generic, surface-less update command acts on: the machine the
 *  user is connected to. Surfaces that display one target's status must pass
 *  that target explicitly instead of inheriting this. */
function activeUpdateTarget(): UpdateTarget {
  return isRemoteMode() ? 'backend' : 'client'
}

/**
 * Open the updates overlay and kick off its check.
 *
 * Callers tied to a specific status surface pass its target; only genuinely
 * generic entry points take the connection-mode default. The macOS "Check for
 * Updates…" menu item is the former — it is the OS-standard affordance for
 * updating *this app*, so in remote mode it checked the wrong machine and the
 * Mac client silently drifted behind (#70266).
 */
export function openUpdatesWindow(target: UpdateTarget = activeUpdateTarget()): void {
  openUpdateOverlayFor(target)
}

/**
 * Start applying the available update for the active target right away. Opens
 * the updates overlay first so the user sees apply progress (the overlay
 * renders ApplyingView once `applying` flips true), then kicks off the install.
 * Used by the "Update now" affordance on the About panel, which would otherwise
 * only be able to open the changelog overlay.
 *
 * Multi-target installs (remote mode / multi-connection registry) route
 * through the everything-flow so "update" means every machine, not just the
 * active target — the single-target ternary is what left remote-mode users
 * updating the backend forever while the GUI itself went stale.
 *
 * An explicit `target` opts out of both: the caller is acting on one named
 * machine's status and must not fan out to the others.
 */
export function startActiveUpdate(target?: UpdateTarget): void {
  if (!target && hasMultipleUpdateTargets()) {
    $updateOverlayOpen.set(true)
    void applyEverythingUpdate()

    return
  }

  const effective = target ?? activeUpdateTarget()
  $updateOverlayTarget.set(effective)
  $updateOverlayOpen.set(true)
  void (effective === 'backend' ? applyBackendUpdate() : applyUpdates())
}

/**
 * Command-palette entry point. The About panel's "Update now" only renders once
 * we know an update is waiting; this row is always listed, so it also has to
 * handle "already current" — open the overlay for the active target and let its
 * check answer, and only apply when there's something to install. On
 * multi-target installs an update waiting on EITHER the client or the backend
 * triggers the everything-flow.
 */
export function requestActiveUpdate(): void {
  if (hasMultipleUpdateTargets()) {
    const clientStatus = $updateStatus.get()
    const backendStatus = $backendUpdateStatus.get()

    const anyBehind =
      (clientStatus?.behind ?? 0) > 0 ||
      clientStatus?.updateAvailable ||
      (backendStatus?.behind ?? 0) > 0 ||
      backendStatus?.updateAvailable

    if (anyBehind) {
      startActiveUpdate()

      return
    }
  }

  const target = activeUpdateTarget()
  const status = target === 'backend' ? $backendUpdateStatus.get() : $updateStatus.get()

  if ((status?.behind ?? 0) > 0 || status?.updateAvailable) {
    startActiveUpdate(target)

    return
  }

  openUpdateOverlayFor(target)
}

// Only the newest getVersion may publish, and only while the request scope
// (connection + profile) is unchanged. A profile switch moves $apiRequestScope
// without replacing $connection, so the connection identity alone is not enough.
let versionRequestSeq = 0

function versionScopeKey(): string {
  const { connectionId, profile } = $apiRequestScope.get()

  return `${connectionKey($connection.get())}|${connectionId ?? ''}|${profile ?? ''}`
}

/** Refresh the active gateway version and the desktop's build metadata. */
export async function refreshDesktopVersion(): Promise<DesktopVersionInfo | null> {
  if (typeof window === 'undefined') {
    return null
  }

  // Best-effort UI sync: callers (checkUpdates, startUpdatePoller, window
  // focus handler) all kick this off with `void refreshDesktopVersion()`,
  // so any rejection from the IPC bridge (e.g. main process shutting down
  // mid-reload, or the bridge not yet ready on first paint) would surface
  // as an unhandled promise rejection in the renderer. Swallow it.
  try {
    const seq = ++versionRequestSeq
    const scope = versionScopeKey()
    const next = await window.hermesDesktop?.getVersion?.({ ...connectionScoped(), ...profileScoped() })

    // Superseded, or the scope moved while in flight: the scope listener has
    // already asked again for the new target.
    if (seq !== versionRequestSeq || versionScopeKey() !== scope) {
      return null
    }

    if (next) {
      $desktopVersion.set(next)
    }

    return next ?? null
  } catch {
    return null
  }
}

function isRemoteMode(): boolean {
  return $connection.get()?.mode === 'remote'
}

export function mapBackendCheck(res: BackendUpdateCheckResponse): DesktopUpdateStatus {
  // The producer's contract (web_routers/actions.py): behind is 0 = up to
  // date, -1 = update available but the count is unknown (shallow clone
  // without a merge-base, unusable GitHub compare), null = the check could
  // not run at all. DesktopUpdateStatus types "unknown count" as null —
  // "never render it as a literal number" — so pass that through instead of
  // clamping the sentinel to a byte-identical copy of "up to date".
  const behind = res.behind === undefined ? 0 : res.behind

  // `behind: null` from a supported (git) backend is the endpoint's "the check
  // could not run" answer (GitHub unreachable, rate limited, offline) and
  // carries the explanation in `message`. Folding it to 0 made the overlay
  // report "the backend is on the latest version" whenever the check failed,
  // and hid that message. Surface the failure state the local check path
  // already uses so the overlay shows the reason and a retry; only a check
  // that actually ran may claim there is nothing to update. Backends that
  // cannot self-update also answer `behind: null`, but `can_apply: false`
  // renders the unsupported copy first — those must not become failures.
  const checkFailed = res.can_apply && res.behind === null

  return {
    supported: res.can_apply,
    error: checkFailed ? 'check-failed' : undefined,
    message: res.message ?? undefined,
    updateAvailable: res.update_available,
    rollback: Boolean(res.rollback_to),
    held: res.held ?? undefined,
    sourceVersion: res.rollback_to ?? (res.held ? res.source_version : undefined) ?? undefined,
    behind: behind === null || behind < 0 ? null : behind,
    currentVersion: res.current_version,
    channel: res.channel,
    branch: res.branch ?? undefined,
    latestTag: res.source_version && !res.rollback_to ? `v${res.source_version}` : undefined,
    targetSha: res.update_available ? `backend:${res.current_version}` : undefined,
    commits: res.commits,
    fetchedAt: Date.now()
  }
}

/** Only explicit user checks and post-update refreshes bypass the caches. */
export interface UpdateCheckOptions {
  force?: boolean
}

// Key of the connection that wants the next check once the in-flight one
// (if any) clears — set when a check is requested while another is already
// running for a different target, so that target isn't silently dropped.
let backendCheckPendingKey: string | undefined

export async function checkBackendUpdates({
  force = false
}: UpdateCheckOptions = {}): Promise<DesktopUpdateStatus | null> {
  if (!isRemoteMode()) {
    return $backendUpdateStatus.get()
  }

  // Bind this request to the connection active when it started. Switching
  // remote targets mid-request must not let a slower, now-stale response
  // (for the connection we've since left) overwrite the newer one.
  const requestKey = connectionKey($connection.get())

  if ($backendUpdateChecking.get()) {
    backendCheckPendingKey = requestKey

    return $backendUpdateStatus.get()
  }

  $backendUpdateChecking.set(true)

  try {
    const status = mapBackendCheck(await checkHermesUpdate(force))

    if (connectionKey($connection.get()) === requestKey) {
      $backendUpdateStatus.set(status)
      maybeNotifyUpdateAvailable(status, 'backend')
    }

    return status
  } catch (error) {
    const fallback: DesktopUpdateStatus = {
      supported: $backendUpdateStatus.get()?.supported ?? true,
      error: 'check-failed',
      message: error instanceof Error ? error.message : String(error),
      fetchedAt: Date.now()
    }

    if (connectionKey($connection.get()) === requestKey) {
      $backendUpdateStatus.set(fallback)
    }

    return fallback
  } finally {
    $backendUpdateChecking.set(false)

    const pendingKey = backendCheckPendingKey

    backendCheckPendingKey = undefined

    // Someone asked for a check for a different (still-active) target while
    // this one was in flight — run it now instead of leaving that target
    // showing whatever this request happened to return.
    if (pendingKey && pendingKey !== requestKey && pendingKey === connectionKey($connection.get())) {
      void checkBackendUpdates()
    }
  }
}

export async function checkUpdates({ force = false }: UpdateCheckOptions = {}): Promise<DesktopUpdateStatus | null> {
  const bridge = window.hermesDesktop?.updates

  if (!bridge || $updateChecking.get()) {
    return $updateStatus.get()
  }

  $updateChecking.set(true)

  try {
    const status = await bridge.check({ force })
    $updateStatus.set(status)

    if (status.retirement) {
      maybeNotifyDiscontinued(status.retirement)
    }

    maybeNotifyUpdateAvailable(status, 'client')
    void refreshDesktopVersion()

    return status
  } catch (error) {
    const previous = $updateStatus.get()

    const fallback: DesktopUpdateStatus = {
      supported: previous?.supported ?? true,
      branch: previous?.branch,
      error: 'check-failed',
      message: error instanceof Error ? error.message : String(error),
      fetchedAt: Date.now()
    }

    $updateStatus.set(fallback)

    return fallback
  } finally {
    $updateChecking.set(false)
  }
}

export type SourceUpdateChannel = 'main' | 'stable'

/** What a source checkout follows, for display; null where a package owns the channel. */
export type SourceUpdateTrack = { kind: 'stable' } | { kind: 'main' } | { kind: 'branch'; name: string }

export function sourceUpdateTrack(status: DesktopUpdateStatus | null): SourceUpdateTrack | null {
  if (!status?.supported || (status.mechanism !== 'posix-handoff' && status.mechanism !== 'windows-handoff')) {
    return null
  }

  if (status.channel === 'stable') {
    return { kind: 'stable' }
  }

  if (status.channel !== undefined || !status.branch) {
    return null
  }

  return status.branch === 'main' ? { kind: 'main' } : { kind: 'branch', name: status.branch }
}

/**
 * The selectable channel of a source checkout, or null where the selector must not
 * appear: packages own their channel, runtimes older than the flag cannot save one,
 * and a custom branch is neither stable releases nor every commit on main.
 */
export function sourceUpdateChannel(status: DesktopUpdateStatus | null): SourceUpdateChannel | null {
  const source = status?.mechanism === 'posix-handoff' || status?.mechanism === 'windows-handoff'

  if (!status?.supported || !source || !status.channelSelectable) {
    return null
  }

  if (status.channel === 'stable') {
    return 'stable'
  }

  return status.channel === undefined && status.branch === 'main' ? 'main' : null
}

/**
 * Persist the source checkout's channel; the reply is a fresh check against it.
 * An unreachable release still returns a status naming the saved channel.
 */
export async function setUpdateChannel(channel: SourceUpdateChannel): Promise<DesktopUpdateStatus> {
  const setChannel = window.hermesDesktop?.updates?.setChannel

  if (!setChannel) {
    throw new Error('This installation cannot change its update channel.')
  }

  $updateChecking.set(true)

  try {
    const status = await setChannel(channel)
    $updateStatus.set(status)
    maybeNotifyUpdateAvailable(status, 'client')

    return status
  } finally {
    $updateChecking.set(false)
  }
}

export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promise<DesktopUpdateApplyResult> {
  if ($updateStatus.get()?.retirement) {
    openUpdateOverlayFor('client')

    return { ok: false, error: 'retirement-blocked' }
  }

  const bridge = window.hermesDesktop?.updates

  if (!bridge) {
    return { ok: false, error: 'unavailable', message: 'Desktop bridge unavailable.' }
  }

  dismissNotification(UPDATE_TOAST_ID)
  $updateApply.set({ ...IDLE, applying: true, stage: 'prepare', message: 'Starting update…' })

  try {
    const result = await bridge.apply(opts)

    // CLI install with no staged updater: not an error — the user just runs
    // `hermes update` themselves. Land on a dedicated manual state so the
    // overlay shows the command + copy button instead of a dead retry loop.
    if (result?.manual) {
      $updateApply.set({
        ...IDLE,
        applying: false,
        stage: 'manual',
        message: result.message ?? result.command ?? 'hermes update',
        command: result.command ?? 'hermes update'
      })

      return result
    }

    // A detached relauncher took over (macOS bundle swap / Linux re-exec): the
    // app is about to quit and reopen, so hold the "Restarting…" view until it
    // does. Every other resolved outcome MUST land on a terminal, closeable
    // state: the apply IPC resolves here, but the progress stream may have left
    // us on a non-terminal stage (e.g. 'done'/'rebuild'), which renders as a
    // spinner with no close button — the exact hang this guards against.
    // Linux GUI/backend skew (#45205): the backend was updated but the running
    // desktop app PACKAGE was not changed (AppImage/.deb/.rpm). We must NOT tell
    // the user "the new version loads next launch" — that's false; this packaged
    // shell keeps running old GUI code against the new backend. Land on the
    // dedicated, closeable guiSkew terminal state telling them to update/reinstall
    // the desktop app.
    if (result?.guiSkew) {
      $updateApply.set({
        ...IDLE,
        applying: false,
        stage: 'guiSkew',
        message: result.message ?? translateNow('updates.guiSkewBody')
      })

      return result
    }

    // Backend updated but the app couldn't auto-relaunch (e.g. the rebuilt
    // sandbox helper isn't launchable): keep a closeable manual-restart state so
    // the user keeps a working window instead of a dead app or a stuck spinner.
    if (result?.ok && result?.manualRestart) {
      $updateApply.set({
        ...IDLE,
        applying: false,
        stage: 'manual',
        message: result.message ?? translateNow('updates.manualPickedUp')
      })

      return result
    }

    if (!result?.handedOff) {
      if (result?.ok) {
        // Updated, but couldn't relaunch in place (AppImage / dev run). Dismiss
        // the overlay and let the user know the new version loads next launch
        // rather than stranding them on an un-closeable spinner.
        setUpdateOverlayOpen(false)
        resetUpdateApplyState()

        if (result.updateAvailable === false) {
          return result
        }

        notify({
          durationMs: 8000,
          id: UPDATE_TOAST_ID,
          kind: 'success',
          message: translateNow('updates.manualPickedUp'),
          // No action button here, but it's still update-lifecycle news — keep
          // it with the other update toasts instead of the ambient bottom-right
          // stack.
          placement: 'default',
          title: translateNow('updates.allSetTitle')
        })
      } else {
        $updateApply.set({
          ...$updateApply.get(),
          applying: false,
          stage: 'error',
          error: result?.error ?? 'apply-failed',
          message: result?.message ?? translateNow('updates.errorBody')
        })
      }
    }

    return result
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error)
    $updateApply.set({ ...$updateApply.get(), applying: false, stage: 'error', error: 'apply-failed', message })

    return { ok: false, error: 'apply-failed', message }
  }
}

const BACKEND_ACTION_POLL_MS = 1500
const BACKEND_ACTION_MAX_MS = 6 * 60 * 1000
const BACKEND_RETURN_MAX_MS = 4 * 60 * 1000

// C3: a committed update succeeds even when post-commit steps are still owed,
// and a partial one (committed, but the user must act) still owes them. Name
// every owed step of THIS action's committed run whatever the exit: follow-ups
// with the rerun remedy, a user action with the producer's own instruction,
// verbatim (a rerun does not restore a parked stash).
function owedMessage(receipt: UpdateReceiptSummary | undefined, actionId: string | undefined): string | null {
  const debt = updateDebt(receipt, actionId)

  if (!debt) {
    return null
  }

  return [debt.followups && translateNow('updates.applyStatus.owed', debt.followups), debt.userAction]
    .filter(Boolean)
    .join(' ')
}

// A failed apply whose receipt still proves a committed partial run (exit 1)
// names what that run owes instead of only "failed" / "did not come back".
function failBackendApply(
  fallback: { shown: string; result: string },
  status: { receipt?: UpdateReceiptSummary } | null,
  actionId: string | undefined
): DesktopUpdateApplyResult {
  const owed = owedMessage(status?.receipt, actionId)
  const message = owed ? `${translateNow('updates.applyStatus.failed')} ${owed}` : fallback.shown

  $backendUpdateApply.set({
    ...$backendUpdateApply.get(),
    applying: false,
    stage: 'error',
    error: 'apply-failed',
    message
  })

  return { ok: false, error: 'apply-failed', message: owed ? message : fallback.result }
}

function finishBackendApply(
  returned: boolean,
  receipt?: UpdateReceiptSummary,
  actionId?: string
): DesktopUpdateApplyResult {
  if (returned) {
    $backendUpdateApply.set(IDLE)
    setUpdateOverlayOpen(false)
    void checkBackendUpdates({ force: true })
    // The update restarted the gateway process, which strands this window's
    // WebSocket: over SSH/tailscale tunnels the old TCP connection often dies
    // without a close event, so connectionState still reads 'open' while every
    // RPC hangs — users force-quit the app to recover. Nudge the registered
    // reconnect handler (forceReconnectNow), which retires the half-open
    // socket and re-dials with a fresh ticket. Best-effort: local installs
    // whose socket survived treat it as a cheap probe.
    void reconnectGateway().catch(() => undefined)
    // The backend caught up, but the CLIENT may still be behind — the exact
    // gap that strands remote-mode users on an old GUI forever (every update
    // affordance in remote mode targets the backend, so nothing ever told
    // them the app itself was stale). Nudge with a one-click client update.
    void maybeNudgeClientAfterBackendUpdate()
    const owed = owedMessage(receipt, actionId)

    if (owed) {
      notify({ durationMs: 0, kind: 'warning', message: owed })

      return { ok: true, message: owed }
    }

    return { ok: true, message: 'Backend update applied.' }
  }

  return failBackendApply(
    { shown: translateNow('updates.applyStatus.noReturn'), result: 'Backend did not come back online.' },
    { receipt },
    actionId
  )
}

function ingestBackendActionStatus(status: Awaited<ReturnType<typeof getActionStatus>>): void {
  const current = $backendUpdateApply.get()

  const log = status.lines
    .filter(line => line.trim().length > 0)
    .map(line => ({ at: Date.now(), message: line, stage: current.stage }))
    .slice(-50)

  const latest = log.at(-1)?.message

  if (log.length === 0 && !latest) {
    return
  }

  $backendUpdateApply.set({
    ...current,
    log,
    message: latest ?? current.message
  })
}

function completedAfterRestart(
  status: Awaited<ReturnType<typeof getActionStatus>>,
  actionId: string | undefined
): boolean {
  return !!actionId && status.lines.some(line => line === `=== hermes-update completed ${actionId} ===`)
}

/** Whether the durable update receipt attached to the status proves the
 *  outcome of THIS apply (#91277 bullet 3). Only a finished receipt whose
 *  run started at-or-after we kicked the update off counts — an older
 *  receipt describes a previous update, and a still-running one proves
 *  nothing yet. The 60s slack absorbs client/backend clock skew. */
function receiptProvesOutcome(
  status: Awaited<ReturnType<typeof getActionStatus>>,
  applyStartedAtMs: number,
  actionId: string | undefined
): boolean {
  const receipt = status.receipt

  if (!receipt || !receipt.finished_at || !receipt.started_at) {
    return false
  }

  if (receipt.outcome !== 'success' && receipt.outcome !== 'partial' && receipt.outcome !== 'failed') {
    return false
  }

  // A backend that records the writing action (null for a CLI run) proves
  // identity directly: another action's success cannot certify this one.
  if (actionId && receipt.action_id !== undefined) {
    return receipt.action_id === actionId
  }

  const startedMs = Date.parse(receipt.started_at)

  return Number.isFinite(startedMs) && startedMs >= applyStartedAtMs - 60_000
}

function legacyBackendReachedTarget(
  status: BackendUpdateCheckResponse,
  targetSha: string | undefined,
  previousVersion: string | undefined
): boolean {
  if (status.behind === 0) {
    return true
  }

  if (previousVersion && status.current_version !== previousVersion) {
    return true
  }

  return !!targetSha && !!status.commits?.length && !status.commits.some(commit => commit.sha === targetSha)
}

let backendUpdateInFlight: Promise<DesktopUpdateApplyResult> | null = null

async function runBackendUpdate(): Promise<DesktopUpdateApplyResult> {
  dismissNotification(UPDATE_TOAST_ID)
  $backendUpdateApply.set({
    ...IDLE,
    applying: true,
    stage: 'prepare',
    message: translateNow('updates.applyStatus.preparing')
  })

  try {
    const previousStatus = $backendUpdateStatus.get()
    const requestedTargetSha = previousStatus?.commits?.at(0)?.sha

    const previousVersion = previousStatus?.targetSha?.startsWith('backend:')
      ? previousStatus.targetSha.slice('backend:'.length)
      : undefined

    const started = await updateHermes()
    const applyStartedAtMs = Date.now()

    if (!started.ok) {
      const message = (started as { message?: string }).message || translateNow('updates.applyStatus.notAvailable')
      // An empty update_command is the backend saying "there is no command to
      // run here" (managed container, commit build) — render the message-only
      // view. Only a field absent from an older backend falls back.
      const command = ((started as { update_command?: string | null }).update_command ?? 'hermes update') || null
      $backendUpdateApply.set({ ...IDLE, applying: false, stage: 'manual', message, command })

      return { ok: false, error: 'manual', manual: true, message, command: command ?? undefined }
    }

    $backendUpdateApply.set({
      ...IDLE,
      applying: true,
      stage: 'pull',
      message: translateNow('updates.applyStatus.pulling')
    })

    let last: Awaited<ReturnType<typeof getActionStatus>> | null = null
    // Backups, dependency repair, and builds can legitimately take several
    // minutes. Keep the generous cap only as a guard against a stuck action.
    const actionDeadline = Date.now() + BACKEND_ACTION_MAX_MS
    let deadline = actionDeadline
    let reconnecting = false

    while (Date.now() < deadline) {
      await new Promise(resolve => globalThis.setTimeout(resolve, BACKEND_ACTION_POLL_MS))

      try {
        last = await getActionStatus(started.name, 2000)
        ingestBackendActionStatus(last)
      } catch {
        if (!reconnecting) {
          reconnecting = true
          deadline = Date.now() + BACKEND_RETURN_MAX_MS
          $backendUpdateApply.set({
            ...$backendUpdateApply.get(),
            applying: true,
            stage: 'restart',
            message: translateNow('updates.applyStatus.restarting')
          })
        }

        continue
      }

      if (last.running) {
        if (reconnecting) {
          reconnecting = false
          deadline = actionDeadline
          $backendUpdateApply.set({
            ...$backendUpdateApply.get(),
            applying: true,
            stage: 'pull',
            message: translateNow('updates.applyStatus.pulling')
          })
        }

        continue
      }

      if (last.exit_code === 0 || (last.exit_code === null && completedAfterRestart(last, started.action_id))) {
        return finishBackendApply(true, last.receipt, started.action_id)
      }

      // #91277 bullet 3: the backend now attaches the durable update
      // receipt to the status. A receipt whose run STARTED after we kicked
      // this update off is authoritative — read its outcome instead of
      // inferring from log markers or timing out across the restart gap.
      if (last.exit_code === null && receiptProvesOutcome(last, applyStartedAtMs, started.action_id)) {
        return finishBackendApply(last.receipt!.outcome === 'success', last.receipt, started.action_id)
      }

      if (!started.action_id && last.exit_code === null) {
        try {
          const status = await checkHermesUpdate(true)

          if (legacyBackendReachedTarget(status, requestedTargetSha, previousVersion)) {
            return finishBackendApply(true)
          }
        } catch {
          continue
        }
      }

      if (last.exit_code !== null) {
        break
      }
    }

    return failBackendApply(
      { shown: translateNow('updates.applyStatus.failed'), result: 'Backend update failed.' },
      last,
      started.action_id
    )
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error)
    $backendUpdateApply.set({
      ...$backendUpdateApply.get(),
      applying: false,
      stage: 'error',
      error: 'apply-failed',
      message
    })

    return { ok: false, error: 'apply-failed', message }
  }
}

export function applyBackendUpdate(): Promise<DesktopUpdateApplyResult> {
  if (backendUpdateInFlight) {
    return backendUpdateInFlight
  }

  backendUpdateInFlight = runBackendUpdate().finally(() => {
    backendUpdateInFlight = null
  })

  return backendUpdateInFlight
}

// ── Update everything: the client + every registered backend in one action ──
//
// Remote-mode installs update on two (or more) clocks: the GUI app on this
// machine, the connected backend, and any other registered sources. Each has
// its own updater, and before this flow existed every remote-mode affordance
// targeted only the backend — so users "updated" and stayed on a stale GUI.
// This orchestration drives all of them:
//   1. The ACTIVE backend (remote mode) through the detailed-progress path.
//   2. Every OTHER eligible registered connection via the Electron fan-out
//      (cloud rows are platform-managed and report as skipped).
//   3. The local client LAST — its apply relaunches or hands off the app, so
//      it must not preempt the dispatches above.

const CLIENT_BEHIND_TOAST_ID = 'client-update-after-backend'

/** After a successful backend update, tell the user when the desktop app
 *  itself is still behind, with a one-click client update. Silent when the
 *  client is current, so aligned installs never see it. */
async function maybeNudgeClientAfterBackendUpdate(): Promise<void> {
  if (typeof window === 'undefined') {
    return
  }

  const status = (await checkUpdates({ force: true }).catch((): null => null)) ?? $updateStatus.get()

  if (!status || status.error || (!status.updateAvailable && (status.behind ?? 0) <= 0)) {
    return
  }

  notify({
    action: {
      label: translateNow('updates.clientAlsoBehindAction'),
      onClick: () => {
        dismissNotification(CLIENT_BEHIND_TOAST_ID)
        $updateOverlayTarget.set('client')
        $updateOverlayOpen.set(true)
        void applyUpdates()
      }
    },
    durationMs: 0,
    id: CLIENT_BEHIND_TOAST_ID,
    kind: 'warning',
    message: translateNow('updates.clientAlsoBehindMessage'),
    title: translateNow('updates.clientAlsoBehindTitle')
  })
}

export interface UpdateEverythingState {
  running: boolean
}

export const $updateEverything = atom<UpdateEverythingState>({ running: false })

/** True when this install has more than one update target — a remote-mode
 *  window (backend + client) or a multi-connection registry. Gates the
 *  "Update everything" affordance so single-machine installs keep the
 *  one-button experience. */
export function hasMultipleUpdateTargets(): boolean {
  return isRemoteMode() || ($connectionsRegistry.get()?.connections.length ?? 0) > 1
}

let updateEverythingInFlight: Promise<void> | null = null

export function applyEverythingUpdate(): Promise<void> {
  if (updateEverythingInFlight) {
    return updateEverythingInFlight
  }

  updateEverythingInFlight = runEverythingUpdate().finally(() => {
    updateEverythingInFlight = null
  })

  return updateEverythingInFlight
}

async function runEverythingUpdate(): Promise<void> {
  $updateEverything.set({ running: true })

  // Snapshot the client status before any leg runs: the backend leg's own
  // post-update nudge re-checks the client and overwrites `$updateStatus`,
  // including with an error row when the bridge is unreachable. Step 3 needs a
  // pre-flow value to fall back on when its own live check can't answer.
  const cachedClientStatus = $updateStatus.get()

  try {
    // 1. Active backend first (remote mode), with the detailed overlay flow.
    //    Its own finish path re-checks and nudges, but the everything-flow
    //    continues regardless of the outcome: one unreachable backend must
    //    not strand the other machines or the client.
    if (isRemoteMode()) {
      $updateOverlayTarget.set('backend')

      await applyBackendUpdate().catch(() => null)
    }

    // 2. Fan out to every OTHER eligible registered connection. The active
    //    backend was just updated (excluded), and the local runtime updates
    //    with the client in step 3 (excluded). No registry/bridge → skip.
    const bridge = window.hermesDesktop?.connections
    const registry = $connectionsRegistry.get() ?? (await refreshConnectionsRegistry().catch(() => null))
    const excludeIds = ['local']
    const activeConnectionId = $connection.get()?.connectionId

    if (isRemoteMode() && activeConnectionId && !excludeIds.includes(activeConnectionId)) {
      excludeIds.push(activeConnectionId)
    }

    const remaining = (registry?.connections ?? []).filter(connection => !excludeIds.includes(connection.id))

    if (bridge?.updateAll && remaining.length > 0) {
      try {
        const { results } = await bridge.updateAll({ excludeIds })

        for (const row of results) {
          if (row.ok) {
            notify({ title: row.label, message: row.detail || translateNow('updates.everythingDispatched') })
          } else if (row.skipped) {
            notify({
              title: row.label,
              message: row.detail || row.reason || translateNow('updates.everythingSkipped')
            })
          } else {
            notify({
              kind: 'warning',
              title: row.label,
              message: row.error || row.detail || translateNow('updates.everythingRowFailed')
            })
          }
        }
      } catch (error) {
        notify({
          kind: 'warning',
          title: translateNow('updates.everythingFanoutFailedTitle'),
          message: error instanceof Error ? error.message : String(error)
        })
      }
    }

    // 3. The client last — its apply relaunches or hands off the app, so it
    //    must come after every dispatch above. Skipped when already current.
    //    Re-check rather than trusting `$updateStatus`: the cached value can be
    //    up to a poll interval (24h) old and was captured BEFORE the backend
    //    update above, so a cached `behind: 0` would skip the client leg and
    //    leave the app stale — the exact failure this flow exists to prevent.
    //    `checkUpdates()` resolves with an error-status rather than rejecting,
    //    so fall back to the pre-flow snapshot when the live check can't answer.
    const freshClientStatus = await checkUpdates({ force: true }).catch((): null => null)
    const clientStatus = freshClientStatus?.error ? cachedClientStatus : (freshClientStatus ?? cachedClientStatus)

    if ((clientStatus?.behind ?? 0) > 0 || clientStatus?.updateAvailable) {
      $updateOverlayTarget.set('client')
      $updateOverlayOpen.set(true)
      await applyUpdates()
    }
  } finally {
    $updateEverything.set({ running: false })
  }
}

function ingestProgress(payload: DesktopUpdateProgress): void {
  const current = $updateApply.get()
  const log = [...current.log, { stage: payload.stage, message: payload.message, at: payload.at }].slice(-50)

  const terminal =
    payload.stage === 'error' ||
    payload.stage === 'restart' ||
    payload.stage === 'manual' ||
    payload.stage === 'guiSkew'

  $updateApply.set({
    applying: !terminal,
    stage: payload.stage,
    message: payload.message,
    // Streamed log lines carry percent: null; keep the last milestone percent
    // (10/60/…) instead of resetting the bar to indeterminate on every line.
    percent: payload.percent ?? current.percent,
    error: payload.error,
    // 'manual' carries the command to run in its message field.
    command: payload.stage === 'manual' ? payload.message : current.command,
    log
  })
}

let pollerStarted = false
let backgroundTimer: ReturnType<typeof setInterval> | null = null
let connectionUnsub: (() => void) | null = null
let lastConnectionKey: string | undefined
let versionScopeUnsub: (() => void) | null = null
let lastVersionScopeKey: string | undefined

// mode alone can't tell two remote backends apart — switching directly from
// remote profile A to remote profile B leaves mode === 'remote' both times.
// Key on the actual backend target so a target change re-checks even when
// the mode doesn't. Pooled profiles share a baseUrl, so the profile joins
// the key: the update check is profile-scoped (per-profile overrides can
// pin a different channel/branch).
function connectionKey(conn: HermesConnection | null): string {
  if (conn?.mode !== 'remote') {
    return String(conn?.mode)
  }

  return conn.profile ? `remote:${conn.baseUrl}:${conn.profile}` : `remote:${conn.baseUrl}`
}

export const BACKGROUND_UPDATE_CHECK_MS = 24 * 60 * 60 * 1000
const FOCUS_RECHECK_KEY = 'hermes.updates.last-passive-check'

function passiveCheckDue(now: number): boolean {
  const last = Number(storedString(FOCUS_RECHECK_KEY) ?? 0)

  return !Number.isFinite(last) || now - last >= BACKGROUND_UPDATE_CHECK_MS
}

function runPassiveChecks(): void {
  persistString(FOCUS_RECHECK_KEY, String(Date.now()))
  void checkUpdates()
  void checkBackendUpdates()
}

/** Wire up background polling + progress streaming. Idempotent. */
export function startUpdatePoller(): void {
  if (pollerStarted || typeof window === 'undefined') {
    return
  }

  const bridge = window.hermesDesktop?.updates

  if (!bridge) {
    return
  }

  pollerStarted = true
  runPassiveChecks()
  lastVersionScopeKey = versionScopeKey()
  void refreshDesktopVersion()
  bridge.onProgress(ingestProgress)

  // The poller starts at mount, before the gateway connects — so the first
  // backend check above sees mode≠remote and no-ops. Re-check once the
  // connection resolves to remote, and again whenever the remote target
  // itself changes (switching between two remote profiles).
  connectionUnsub = $connection.subscribe((conn: HermesConnection | null): void => {
    const key = connectionKey(conn)

    if (key === lastConnectionKey) {
      return
    }

    lastConnectionKey = key

    if (conn?.mode === 'remote') {
      void checkBackendUpdates()
    }
  })

  // The reported version belongs to the request scope, local or remote. Watch
  // both stores: a profile switch changes $apiRequestScope but not $connection.
  const onVersionScope = (): void => {
    const key = versionScopeKey()

    if (key === lastVersionScopeKey) {
      return
    }

    lastVersionScopeKey = key
    void refreshDesktopVersion()
  }

  const unsubScope = $apiRequestScope.listen(onVersionScope)
  const unsubConnection = $connection.listen(onVersionScope)

  versionScopeUnsub = () => {
    unsubScope()
    unsubConnection()
  }

  window.addEventListener('focus', onFocus)
  backgroundTimer = setInterval(runPassiveChecks, BACKGROUND_UPDATE_CHECK_MS)
}

export function stopUpdatePoller(): void {
  if (backgroundTimer !== null) {
    clearInterval(backgroundTimer)
    backgroundTimer = null
  }

  connectionUnsub?.()
  connectionUnsub = null
  versionScopeUnsub?.()
  versionScopeUnsub = null
  lastConnectionKey = undefined
  lastVersionScopeKey = undefined
  versionRequestSeq++
  window.removeEventListener('focus', onFocus)
  pollerStarted = false
}

function onFocus(): void {
  void refreshDesktopVersion()

  if (passiveCheckDue(Date.now())) {
    runPassiveChecks()
  }
}