Skip to content

AI, fully local on your computer.

92.9 KB
Raw Blame
import { useEffect, useMemo, useRef, useState } from 'react'
import { Badge, Banner, Button, ConfirmDialog, EmptyState, EngineProblemNotice, ErrorBanner, KnowledgePackToolsDialog, OcrInstallControl, OcrInstallDialog, Progress, SegmentedControl, Spinner, useToast, type BadgeTone, type EngineProblemReinstall } from '../components'
import {
  availableFamilies,
  groupModelVariants,
  matchesLibraryView,
  matchesModelSearch,
  modelTask,
  newerAppRows,
  variantGroupOrder,
  type ModelTask,
  type ModelVariantGroup
} from '../lib/modelLibrary'
import {
  isModelInstalled,
  orderPickerModels
} from '../lib/modelAvailability'
import { EngineConfirmDialog } from '../components/EngineConfirmDialog'
import { computeDownloadGate } from '../lib/downloadGate'
import { friendlyIpcError, runAndSurface } from '../lib/errors'
import { useKnowledgePackToolsInstall } from '../lib/useKnowledgePackToolsInstall'
import { useOcrInstall } from '../lib/useOcrInstall'
import { httpsLink } from '../lib/httpsLink'
import { useEngineProblemsRead } from '../lib/useEngineProblems'
import type { ModelsFocus } from '../navigation'
import { useT } from '../i18n'
import type { MessageKey, UiLanguage } from '@shared/i18n'
import { engineProblemOffersReinstall } from '@shared/engine-problem'
import type { RuntimeFamily } from '@shared/runtime-sources'
import type {
  AppSettings,
  DownloadJob,
  EngineDownloadJob,
  EngineDownloadPreview,
  EngineDownloadRequest,
  EngineProblem,
  EngineProblemFamily,
  EngineRecheckResult,
  EngineStatus,
  ModelInfo,
  ModelState,
  ModelVerifyProgress,
  PolicyStatus,
  RuntimeStatus
} from '@shared/types'
import { isUnresolvedDownloadResult } from '@shared/downloads'
import { fmt1, fmtDiskGb, unitJoin } from '@shared/format'
import { RUNTIME_POLL_MS } from '../lib/polling'

// "AI Model" screen (guidelines §2/§3 principle: singular mental model).
// The active model leads with a plain-language size/speed hint; the rest is a friendly
// picker. Checksums, quantization ids, paths, and runtime details sit behind a
// per-card "Technical details" disclosure (closed by default). The verify / download /
// RAM-gate / mock-start flows live in the main process; this screen only presents them.

const UNKNOWN_RAM = null
const TASKS: { value: ModelTask; label: MessageKey }[] = [
  { value: 'chat', label: 'models.library.chat' },
  { value: 'documents', label: 'models.section.docSearch' },
  { value: 'translation', label: 'models.library.translation' },
  { value: 'vision', label: 'models.library.images' },
  { value: 'transcriber', label: 'models.library.voice' }
]

// A deep link about a missing optional model lands on that model (#527, #539): Browse, filtered to
// its task. `engineFamilies`: an install banner for one of these sits at the top of the screen and
// is the first thing to act on, so the library is then not scrolled into view. The AI engine's
// "can't run" banner (#530, with its #532 reinstall) sits there too and counts the same way; the
// voice engine's notice is a hint on the speech-model card, inside the library, so it does not.
const FOCUS: Record<ModelsFocus, { task: ModelTask; engineFamilies: readonly string[] }> = {
  voice: { task: 'transcriber', engineFamilies: ['llama_cpp', 'whisper_cpp'] },
  images: { task: 'vision', engineFamilies: ['llama_cpp'] },
  translation: { task: 'translation', engineFamilies: ['llama_cpp'] }
}

// Status pills: icon + word, never color-only (guidelines §6). Label values are
// MessageKeys resolved at render (i18n record §5).
const STATE_BADGE: Record<ModelState, { labelKey: MessageKey; tone: BadgeTone; icon: string }> = {
  installed: { labelKey: 'models.state.installed', tone: 'success', icon: '✓' },
  missing: { labelKey: 'models.state.missing', tone: 'neutral', icon: '○' },
  checksum_failed: { labelKey: 'models.state.checksumFailed', tone: 'error', icon: '⚠' },
  unsupported: { labelKey: 'models.state.unsupported', tone: 'error', icon: '⚠' },
  not_recommended: { labelKey: 'models.state.notRecommended', tone: 'warning', icon: '⚠' },
  ready: { labelKey: 'models.state.ready', tone: 'success', icon: '✓' },
  running: { labelKey: 'models.state.running', tone: 'accent', icon: '▶' }
}

/** #932: a `checksum_failed` model whose manifest has no checksum on record (`ModelInfo.noChecksum`): not damaged. */
const NO_CHECKSUM_BADGE: { labelKey: MessageKey; tone: BadgeTone; icon: string } = {
  labelKey: 'models.state.noChecksum',
  tone: 'warning',
  icon: '⚠'
}

/**
 * A disk size → "14.4 GB": the declared bytes when known, else the manifest's `size_on_disk_gb`.
 * Decimal GB with one decimal, the separator from the UI language (#768: it divided by 1024³ and
 * rounded from 10 GB up to a whole number, so a card reading 14.4 offered "13 GB" in its dialog).
 */
function fmtGb(bytes: number | null, fallbackGb: number, lang: UiLanguage): string {
  return bytes != null ? fmtDiskGb(bytes, lang) : `${fmt1(fallbackGb, lang)}${unitJoin(lang)}GB`
}

/**
 * A GB number that is ALREADY a GB value (manifest fields, not bytes) → locale string
 * (M-U5). Unlike `fmtGb` this does not round the manifest figure away; it only routes
 * the decimal separator + grouping through the UI language (German "4,5 GB"), and the space before
 * the unit (`unitJoin`, #804).
 */
function fmtGbNum(gb: number, lang: UiLanguage): string {
  return `${gb.toLocaleString(lang)}${unitJoin(lang)}GB`
}

/**
 * Plain-language size/speed hint (guidelines §7 spirit: "Balanced — works well on most
 * laptops" instead of quantization labels). Derived from what the manifest already
 * carries; the technical numbers live in the disclosure.
 */
function plainHintKey(m: ModelInfo): MessageKey {
  if (m.role === 'embeddings') return 'models.hint.embeddings'
  if (m.role === 'reranker') return 'models.hint.reranker'
  if (m.role === 'transcriber') return 'models.hint.transcriber'
  if (m.role === 'translation') return 'models.hint.translation'
  if (m.role === 'vision') return 'models.hint.vision'
  if (m.sizeOnDiskGb <= 1.5) return 'models.hint.small'
  if (m.sizeOnDiskGb <= 6) return 'models.hint.balanced'
  return 'models.hint.large'
}

/** Where an automatic role is used: on its card, outside the disclosure (#539). */
function automaticUsageKey(m: ModelInfo, installed: boolean): MessageKey {
  if (m.role === 'vision') return installed ? 'models.vision.installed' : 'models.vision.notInstalled'
  if (m.role === 'translation') {
    return installed ? 'models.translation.installed' : 'models.translation.notInstalled'
  }
  return installed ? 'models.automatic.installed' : 'models.automatic.notInstalled'
}

/**
 * Context-size picker presets (the "Kontextgröße" card). "Auto" (null override) launches with
 * the model's recommended window; a fixed pick becomes llama-server's `--ctx-size` at the next
 * model start. Bounded set matching the main-process clamp [2048, 131072]. The 32k ceiling was
 * a dead end (issue #43): long-document workflows — the deep index above all — need >32k, and
 * modern local models support it natively. Big rungs stay honest via the memory warning below
 * (KV cache grows linearly with the window) instead of a silent cap.
 */
const CONTEXT_SIZE_PRESETS = [4096, 8192, 16384, 32768, 65536, 131072] as const

/** Picks at or above this show the "large windows cost memory" hint (issue #43). */
const CONTEXT_SIZE_WARNING_MIN = 65_536

// The in-flight download survives leaving + re-entering the screen (the job itself
// lives in the main process; this only remembers which one to keep polling).
let rememberedJob: DownloadJob | null = null

/**
 * The display name of the remembered job's model (F2/B1). A refresh at the terminal transition
 * can stop listing the model, or list it as `installed` — the RESULT must still be named, so the
 * last known name is remembered alongside the job id it belongs to. Falls back to the model id.
 */
let rememberedJobName: { jobId: string; name: string } | null = null

/**
 * A terminal result the user dismissed, by job id (F2/B1): it must not come back on a refresh,
 * a re-render, or a remount within this renderer session. Module-scoped for the same reason
 * `rememberedJob` is — leaving and re-entering the screen remounts the component. A renderer
 * RELOAD recreates this module, so Dismiss also tells the main process (#314).
 */
let dismissedJobId: string | null = null

const JOB_LIVE: ReadonlySet<DownloadJob['status']> = new Set(['queued', 'downloading', 'verifying'])

// The engine download (like the model download) outlives leaving the screen.
let rememberedEngineJob: EngineDownloadJob | null = null

const ENGINE_JOB_LIVE: ReadonlySet<EngineDownloadJob['status']> = new Set([
  'queued',
  'downloading',
  'verifying',
  'extracting'
])

/**
 * #532: the engine job one surface shows. The install banners (`'install'`) show installs; an
 * "Install … again" action (its family) shows the reinstall of that family; the update notice
 * (`'update'`, #516) shows updates. A job from an older main carries neither flag and reads as an
 * install, as before.
 */
function engineJobFor(
  job: EngineDownloadJob | null,
  surface: 'install' | 'update' | EngineProblemFamily
): EngineDownloadJob | null {
  if (!job) return null
  if (surface === 'install') return job.reinstall === true || job.update === true ? null : job
  if (surface === 'update') return job.update === true ? job : null
  return job.reinstall === true && (job.families ?? []).includes(surface) ? job : null
}

/**
 * The live "Check all model files" pass (#420). The pass runs in the MAIN process, so it
 * survives leaving the screen — the same reason `rememberedJob` is module-scoped. Without
 * this, a revisit mid-pass showed an idle-looking screen while minutes of hashing carried on
 * behind it, and the Cancel affordance (the whole point of #420) was gone with the unmounted
 * component. `latest` seeds a revisited screen's bar until the next progress event lands.
 *
 * The pass is active exactly while its `listModels` promise is pending: `verifyAllModelFiles`
 * sets this and clears it in a `finally` that runs whether or not the screen is still mounted,
 * so it can never be left stale by a pass that finished while the user was away.
 */
let activeVerify: { runId: string; latest: ModelVerifyProgress | null } | null = null

/**
 * A fresh id for one "Check all model files" pass (#420). Renderer-minted so Cancel has a
 * handle before the call is even made; `crypto.randomUUID` is present in Chromium and in the
 * jsdom test environment, and the counter fallback keeps a partial environment working (the
 * id only has to be unique within this renderer session).
 */
let verifyRunSeq = 0
function newVerifyRunId(): string {
  const uuid = globalThis.crypto?.randomUUID?.()
  return uuid ?? `verify-${Date.now()}-${++verifyRunSeq}`
}

/** Mounted screens listening for `activeVerify` changes (at most one in practice). */
const verifyWatchers = new Set<(v: typeof activeVerify) => void>()

function setActiveVerify(next: typeof activeVerify): void {
  activeVerify = next
  for (const watch of verifyWatchers) watch(next)
}

/**
 * Test-only reset of this module's download memory. Module state is deliberately outside React so
 * it survives a remount, which also means a jsdom test has no other way to start from a known
 * state. Production code never calls this.
 */
export function __resetModelsScreenMemoryForTests(): void {
  rememberedJob = null
  rememberedJobName = null
  dismissedJobId = null
  rememberedEngineJob = null
  setActiveVerify(null)
}

export interface ModelsScreenProps {
  /**
   * Open on one task's Browse list instead of the default view (#527, #539): `'voice'` is the
   * composer's dictation hint ("Get the speech model"), `'images'` / `'translation'` the Images
   * and Translate availability cards and the Documents row's "Get the translation model…" —
   * Browse, because the model is the missing piece there, filtered to its task so it is the row
   * in view. Read at mount; the screen's own controls take over from there (the
   * `documents:packs` pattern).
   */
  focus?: ModelsFocus | null
  /** Navigation out of the screen (#539: the vision card's "Go to Images"). Without it, no button. */
  onNavigate?: (target: string) => void
}

export function ModelsScreen({ focus = null, onNavigate }: ModelsScreenProps = {}): JSX.Element {
  const { t, tCount, lang } = useT()
  // A context size in words: the raw token count picks the plural form, and the text shows the
  // figure grouped for the locale ("8,192" / "8.192").
  const contextSizeText = (key: 'models.tech.contextValue' | 'models.context.autoResolved', tokens: number): string =>
    tCount(key, tokens, { count: tokens.toLocaleString(lang) })
  const [models, setModels] = useState<ModelInfo[] | null>(null)
  const [libraryView, setLibraryView] = useState<'installed' | 'browse' | null>(
    focus !== null ? 'browse' : null
  )
  const [query, setQuery] = useState('')
  const [task, setTask] = useState<ModelTask | 'all'>(focus !== null ? FOCUS[focus].task : 'all')
  const [family, setFamily] = useState('all')
  // F3/C1: group expansion is DERIVED by default — a group holding a damaged (`checksum_failed`)
  // variant starts expanded, so the repair row is reachable without first guessing that it hides
  // behind "Show all variants". This map records only the user's EXPLICIT toggles, by stable
  // group key, and those always win — across a refresh that introduces or clears damage, and
  // across filter/view changes (the key outlives both).
  const [userToggledGroups, setUserToggledGroups] = useState<ReadonlyMap<string, boolean>>(new Map())
  const [settings, setSettings] = useState<AppSettings | null>(null)
  const [policy, setPolicy] = useState<PolicyStatus | null>(null)
  const [machineRam, setMachineRam] = useState<number | null>(UNKNOWN_RAM)
  // #527: the voice engine has no build for this system (and none is on the drive) — the
  // speech-model card says so instead of presenting its download as the way to dictation.
  const [voiceEngineUnsupported, setVoiceEngineUnsupported] = useState(false)
  // Drives a determinate bar instead of an opaque spinner while weights hash — in the
  // loading state (a cold ACTIVE model, the one file lazy verification still hashes) and,
  // since #382, IN PLACE on the loaded screen while "Check all model files" runs. Null once
  // nothing is hashing.
  const [verifyProgress, setVerifyProgress] = useState<ModelVerifyProgress | null>(
    activeVerify?.latest ?? null
  )
  // #420: the live "Check all model files" pass, if one is running — including one this
  // screen did not start itself (the user left mid-pass and came back). Non-null ⇒ the bar
  // and its Cancel button are on screen and the action is disabled.
  const [verifyRun, setVerifyRun] = useState(activeVerify)
  // Set between the Cancel click and the pass unwinding, so the button can't be clicked twice.
  const [verifyCancelling, setVerifyCancelling] = useState(false)
  // Runtime status — so a model that is loading in the background shows a disabled
  // "Starting…" button (the `startingModelId` is server truth that survives a revisit,
  // unlike the per-click `busy` flag). Without this, the still-enabled Start button let a
  // revisit kick off a disruptive restart.
  const [runtime, setRuntime] = useState<RuntimeStatus | null>(null)
  const [busy, setBusy] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  // The per-download confirmation dialog + the polled download job.
  const [confirming, setConfirming] = useState<ModelInfo | null>(null)
  const [licenseAck, setLicenseAck] = useState(false)
  const [job, setJob] = useState<DownloadJob | null>(rememberedJob)
  const jobRef = useRef<DownloadJob | null>(rememberedJob)
  // F2/B1: the last known display name of the job's model, and the terminal result the user
  // dismissed. Both mirror module state so they survive leaving + re-entering the screen.
  const [jobName, setJobName] = useState<{ jobId: string; name: string } | null>(rememberedJobName)
  const [dismissedJob, setDismissedJob] = useState<string | null>(dismissedJobId)
  // The real AI engine (llama.cpp): without it, started models run in demo mode.
  const [engine, setEngine] = useState<EngineStatus | null>(null)
  const [engineJob, setEngineJob] = useState<EngineDownloadJob | null>(rememberedEngineJob)
  const engineJobRef = useRef<EngineDownloadJob | null>(rememberedEngineJob)
  // #843: the engine install / update / reinstall confirmation — what main's preview says the job
  // will fetch, the request Confirm sends unchanged, and the clicked surface's title and action label.
  const [engineConfirm, setEngineConfirm] = useState<{
    preview: EngineDownloadPreview
    request: EngineDownloadRequest | undefined
    titleKey: MessageKey
    confirmKey: MessageKey
  } | null>(null)
  // #339 P8-2 (the owner's ruling): the quiet "knowledge-pack tools" row below the two engine
  // banners — the SAME confirm dialog/hook the Knowledge-packs panel notice uses, so the two
  // entry points can never present different facts. Only fetches its own getEngineStatus/
  // getPolicy while `packToolsMissing` is true (the hook's lazy-load contract).
  const [packToolsDialogOpen, setPackToolsDialogOpen] = useState(false)
  const packToolsMissing = engine?.missingOptionalFamilies?.includes('kiwix_tools') ?? false
  const packToolsInstall = useKnowledgePackToolsInstall(packToolsMissing, () => {
    void runAndSurface(refresh, (m) => mountedRef.current && setError(m))
  })
  // #410: the quiet OCR row — the SAME dialog/hook the Documents rows use. Shown while this drive
  // has a usable download list and a pinned language file is missing (or does not match its pin),
  // plus, after a job this visit ran, until the screen is left (so its outcome — "ready" or
  // "restart" — stays readable). Hidden once installed.
  const [ocrDialogOpen, setOcrDialogOpen] = useState(false)
  const [ocrJobFinishedHere, setOcrJobFinishedHere] = useState(false)
  const ocrInstall = useOcrInstall(true, () => setOcrJobFinishedHere(true))
  // #530: an engine on the drive that the OS refused to start this session (live: the push
  // re-reads it, so a refusal found after this screen mounted still shows, and a healed one goes).
  const { problems: engineProblems, settled: engineProblemsSettled } = useEngineProblemsRead()
  const chatEngineProblem = engineProblems?.find((p) => p.family === 'llama_cpp') ?? null
  const voiceEngineProblem = engineProblems?.find((p) => p.family === 'whisper_cpp') ?? null
  // #532: confirms a reinstall that finished — its banner unmounts with the verdict at that moment.
  const showToast = useToast()
  // #516: required engines on the drive older than this app's pin (or whose `cpu/` net is). An
  // engine the OS refused shows its own banner instead — a reinstall fetches the pin anyway.
  const updatableFamilies = useMemo(
    () =>
      (engine?.engineVersions ?? [])
        .filter((v) => !v.optional && (v.relation === 'older' || v.cpuNet?.relation === 'older'))
        .map((v) => v.family)
        .filter((f) => !(f === 'llama_cpp' && chatEngineProblem) && !(f === 'whisper_cpp' && voiceEngineProblem)),
    [engine, chatEngineProblem, voiceEngineProblem]
  )
  const recheckEngine = (): Promise<EngineRecheckResult> =>
    window.api.recheckEngine().catch((err: unknown) => {
      throw new Error(friendlyIpcError(err))
    })
  const ocrFilesMissing =
    ocrInstall.status?.available === true && ocrInstall.status.languages.some((l) => !l.installed)
  const ocrRowVisible = ocrFilesMissing || ocrInstall.live || ocrJobFinishedHere
  // #538: text recognition works and only the orientation file is missing — the row says what it adds.
  const ocrOnlyOrientationMissing =
    ocrFilesMissing &&
    (ocrInstall.status?.languages.every((l) => l.installed || l.role === 'orientation') ?? false)
  // Mounted flag (audit FE-4): refresh() and the download/engine polls below resolve async; a
  // parked tick can land AFTER unmount (clearing the interval doesn't abort the in-flight
  // promise). Guard every setState behind this so ModelsScreen joins the uniform FE-4 discipline.
  const mountedRef = useRef(true)
  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])

  // #527, #539: a deep link lands ON the missing model. The library sits below the engine
  // banners, the OCR row and the context card, so once the first load is in, it is scrolled into
  // view, unless an engine banner is showing: then an engine is part of what is missing, and the
  // banner at the top is the first thing to act on. Once per visit, never after the user scrolled.
  // #532: the AI engine's "can't run" banner counts too, so the decision also waits for the first
  // read of the engine verdicts (a refusal reported after that read still cannot move the screen).
  const libraryRef = useRef<HTMLElement>(null)
  const focusScrolledRef = useRef(false)
  useEffect(() => {
    if (focus === null || models === null || !engineProblemsSettled || focusScrolledRef.current) return
    focusScrolledRef.current = true
    const families = FOCUS[focus].engineFamilies
    // #516: the update notice for one of these engines sits there too (the #539 note on #516).
    const engineBannerShown =
      (engine?.available === true && families.some((f) => engine.missingFamilies.includes(f))) ||
      (chatEngineProblem !== null && families.includes('llama_cpp')) ||
      updatableFamilies.some((f) => families.includes(f))
    if (!engineBannerShown) libraryRef.current?.scrollIntoView?.({ block: 'start' })
  }, [focus, models, engine, engineProblemsSettled, chatEngineProblem, updatableFamilies])

  async function refresh(): Promise<void> {
    const [m, s, p, e, rt] = await Promise.all([
      // #382: LAZY verification. The Models screen used to omit the flag and hash every
      // present weight before it could render a single card — 25.5 min for 39.44 GB on the
      // #330 slow-drive round trip (mean 25.8 MB/s, strictly sequential), and this screen is
      // the ONLY route to a first model on a fresh workspace (`activeModelId` starts null).
      // Lazy resolves to `onlyVerifyModelId: settings.activeModelId`, so at most ONE weight
      // is hashed here. The §7.4 gate is untouched: `startModelRuntime` re-verifies what it
      // launches and the ship-time gates always hash fully. Passive `checksum_failed`
      // discovery for models nothing has started is traded away on purpose — the explicit
      // "Check all model files" action below is the replacement.
      window.api.listModels(true),
      window.api.getSettings(),
      window.api.getPolicy().catch(() => null),
      window.api.getEngineStatus().catch(() => null),
      window.api.getRuntimeStatus().catch(() => null)
    ])
    if (!mountedRef.current) return // unmounted while the batch was loading (FE-4)
    setModels(m)
    // Initialize once: finishing a download must not unexpectedly change views.
    setLibraryView((current) => current ?? (m.some(isModelInstalled) ? 'installed' : 'browse'))
    setSettings(s)
    setPolicy(p)
    setEngine(e)
    setRuntime(rt)
    // Machine RAM feeds the "needs more memory" flag copy; best-effort.
    window.api
      .getAppStatus()
      .then((st) => {
        if (!mountedRef.current) return
        setMachineRam(st.machineRamGb)
        setVoiceEngineUnsupported(st.transcriberMissing === 'engine-unsupported')
      })
      .catch(() => mountedRef.current && setMachineRam(UNKNOWN_RAM))
  }

  useEffect(() => {
    // RD-5: the reject can land after unmount too — same FE-4 guard as every other setState here.
    refresh().catch((e) => mountedRef.current && setError(friendlyIpcError(e)))
  }, [])

  // #314 — adopt an existing download after a renderer RELOAD, which wipes this module's memory.
  // Ordinary navigation still wins (`rememberedJob` is set, so this does nothing); only an empty
  // memory asks the main process which jobs are still the user's problem — the live one, plus the
  // undismissed failed / unverified results. Seeding `job` is all it takes: the poll, the
  // name-remembering effect and the panel derivation then run exactly as if nothing was lost.
  useEffect(() => {
    if (rememberedJob) return
    window.api
      .listDownloadJobs()
      .then((jobs) => {
        if (!mountedRef.current || jobs.length === 0) return
        // A download the user started while this read was in flight is newer — never overwrite it.
        if (jobRef.current) return
        const unresolved = jobs.filter(isUnresolvedDownloadResult)
        const adopted =
          jobs.find((j) => JOB_LIVE.has(j.status)) ?? unresolved[unresolved.length - 1] ?? null
        if (!adopted) return
        jobRef.current = adopted
        rememberedJob = adopted
        setJob(adopted)
      })
      .catch(() => undefined)
  }, [])

  // Stream first-run verification progress (the cold-hash bar). The terminal `done` event
  // clears it so the bar never lingers after hashing finishes.
  useEffect(() => {
    return window.api.onModelVerifyProgress((p) => {
      // #420: keep the module's memory of the live full pass fresh, so leaving and coming
      // back re-draws the bar where it actually is instead of at zero.
      if (activeVerify && activeVerify.runId === p.runId) activeVerify.latest = p.done ? null : p
      // Lock onto one pass: `listModels` can run as overlapping passes (a remount, the
      // download poll), each with its own `modelCount` as the cache warms — without this
      // the bar flips between "1 of 1" and "2 of 2". Ignore events from a different pass
      // until the tracked one's terminal `done`.
      setVerifyProgress((prev) => {
        if (prev && prev.runId !== p.runId) return prev
        return p.done ? null : p
      })
    })
  }, [])

  // #420: follow the module-scoped full pass, so a screen that was remounted mid-pass shows
  // the bar + Cancel, and one whose pass finished while the user was away settles by itself.
  useEffect(() => {
    const watch = (v: typeof activeVerify): void => {
      if (!mountedRef.current) return
      setVerifyRun(v)
      if (!v) {
        setVerifyCancelling(false)
        setVerifyProgress(null)
      }
    }
    verifyWatchers.add(watch)
    return () => {
      verifyWatchers.delete(watch)
    }
  }, [])

  // While a model is starting in the background, poll runtime status so the "Starting…"
  // button flips to "Stop" on its own once the GGUF finishes loading (a full `refresh`
  // also picks up the new `running` model state).
  // SH-9 (#149): while a model starts, poll ONLY the small getRuntimeStatus — the previous
  // full 6-IPC refresh() (listModels, settings, policy, engine, runtime, app
  // status) rebuilt every card ~2.5 s for minutes on a 20 GB GGUF. One full refresh runs on
  // the starting→settled transition, which also re-fires this effect and clears the timer.
  useEffect(() => {
    if (!runtime?.startingModelId) return
    const timer = setInterval(() => {
      void window.api
        .getRuntimeStatus()
        .then((rt) => {
          if (!mountedRef.current) return
          setRuntime(rt)
          if (!rt.startingModelId) {
            // Settled (running or stopped): the cards' install/active state may have changed.
            void runAndSurface(refresh, (m) => mountedRef.current && setError(m))
          }
        })
        .catch(() => undefined)
    }, RUNTIME_POLL_MS)
    return () => clearInterval(timer)
  }, [runtime?.startingModelId])

  // #600: while an answer is being written, poll the same small status so the card's "an answer is
  // being written" note disappears once the answer finishes (the screen is usually opened mid-answer
  // from the chat). Stops on its own when `answering` clears; while a model starts (a switch: the old one
  // still answers meanwhile) the poll above already refreshes the same status.
  useEffect(() => {
    if (!runtime?.answering || runtime.startingModelId) return
    const timer = setInterval(() => {
      void window.api
        .getRuntimeStatus()
        .then((rt) => {
          if (mountedRef.current) setRuntime(rt)
        })
        .catch(() => undefined)
    }, RUNTIME_POLL_MS)
    return () => clearInterval(timer)
  }, [runtime?.answering, runtime?.startingModelId])

  // F2/B1: remember the downloading model's NAME while the catalog still lists it, so a terminal
  // result stays named after a refresh that drops the entry or flips it to `installed`.
  useEffect(() => {
    if (!job || !models) return
    const found = models.find((m) => m.id === job.modelId)
    if (!found) return
    if (rememberedJobName?.jobId === job.jobId && rememberedJobName.name === found.displayName) return
    rememberedJobName = { jobId: job.jobId, name: found.displayName }
    setJobName(rememberedJobName)
  }, [job, models])

  // Poll the live download job (async-with-polling, like import progress).
  useEffect(() => {
    jobRef.current = job
    rememberedJob = job
    if (!job || !JOB_LIVE.has(job.status)) return
    const timer = setInterval(() => {
      window.api
        .getDownloadJob(job.jobId)
        .then((next) => {
          if (!mountedRef.current) return // late tick after unmount (FE-4)
          // F2/B1: a response for a job that is no longer the current one (a new download was
          // accepted meanwhile) must never overwrite the newer job or resurrect an old result.
          if (jobRef.current?.jobId !== job.jobId || next.jobId !== job.jobId) return
          setJob(next)
          // A finished download changes install state — refresh the cards once. CODE-28
          // (full-audit 2026-07-11): surfaced, not fire-and-forget — a failing refresh at
          // exactly this transition left stale cards + an unhandled rejection.
          if (!JOB_LIVE.has(next.status) && JOB_LIVE.has(jobRef.current?.status ?? 'done')) {
            void runAndSurface(refresh, (m) => mountedRef.current && setError(m))
          }
        })
        .catch(() => undefined)
    }, 1000)
    return () => clearInterval(timer)
  }, [job?.jobId, job?.status])

  // Poll the engine download the same way; a finished install refreshes the cards once
  // (the engine status flips installed → the demo-mode banner disappears).
  useEffect(() => {
    engineJobRef.current = engineJob
    rememberedEngineJob = engineJob
    if (!engineJob || !ENGINE_JOB_LIVE.has(engineJob.status)) return
    const timer = setInterval(() => {
      window.api
        .getEngineJob(engineJob.jobId)
        .then((next) => {
          if (!mountedRef.current) return // late tick after unmount (FE-4)
          setEngineJob(next)
          if (
            !ENGINE_JOB_LIVE.has(next.status) &&
            ENGINE_JOB_LIVE.has(engineJobRef.current?.status ?? 'done')
          ) {
            // CODE-28: same surfaced completion-refresh as the model-download poll above.
            void runAndSurface(refresh, (m) => mountedRef.current && setError(m))
            // #532: a finished reinstall drops the verdict, and its banner with it — say what happened.
            // #516: likewise a finished update, whose notice leaves with the refreshed versions.
            if (next.status === 'done' && (next.reinstall === true || next.update === true)) {
              const chat = next.families?.includes('llama_cpp') === true
              const voice = next.families?.includes('whisper_cpp') === true
              const key: MessageKey =
                next.update === true
                  ? chat && voice
                    ? 'models.engineUpdate.bothDone'
                    : voice
                      ? 'models.engineUpdate.voiceDone'
                      : 'models.engineUpdate.done'
                  : voice && !chat
                    ? 'models.engineProblem.voiceReinstalled'
                    : 'models.engineProblem.reinstalled'
              showToast(t(key))
            }
          }
        })
        .catch(() => undefined)
    }, 1000)
    return () => clearInterval(timer)
  }, [engineJob?.jobId, engineJob?.status])

  /**
   * #843: every engine action asks first. The click reads main's preview of what this exact request
   * would fetch (`getEnginePlan` — the step selection the job itself runs) and opens the dialog; a
   * refusal (nothing to update, a repair no longer needed) is shown like a failed start. The request
   * is kept as it is and sent unchanged on Confirm, so main needs no consent token.
   */
  async function askEngine(
    request: EngineDownloadRequest | undefined,
    titleKey: MessageKey,
    confirmKey: MessageKey
  ): Promise<void> {
    setError(null)
    try {
      const preview = await (request === undefined ? window.api.getEnginePlan() : window.api.getEnginePlan(request))
      if (mountedRef.current) setEngineConfirm({ preview, request, titleKey, confirmKey })
    } catch (e) {
      if (mountedRef.current) setError(friendlyIpcError(e))
    }
  }

  /**
   * The confirmed engine job: the default install (no argument), #516's "Update" (main pauses the
   * engine's users only for the swap) or #532's "Install … again" — the same job and gates for each.
   */
  async function startEngineJob(request: EngineDownloadRequest | undefined): Promise<void> {
    setError(null)
    try {
      setEngineJob(await (request === undefined ? window.api.downloadEngine() : window.api.downloadEngine(request)))
    } catch (e) {
      setError(friendlyIpcError(e))
    }
  }

  /**
   * #599: Restart on a model that stopped responding. The main side claims the "starting" window
   * synchronously, so one status read right after the request shows it — and arms the starting poll
   * above — instead of leaving "Not responding" up for the whole reload.
   */
  async function restartModel(): Promise<void> {
    const done = window.api.restartRuntime()
    void window.api
      .getRuntimeStatus()
      .then((rt) => {
        if (mountedRef.current) setRuntime(rt)
      })
      .catch(() => undefined)
    await done
  }

  async function run(key: string, fn: () => Promise<unknown>): Promise<void> {
    setBusy(key)
    setError(null)
    try {
      await fn()
      await refresh()
    } catch (e) {
      setError(friendlyIpcError(e))
    } finally {
      setBusy(null)
    }
  }

  /**
   * #382: the determinate hashing bar, rendered by BOTH sites — the blocked loading state
   * (a cold active model) and, in place, the loaded screen while "Check all model files"
   * runs. Before #382 the only render site was inside the `!models` branch, so a full pass
   * on a loaded screen would have hashed for minutes with nothing on screen at all.
   * Null whenever nothing is hashing, or before the byte denominator is known.
   */
  function verifyBar(): JSX.Element | null {
    const p = verifyProgress
    if (!p || p.overallBytesTotal <= 0) return null
    const pct = Math.min(100, Math.round((p.overallBytesHashed / p.overallBytesTotal) * 100))
    return (
      <Progress
        label={t('models.checkingProgress', {
          n: p.modelIndex,
          m: p.modelCount,
          name: p.displayName,
          pct
        })}
        value={p.overallBytesHashed}
        max={p.overallBytesTotal}
      />
    )
  }

  /**
   * #382: the explicit opt-in replacement for the passive full hash. Omitting `lazyVerify`
   * is the full-verify mode `buildModelList` already has, so this needs no new channel; the
   * hashes it computes land in the (size, mtime) checksum store, so the `refresh()` that
   * `run` fires afterwards reports every state — `checksum_failed` included — from the cache.
   * The pass stops at a model's first damaged file and leaves its other files unhashed; the
   * lazy refresh still reads that one cached mismatch as `checksum_failed` (#913).
   *
   * #420: the run id is minted HERE, before the call, and handed to main — so Cancel has a
   * handle from the first instant, not from the first progress event (which can be seconds
   * away, and never arrives at all when there is nothing to hash). The `finally` clears the
   * module memory whether or not this screen is still mounted, which is what makes
   * `activeVerify` an honest "a pass is running right now".
   */
  async function verifyAllModelFiles(): Promise<void> {
    const runId = newVerifyRunId()
    setActiveVerify({ runId, latest: null })
    await run('verify-all', async () => {
      try {
        const m = await window.api.listModels(undefined, runId)
        if (mountedRef.current) setModels(m)
      } finally {
        setActiveVerify(null)
      }
    })
  }

  /**
   * #420: stop the pass. A cancelled pass is NOT a failure — main returns a complete list in
   * which what finished is verified and the rest is simply unchecked — so nothing here shows
   * an error banner; the call above resolves normally and `run`'s trailing refresh reports
   * the settled state. A cancel that finds nothing (the pass ended a moment earlier) is a
   * no-op by contract.
   */
  async function cancelVerifyAll(): Promise<void> {
    const active = verifyRun
    if (!active) return
    setVerifyCancelling(true)
    try {
      await window.api.cancelModelVerify(active.runId)
    } catch {
      // Nothing to surface: either the pass had already finished, or it will finish on its
      // own. Re-enable the button so the user can try again.
      if (mountedRef.current) setVerifyCancelling(false)
    }
  }

  /** Persist the context-size pick ('auto' = null override = the model's recommended window).
   *  Applies at the next model start — the card's hint (+ restart note while one runs) says so. */
  async function onContextSizeChange(value: string): Promise<void> {
    setError(null)
    try {
      const s = await window.api.updateSettings({
        contextTokensOverride: value === 'auto' ? null : Number(value)
      })
      if (mountedRef.current) setSettings(s)
    } catch (e) {
      if (mountedRef.current) setError(friendlyIpcError(e))
    }
  }

  async function startDownload(m: ModelInfo): Promise<void> {
    setConfirming(null)
    setError(null)
    try {
      const started = await window.api.downloadModel(m.id, { licenseAccepted: licenseAck })
      // F2/B1: only an ACCEPTED job replaces a retained terminal result — a rejected start (and a
      // cancelled dialog) leaves the previous result on screen. The dismissal is cleared with it so
      // a backend that resumes under the same job id cannot start out hidden. FE-4 mounted guard.
      if (!mountedRef.current) return
      dismissedJobId = null
      setDismissedJob(null)
      setJob(started)
    } catch (e) {
      if (mountedRef.current) setError(friendlyIpcError(e))
    } finally {
      if (mountedRef.current) setLicenseAck(false)
    }
  }

  if (error && !models) {
    return (
      <div className="screen models-screen">
        <h1>{t('models.title')}</h1>
        <p className="hint">{t('models.loadError', { error })}</p>
      </div>
    )
  }

  if (!models || !settings) {
    const bar = verifyBar()
    return (
      <div className="screen models-screen">
        <h1>{t('models.title')}</h1>
        {bar ?? (
          <p className="hint">
            <Spinner /> {t('models.checking')}
          </p>
        )}
      </div>
    )
  }

  const isActive = (m: ModelInfo): boolean =>
    m.role === 'embeddings'
      ? settings.activeEmbeddingModelId === m.id
      : settings.activeModelId === m.id

  const chat = models.filter((m) => m.role === 'chat')

  // The active chat model remains pinned outside the filters. The library contains
  // alternatives, ordered by availability/recommendation before grouping variants.
  const activeChat = chat.find(isActive) ?? null
  const currentView = libraryView ?? 'browse'
  // #313 — the whole row filter (view/task/family/search), factored so the empty-state's "what
  // would Browse show" count (below) is computed by the SAME rule as `visibleModels` itself, just
  // with `view` substituted — the two can never disagree.
  const matchesLibraryRow = (m: ModelInfo, view: typeof currentView): boolean =>
    m !== activeChat &&
    // F3/C1: the drive view lists known damaged entries too — the repair action is on the row.
    matchesLibraryView(m, view) &&
    (task === 'all' || modelTask(m) === task) &&
    (family === 'all' || m.family === family) &&
    matchesModelSearch(m, query)
  const visibleModels = orderPickerModels(models.filter((m) => matchesLibraryRow(m, currentView)))
  // #847 — the trailing "Needs a newer HilbertRaum" rows (never library rows, never a family option).
  const newerRows = newerAppRows(models, { view: currentView, task, family, query })
  const families = availableFamilies(models, { activeChat, view: currentView, task })
  // #313 — a selected family the current view/task cannot yield: kept visible (never silently
  // dropped) with a marker option, and the trigger for the family-specific empty state below.
  const familyOutOfView = family !== 'all' && !families.includes(family)
  // #313 — "On this drive" empty state names what Browse would show for the same family/task/
  // search instead: `matchesLibraryRow` with `view` swapped to 'browse' guarantees the number
  // matches exactly what the user sees after pressing the "Browse models" button below.
  const browseRowCountForFamily =
    familyOutOfView && currentView === 'installed'
      ? models.filter((m) => matchesLibraryRow(m, 'browse')).length
      : 0
  const hasFilters = query !== '' || task !== 'all' || family !== 'all'
  // #315 — grouping + expansion, computed ONCE per task section so the list below and the
  // "current model download" panel's own-name decision (`renderedModelIds`) read the SAME
  // groups/expansion instead of two copies that could disagree.
  const sections = TASKS.map((entry) => {
    const list = visibleModels.filter((m) => modelTask(m) === entry.value)
    return {
      entry,
      groups: groupModelVariants(list).map((group) => {
        // C1: a damaged variant must not hide inside a collapsed group — the whole recovery
        // action sits on its row. An explicit user toggle still wins (both directions).
        const hasRepair = group.models.some((m) => m.state === 'checksum_failed')
        return { group, expanded: userToggledGroups.get(group.key) ?? hasRepair }
      })
    }
  })
  // #315 — every model id whose row is actually on screen below: a single-variant card, a
  // group's face, or (only while expanded) any other member of that group.
  const renderedModelIds = new Set<string>()
  for (const section of sections) {
    for (const { group, expanded } of section.groups) {
      const ordered = variantGroupOrder(group)
      renderedModelIds.add(ordered[0].id)
      if (expanded) for (const m of ordered.slice(1)) renderedModelIds.add(m.id)
    }
  }
  // F2/B1 — what the independent "Current model download" panel owns: the live job (as before)
  // AND an unresolved terminal result, until the user dismisses it, a new job is accepted, or the
  // download ends verified/cancelled. Derived from `job` alone; no separate copy of the job.
  const panelJob =
    job &&
    job.jobId !== dismissedJob &&
    (JOB_LIVE.has(job.status) || isUnresolvedDownloadResult(job))
      ? job
      : null
  const panelLive = panelJob != null && JOB_LIVE.has(panelJob.status)
  const panelModel = panelJob ? models.find((m) => m.id === panelJob.modelId) ?? null : null
  // Name the result even when the refresh at the transition no longer lists the model.
  const panelName = panelJob
    ? panelModel?.displayName ??
      (jobName?.jobId === panelJob.jobId ? jobName.name : null) ??
      panelJob.modelId
    : ''
  // #315 — the panel's own name line is only needed while the model's row is off screen
  // (filtered away, collapsed inside a group, or no longer listed); otherwise the row already
  // carries the identity and repeating it in the panel just above is redundant.
  const panelRowRendered = panelModel != null && renderedModelIds.has(panelModel.id)

  // Download gates: the drive policy is the ceiling, the Settings toggle the
  // switch. The copy distinguishes the two — "disabled by policy" vs. "turn it on in
  // Settings" — reusing the PolicyStatus distinction the Privacy & data tab makes.
  // #339 P8-2: extracted to `lib/downloadGate.ts` so the knowledge-pack tools install (same
  // gate, same copy) can never diverge from this screen's own engine/model download gate.
  const { downloadsEnabled, blockedReason: downloadsBlockedReason } = computeDownloadGate(policy, t)
  // A withdrawn source (#196) is NOT downloadable — the network-gate banner above the list
  // must not appear for a screen whose only "missing" models can never be fetched anyway.
  const anyDownloadable = models.some(
    (m) =>
      m.download &&
      !m.download.withdrawn &&
      !m.noChecksum &&
      (m.state === 'missing' || m.state === 'checksum_failed')
  )

  // #339 P8-2: the knowledge-pack tools install job's download percentage, same shape as the
  // engine banner's own `pct` (see `engineBanner` below).
  const packToolsPct =
    packToolsInstall.job && packToolsInstall.job.totalBytes && packToolsInstall.job.totalBytes > 0
      ? Math.min(100, Math.round((packToolsInstall.job.receivedBytes / packToolsInstall.job.totalBytes) * 100))
      : null

  // Retry (panel, terminal result only): resolve the EXACT model id from the current list and run
  // it through the same confirmation as every other download — the same gates, the same license
  // link, a fresh acknowledgement. A model that left the catalog, lost its download block or was
  // withdrawn (#196) keeps a visible, explained result instead of a button that can only fail.
  const retryTarget =
    panelJob && !panelLive ? models.find((m) => m.id === panelJob.modelId) ?? null : null
  const retryWithdrawn = retryTarget?.download?.withdrawn ?? null
  // #314: the refresh reports the weight already on the drive, so Retry would offer to re-fetch
  // gigabytes the user has. Its OWN case, not `retryUnavailable` — that copy ("no longer offered
  // here, look for it in the library") would be plainly wrong about an installed model. It also
  // outranks the withdrawn explanation: a copy on the drive is what the user actually asked about.
  const retryInstalled = retryTarget != null && isModelInstalled(retryTarget)
  const retryUnavailable = retryTarget == null || retryTarget.download == null
  const retryBlockedReason =
    downloadsBlockedReason ??
    (retryInstalled ? t('models.download.retryInstalled') : null) ??
    (retryWithdrawn != null ? t('models.download.withdrawn', { reason: retryWithdrawn }) : null) ??
    (retryUnavailable ? t('models.download.retryUnavailable') : null) ??
    // The same one-at-a-time gate the rows use; a retained result never widens it (see below).
    (job != null && JOB_LIVE.has(job.status) ? t('models.download.otherRunning') : null)

  function downloadSection(m: ModelInfo): JSX.Element | null {
    if (!m.download) return null
    if (m.state !== 'missing' && m.state !== 'checksum_failed') return null
    // #932 (A S-A9): no checksum on record is not a damaged file, and a download cannot give the manifest a checksum:
    // the model stays refused while any of its files has none, so the card's hint says what it needs instead. When no
    // file needs fetching, main refuses the download too (`main.download.presentUnverified`). A mixed manifest (a
    // real-hash GGUF, damaged, beside a placeholder projector) would get the GGUF planned and fetched, but the new copy
    // still could not start, so the button stays hidden there too (#933 review N2; docs/model-policy.md "Model states").
    if (m.noChecksum) return null
    // #196: the publisher removed the pinned file. Explain instead of offering a button that
    // can only end in an HTTP 404 — the main process refuses the start regardless.
    if (m.download.withdrawn) {
      return (
        <div className="download-progress">
          <Banner tone="info">
            {t('models.download.withdrawn', { reason: m.download.withdrawn })}
          </Banner>
        </div>
      )
    }
    const mine = job && job.modelId === m.id ? job : null
    if (mine && JOB_LIVE.has(mine.status)) {
      const pct =
        mine.totalBytes && mine.totalBytes > 0
          ? Math.min(100, Math.round((mine.receivedBytes / mine.totalBytes) * 100))
          : null
      return (
        <div className="download-progress">
          <Progress
            label={
              mine.status === 'verifying'
                ? t('models.download.verifying')
                : pct != null
                  ? t('models.download.progress', {
                      pct,
                      received: fmtGb(mine.receivedBytes, 0, lang),
                      total: fmtGb(mine.totalBytes, m.sizeOnDiskGb, lang)
                    })
                  : t('models.download.progressNoTotal', {
                      received: fmtGb(mine.receivedBytes, 0, lang)
                    })
            }
            value={pct != null ? mine.receivedBytes : undefined}
            max={pct != null ? (mine.totalBytes ?? undefined) : undefined}
          />
          <Button
            size="sm"
            // Surface a cancel rejection as a friendly error instead of an unhandled
            // promise rejection (audit FE-2). SH-6 (#149): the resolved state writes the
            // module-scoped rememberedJob DIRECTLY (the state effect can't run after an
            // unmount, so a remount used to briefly resume polling a cancelled job) and
            // both setters take the FE-4 mounted guard. Main treats `verifying` as a
            // cancellable state and stops the hash (BE-4, #752), so no disable here.
            onClick={() =>
              window.api
                .cancelDownload(mine.jobId)
                .then((next) => {
                  rememberedJob = next
                  if (!mountedRef.current) return
                  setJob(next)
                  // Too late to cancel: the check finished since the last poll. This snapshot
                  // stops the poll, so the poll's own refresh of the cards never runs.
                  if (next.status !== 'cancelled') {
                    void runAndSurface(refresh, (m) => mountedRef.current && setError(m))
                  }
                })
                .catch((e) => mountedRef.current && setError(friendlyIpcError(e)))
            }
          >
            {t('models.download.cancel')}
          </Button>
        </div>
      )
    }
    return (
      <div className="download-progress">
        {/* SH-2 (#145): always-mounted so the FIRST download failure is announced. */}
        <ErrorBanner message={mine?.status === 'failed' ? mine.error : null} t={t} />
        {mine?.status === 'cancelled' && (
          <p className="hint">
            {/* #782: nobody pressed Cancel; switching internet access off stopped it. */}
            {t(mine.stoppedBy === 'networkOff' ? 'models.download.stoppedNetworkOff' : 'models.download.cancelled')}
          </p>
        )}
        {mine?.status === 'done' && mine.unverified && (
          <Banner tone="warning">
            {t('models.download.unverifiedBefore')}
            <code>verify-models --generate</code>
            {t('models.download.unverifiedAfter')}
          </Banner>
        )}
        <Button
          size="sm"
          variant="primary"
          disabled={!downloadsEnabled || (job != null && JOB_LIVE.has(job.status))}
          title={
            downloadsBlockedReason ??
            (job != null && JOB_LIVE.has(job.status)
              ? t('models.download.otherRunning')
              : t('models.download.titled', {
                  name: m.displayName,
                  size: fmtGb(m.download.sizeBytes, m.sizeOnDiskGb, lang)
                }))
          }
          onClick={() => {
            setLicenseAck(false)
            setConfirming(m)
          }}
        >
          {mine?.status === 'cancelled' || mine?.status === 'failed'
            ? t('models.download.resume')
            : t('models.download.start')}
        </Button>
      </div>
    )
  }

  function card(m: ModelInfo): JSX.Element {
    const installed = m.state === 'installed' || m.state === 'running' || m.state === 'ready'
    // Embeddings/reranker/transcriber/vision are availability-driven (they work once installed
    // by PRESENCE, not a UI selection — the embedder/reranker/transcriber pick by presence; a
    // vision model is used on demand by the Images screen). There is nothing to select or start,
    // so neither those actions NOR the "Active" badge are shown (only the chat model has a
    // user-chosen active slot). Starting a non-chat model claims the CHAT runtime slot and throws
    // (`registerModelIpc` rejects a non-`chat` role), so these roles must never reach Select/Start.
    // With no action to explain them, their card says where they are used, visibly (#539).
    const automatic =
      m.role === 'embeddings' ||
      m.role === 'reranker' ||
      m.role === 'transcriber' ||
      m.role === 'vision' ||
      m.role === 'translation'
    const active = !automatic && isActive(m)
    // Zero-weights first run: the MAIN process computes whether this (missing, chat)
    // model may start the built-in mock (developer + policy gates).
    const canMockStart = Boolean(m.startableAsMock)
    // RAM gate: this machine has less memory than the model's minimum. Select/Start are
    // disabled (the main process refuses installed weights too); copy stays friendly. The figures
    // take the UI language's decimal separator (#804), like `fmtGbNum`.
    const ramTooLow = m.insufficientRam === true
    const minRam = m.recommendedMinRamGb.toLocaleString(lang)
    const ramHint = ramTooLow
      ? t('models.ram.needs', { min: minRam }) +
        (machineRam != null ? t('models.ram.machine', { ram: machineRam.toLocaleString(lang) }) : '') +
        t('models.ram.advice')
      : undefined
    // A start in flight (server truth, survives a revisit): this model's own, or any.
    const thisStarting = runtime?.startingModelId === m.id
    const anyStarting = runtime?.startingModelId != null
    const taskLabel = TASKS.find((entry) => entry.value === modelTask(m))?.label ?? null
    const stateBadge = m.noChecksum ? NO_CHECKSUM_BADGE : STATE_BADGE[m.state]
    return (
      // #35: not-yet-downloaded cards render visually quieter (`.model-card-missing`) so
      // the models that are usable right now stand out when scanning the list.
      <div className={`card model-card${installed ? '' : ' model-card-missing'}`} key={m.id}>
        <div className="model-head">
          <div>
            <div className="model-title">{m.displayName}</div>
            <div className="model-sub">
              {/* #847 review: no task label (and no crash) for a model with no task; only the trailing
                  newer-app section holds one today, and it has its own card. */}
              {taskLabel && <>{t(taskLabel)}{' · '}</>}
              {t('models.usesSpace', { size: fmtGb(null, m.sizeOnDiskGb, lang) })}
              {' · '}{t('models.library.memory', { size: fmtGbNum(m.recommendedMinRamGb, lang) })}
            </div>
            {automatic && <p className="hint hint-tight">{t(automaticUsageKey(m, installed))}</p>}
          </div>
          <div className="badges">
            {active && (
              <Badge tone="success" icon="●">
                {t('models.badge.active')}
              </Badge>
            )}
            {m.recommended && (
              <Badge tone="accent" icon="★">
                {t('models.badge.recommended')}
              </Badge>
            )}
            {ramTooLow && (
              <Badge tone="warning" icon="⚠" title={ramHint}>
                {t('models.badge.ramNeeded', { min: minRam })}
              </Badge>
            )}
            <Badge tone={stateBadge.tone} icon={stateBadge.icon}>
              {t(stateBadge.labelKey)}
            </Badge>
            {m.state === 'running' && runtime?.unresponsive && (
              <Badge tone="warning" icon="⚠">
                {t('models.badge.notResponding')}
              </Badge>
            )}
          </div>
        </div>

        {/* #932: what a model with no checksum on record needs, in place of a repair it cannot have. */}
        {m.noChecksum && <p className="hint">{t('models.noChecksum.hint')}</p>}
        {m.role === 'transcriber' && voiceEngineUnsupported && (
          <p className="hint">{t('models.transcriber.engineUnsupported')}</p>
        )}
        {/* #530: the voice engine is on the drive, but the OS refused to start it. #532: damaged
            files also offer "Install the voice engine again". */}
        {m.role === 'transcriber' && voiceEngineProblem && (
          <EngineProblemNotice
            problem={voiceEngineProblem}
            variant="hint"
            onRecheck={recheckEngine}
            reinstall={engineReinstall(voiceEngineProblem)}
            t={t}
          />
        )}

        {/* #600: a calm note, not a confirmation dialog (owner decision): an answer is being written
            on this model, and stopping or switching ends it — its text so far is kept. */}
        {m.state === 'running' && runtime?.answering && (
          <p className="hint" role="status">
            {t('models.answeringNote')}
          </p>
        )}
        {/* #599: the running model stopped answering (a failed health re-check, or an answer that
            timed out). The app offers the restart and never performs it on its own. */}
        {m.state === 'running' && runtime?.unresponsive && (
          <p className="hint" role="status">
            {t('models.notRespondingHint')}
          </p>
        )}

        <div className="model-row-actions">
        {!automatic && (
          // A "Not downloaded" card shows ONE clear action — Download (rendered below) —
          // plus, in demo-capable developer mode, "Try in demo mode". The disabled
          // "Select" / "Start runtime" buttons are noise before the weights exist, so they
          // are hidden until the model is downloaded (§3/§7 hide the machinery). Once
          // installed, ONE primary "Use this model" action selects it and starts its runtime
          // (beta #27, D70) — a first-time user no longer has to guess whether Select or Start
          // leads to chatting. Stop / Starting… / the Active badge carry the runtime state.
          (installed || canMockStart || thisStarting || m.state === 'running') && (
            <div className="model-actions">
              {m.state === 'running' ? (
                <>
                  {runtime?.unresponsive && (
                    <Button
                      size="sm"
                      variant="primary"
                      disabled={busy !== null}
                      onClick={() => run('restart', restartModel)}
                    >
                      {t('models.restart')}
                    </Button>
                  )}
                  <Button size="sm" disabled={busy !== null} onClick={() => run('stop', () => window.api.stopRuntime())}>
                    {t('models.stopRuntime')}
                  </Button>
                </>
              ) : thisStarting ? (
                // Server-truth "Starting…": disabled, and it survives leaving + revisiting
                // the screen (the cause of the accidental restart).
                <Button size="sm" disabled title={t('models.startingTitle')}>
                  <Spinner /> {t('models.starting')}
                </Button>
              ) : installed ? (
                // The merged action (select + start, MAIN-side via useModel). NOT disabled on
                // `active`: an already-active model that isn't running still needs this to start
                // (select is idempotent, the start actually loads it). Disabled only by the RAM
                // gate / another button busy / another model starting.
                <Button
                  size="sm"
                  variant="primary"
                  disabled={ramTooLow || busy !== null || anyStarting}
                  onClick={() => run(`use-${m.id}`, () => window.api.useModel(m.id))}
                  title={ramTooLow ? ramHint : t('models.useTitle')}
                >
                  {t('models.use')}
                </Button>
              ) : (
                // Not installed but demo-capable (developer + policy gated in MAIN via
                // `startableAsMock`): "Try in demo mode" lets the dev try the app with no
                // weights. End users never reach this branch (the gate is off for them).
                <Button
                  size="sm"
                  disabled={busy !== null || anyStarting}
                  onClick={() => run(`start-${m.id}`, () => window.api.startRuntime(m.id))}
                  title={t('models.startMockTitle')}
                >
                  {t('models.startMock')}
                </Button>
              )}
            </div>
          )
        )}

        {/* #539: the vision model has nothing to start; the one thing to do is use it on Images. */}
        {m.role === 'vision' && installed && onNavigate && (
          <div className="model-actions">
            <Button size="sm" onClick={() => onNavigate('images')}>
              {t('models.vision.goToImages')}
            </Button>
          </div>
        )}

        {/* While the panel above owns this model's job — live progress OR a retained terminal
            result — the row must not repeat it. After Dismiss the row's own status/recovery UI
            (Resume, the unverified note) comes back exactly as before. */}
        {panelJob?.modelId !== m.id && downloadSection(m)}
        </div>

        {/* Checksums / quantization ids / paths / runtime internals live here, closed
            by default (guidelines §2/§3 principle 3 — never in the everyday path). */}
        <details className="tech-details">
          <summary>{t('models.tech.summary')}</summary>
          <div className="tech-details-body">
            <p className="hint">{t(plainHintKey(m))}</p>
            {ramTooLow && <Banner tone="warning">{ramHint}</Banner>}
            <dl className="kv">
              <dt>{t('models.tech.id')}</dt>
              <dd>
                <code>{m.id}</code>
              </dd>
              <dt>{t('models.tech.family')}</dt>
              <dd>{m.family}</dd>
              <dt>{t('models.tech.format')}</dt>
              <dd>{m.format}</dd>
              <dt>{t('models.tech.runtime')}</dt>
              <dd>{m.runtime}</dd>
              <dt>{t('models.tech.license')}</dt>
              <dd>{m.license}</dd>
              <dt>{t('models.tech.sizeOnDisk')}</dt>
              <dd>{fmtGbNum(m.sizeOnDiskGb, lang)}</dd>
              <dt>{t('models.tech.minRam')}</dt>
              <dd>{fmtGbNum(m.recommendedMinRamGb, lang)}</dd>
              <dt>{t('models.tech.recRam')}</dt>
              <dd>{fmtGbNum(m.recommendedRamGb, lang)}</dd>
              <dt>{t('models.tech.context')}</dt>
              {/* RD-3: locale-formatted like every other figure in this block (fmtGbNum / the
                  context-size picker below) — a German UI reads "32.768", not raw "32768". */}
              <dd>{contextSizeText('models.tech.contextValue', m.recommendedContextTokens)}</dd>
              <dt>{t('models.tech.file')}</dt>
              <dd>
                <code>{m.localPath}</code>
              </dd>
            </dl>
            <Button
              size="sm"
              disabled={busy !== null}
              onClick={() => run(`verify-${m.id}`, () => window.api.verifyModel(m.id))}
              title={t('models.verifyTitle')}
            >
              {busy === `verify-${m.id}` ? (
                <>
                  <Spinner /> {t('models.verifying')}
                </>
              ) : (
                t('models.verify')
              )}
            </Button>
          </div>
        </details>
      </div>
    )
  }

  // #847: a model for a newer HilbertRaum. Display only (the main process refuses it on every path), so there is
  // nothing to select, start, download or verify, and it must not look like a broken download: a neutral badge
  // instead of the error-tone "Unsupported" state, and no technical-details disclosure with its Verify button.
  function newerAppCard(m: ModelInfo): JSX.Element {
    return (
      <div className="card model-card model-card-missing" key={m.id}>
        <div className="model-head">
          <div>
            <div className="model-title">{m.displayName}</div>
            <p className="hint hint-tight">{t('models.newerApp.hint')}</p>
          </div>
          <div className="badges">
            <Badge tone="neutral" icon="↑">
              {t('models.newerApp.badge')}
            </Badge>
          </div>
        </div>
      </div>
    )
  }

  function libraryRows(groups: { group: ModelVariantGroup; expanded: boolean }[]): JSX.Element[] {
    return groups.map(({ group, expanded }) => {
      if (group.models.length === 1) return card(group.models[0])
      // F5: the collapsed card is the group FACE (an obtainable member of the leader's priority
      // cohort), then every other variant once, in the order the sort produced.
      const ordered = variantGroupOrder(group)
      return (
        // Heading outline (O5): screen <h2> → task section <h3> → this group <h4>.
        <section className="model-variant-group" key={group.key} aria-label={group.name}>
          <div className="model-variant-heading">
            <h4>{group.name}</h4>
            <Button size="sm" variant="ghost" aria-expanded={expanded} onClick={() => {
              setUserToggledGroups((previous) => new Map(previous).set(group.key, !expanded))
            }}>
              {t(expanded ? 'models.library.hideVariants' : 'models.library.showVariants', { count: group.models.length })}
            </Button>
          </div>
          {card(ordered[0])}
          {expanded && ordered.slice(1).map(card)}
        </section>
      )
    })
  }

  function confirmDialog(m: ModelInfo): JSX.Element | null {
    if (!m.download) return null
    const needsAck = !m.download.licenseApproved
    const license = httpsLink(m.download.licenseUrl)
    const close = (): void => {
      setConfirming(null)
      setLicenseAck(false)
    }
    return (
      <ConfirmDialog
        open
        title={t('models.confirm.title', { name: m.displayName })}
        confirmLabel={t('models.confirm.start')}
        t={t}
        confirmDisabled={needsAck && !licenseAck}
        onConfirm={() => void startDownload(m)}
        onCancel={close}
      >
        <dl className="kv">
          <dt>{t('models.confirm.size')}</dt>
          <dd>{fmtGb(m.download.sizeBytes, m.sizeOnDiskGb, lang)}</dd>
          <dt>{t('models.confirm.license')}</dt>
          <dd>
            {m.license}
            {/* #804: the link on a line of its own, so no language needs a separator before it. */}
            {license && (
              <div>
                <a href={license.href} target="_blank" rel="noreferrer">
                  {t('models.confirm.readLicense')}
                </a>
                {/* #236: the destination host is shown, like the download address below it. */}
                {' ('}
                <code>{license.host}</code>
                {')'}
              </div>
            )}
          </dd>
          <dt>{t('models.confirm.from')}</dt>
          <dd>
            <code>{m.download.url}</code>
          </dd>
        </dl>
        <p className="hint">{t('models.confirm.hint')}</p>
        {needsAck && (
          <label className="toggle">
            <input
              type="checkbox"
              checked={licenseAck}
              onChange={(e) => setLicenseAck(e.target.checked)}
            />
            <span>{t('models.confirm.licenseAck')}</span>
          </label>
        )}
      </ConfirmDialog>
    )
  }

  // The engine banner: the SAME progress/cancel/error shape serves two distinct cases —
  // the chat engine (llama.cpp) missing is a strong warning (started models would fall
  // back to the demo runtime), while only the voice engine (whisper.cpp) missing is a
  // quiet, accurate note (chat already works — voice dictation is the only thing waiting).
  // The caller picks the tone + copy so the two never get conflated (an installed chat
  // engine must NOT show a "models run in demo mode" alarm).
  function engineBanner(opts: {
    tone: 'warning' | 'info'
    titleKey: MessageKey
    explainKey: MessageKey
    installKey: MessageKey
  }): JSX.Element {
    return (
      <Banner tone={opts.tone}>
        <div className="engine-install">
          <strong>{t(opts.titleKey)}</strong>
          <p className="hint hint-lede">
            {t(opts.explainKey)}
          </p>
          {engineJobControls({
            job: engineJobFor(engineJob, 'install'),
            installKey: opts.installKey,
            primary: true,
            onStart: () => void askEngine(undefined, opts.titleKey, opts.installKey)
          })}
        </div>
      </Banner>
    )
  }

  /**
   * #516: the quiet notice for engines older than this app's pin — one notice, one Update for all
   * of them, the same job controls as the install banners. Main downloads first and pauses the
   * engine's users only for the file swap, then starts the selected model again.
   */
  function engineUpdateNotice(families: string[]): JSX.Element {
    const chat = families.includes('llama_cpp')
    const voice = families.includes('whisper_cpp')
    const titleKey: MessageKey =
      chat && voice ? 'models.engineUpdate.bothTitle' : chat ? 'models.engineUpdate.title' : 'models.engineUpdate.voiceTitle'
    return (
      <Banner tone="info">
        <div className="engine-install">
          <strong>{t(titleKey)}</strong>
          <p className="hint hint-lede">{t('models.engineUpdate.explain')}</p>
          {engineJobControls({
            job: engineJobFor(engineJob, 'update'),
            installKey: 'models.engineUpdate.update',
            primary: false,
            onStart: () =>
              void askEngine({ families: families as RuntimeFamily[], update: true }, titleKey, 'models.engineUpdate.update')
          })}
        </div>
      </Banner>
    )
  }

  /**
   * #532: what the "can't run" notice offers for damaged engine files — "Install … again" through
   * the same job, gates and progress as the install banners. Only for that verdict (and not once a
   * fresh copy also failed), and only for a family the installer can fetch here.
   */
  function engineReinstall(problem: EngineProblem | null): EngineProblemReinstall | undefined {
    if (!problem || !engineProblemOffersReinstall(problem)) return undefined
    if (!(engine?.reinstallableFamilies ?? []).includes(problem.family)) return undefined
    const job = engineJobFor(engineJob, problem.family)
    const voice = problem.family === 'whisper_cpp'
    const installKey: MessageKey = voice ? 'models.engineProblem.voiceReinstall' : 'models.engineProblem.reinstall'
    return {
      control: engineJobControls({
        job,
        installKey,
        // The chat banner's reinstall is the fix and leads; the voice hint stays quiet (§11.17 #5).
        primary: !voice,
        onStart: () => void askEngine({ families: [problem.family], reinstall: true }, installKey, installKey)
      }),
      policyAllows: policy?.policy.network.allowModelDownloads === true,
      live: job != null && ENGINE_JOB_LIVE.has(job.status)
    }
  }

  /**
   * The engine job's controls for one surface: its progress and Cancel while it runs, else the
   * start button (Try again after a failure, with the error) behind the download gate, whose
   * reason is shown. `job` is the job THIS surface shows (`engineJobFor`), or null.
   */
  function engineJobControls(opts: {
    job: EngineDownloadJob | null
    installKey: MessageKey
    primary: boolean
    onStart: () => void
  }): JSX.Element {
    const j = opts.job
    const live = j != null && ENGINE_JOB_LIVE.has(j.status)
    // One engine job at a time (main refuses a second): while another surface's job runs, wait.
    const otherLive = !live && engineJob != null && ENGINE_JOB_LIVE.has(engineJob.status)
    const pct =
      j && j.totalBytes && j.totalBytes > 0
        ? Math.min(100, Math.round((j.receivedBytes / j.totalBytes) * 100))
        : null
    return live && j ? (
      <>
        <Progress
          label={
            j.status === 'extracting'
              ? t('models.engine.extracting')
              : j.status === 'verifying'
                ? t('models.engine.verifying')
                : pct != null
                  ? t('models.engine.progress', { pct })
                  : t('models.engine.downloadingNoTotal')
          }
          value={pct != null && j.status === 'downloading' ? j.receivedBytes : undefined}
          max={pct != null && j.status === 'downloading' ? (j.totalBytes ?? undefined) : undefined}
        />
        {/* SH-1 (#144): the multi-hundred-MB engine fetch was the one long-running
            network action with no Cancel (cancelEngineDownload had zero callers).
            Mirrors the model-download cancel incl. its error surfacing; main treats
            verifying/extracting as cancellable states (F-33), so no disable here. */}
        <Button
          size="sm"
          onClick={() =>
            window.api
              .cancelEngineDownload(j.jobId)
              .then((next) => {
                rememberedEngineJob = next
                if (mountedRef.current) setEngineJob(next)
              })
              .catch((e) => mountedRef.current && setError(friendlyIpcError(e)))
          }
        >
          {t('models.download.cancel')}
        </Button>
      </>
    ) : (
      <>
        {j?.status === 'failed' && j.error && (
          <p className="hint mt-0">
            {j.error}
          </p>
        )}
        <Button
          size="sm"
          variant={opts.primary ? 'primary' : undefined}
          disabled={!downloadsEnabled || otherLive}
          title={downloadsBlockedReason ?? undefined}
          onClick={opts.onStart}
        >
          {j?.status === 'failed' ? t('models.engine.retry') : t(opts.installKey)}
        </Button>
        {downloadsBlockedReason && (
          <p className="hint mb-0">
            {downloadsBlockedReason}
          </p>
        )}
      </>
    )
  }

  return (
    <div className="screen models-screen">
      <h1>{t('models.title')}</h1>
      <p className="lead">{t('models.lead')}</p>

      {/* #382: a screen-level, EXPLICIT full check. Ordinary visits verify lazily (only the
          active model), so nothing here hashes on its own any more; this is the one action
          that walks every present weight — 25.5 minutes for 39.44 GB on the #330 slow drive.
          #420: it can now be STOPPED. The bar renders IN PLACE below it with a Cancel button
          beside it, the same Progress + Cancel pairing the download panels use; the Cancel
          shows as soon as the pass starts, before the first progress event has arrived. */}
      <div className="models-verify-all">
        <Button
          size="sm"
          disabled={busy !== null || verifyRun !== null}
          title={t('models.verifyAllTitle')}
          onClick={() => void verifyAllModelFiles()}
        >
          {busy === 'verify-all' || verifyRun !== null ? (
            <>
              <Spinner /> {t('models.verifyingAll')}
            </>
          ) : (
            t('models.verifyAll')
          )}
        </Button>
        <p className="hint">{t('models.verifyAllHint')}</p>
        {verifyBar()}
        {verifyRun !== null && (
          <Button size="sm" disabled={verifyCancelling} onClick={() => void cancelVerifyAll()}>
            {verifyCancelling ? t('models.verifyAllStopping') : t('models.verifyAllStop')}
          </Button>
        )}
      </div>

      {anyDownloadable && downloadsBlockedReason && <Banner tone="info">{downloadsBlockedReason}</Banner>}

      {/* #530: the chat engine IS on the drive, but the OS refused to start it — the same strong
          place and shape as the missing-engine banner below (models answer in demo mode either
          way), with what the user can do here: Check again after installing the fix, and — for
          damaged engine files (#532) — "Install the AI engine again" first. */}
      {chatEngineProblem && (
        <EngineProblemNotice
          problem={chatEngineProblem}
          variant="banner"
          onRecheck={recheckEngine}
          // The demo note only while no real runtime answers (a `cpu/` build may run beside it).
          demoNote={!(runtime?.running === true && runtime.backend != null && runtime.backend !== 'mock')}
          reinstall={engineReinstall(chatEngineProblem)}
          t={t}
        />
      )}

      {/* Chat engine (llama.cpp) missing → real "demo mode" warning. Voice engine
          (whisper.cpp) missing on its own → a quiet note: chat already works, only
          dictation waits. An installed chat engine never shows the alarming banner. */}
      {engine && engine.available && engine.missingFamilies.includes('llama_cpp') &&
        engineBanner({
          tone: 'warning',
          titleKey: 'models.engine.title',
          explainKey: 'models.engine.explain',
          installKey: 'models.engine.install'
        })}
      {/* #530: not while the chat engine can't run — its copy says chat already works, which
          would contradict the banner above (and on Linux the same missing library would block
          the voice engine too). */}
      {engine &&
        engine.available &&
        !chatEngineProblem &&
        !engine.missingFamilies.includes('llama_cpp') &&
        engine.missingFamilies.includes('whisper_cpp') &&
        engineBanner({
          tone: 'info',
          titleKey: 'models.voiceEngine.title',
          explainKey: 'models.voiceEngine.explain',
          installKey: 'models.voiceEngine.install'
        })}

      {/* #516: an engine on the drive is older than this app's pin — a quiet offer, never an alarm:
          the engine works, the update only brings it to the version this app was tested with. */}
      {updatableFamilies.length > 0 && engineUpdateNotice(updatableFamilies)}

      {/* #339 P8-2 (the owner's ruling): a QUIET row for the OPTIONAL knowledge-pack tools —
          visually lighter than the two engine banners above (a hint line, not a Banner) — shown
          only while `missingOptionalFamilies` names `kiwix_tools` (never when installed or
          absent from the field, e.g. an older main). "Install…" opens the SAME consent dialog
          the Knowledge-packs panel's own notice opens. */}
      {engine && packToolsMissing && (
        <div className="packs-tools-hint">
          <p className="hint">{t('models.packTools.row')}</p>
          {packToolsInstall.live && packToolsInstall.job ? (
            <div className="download-progress">
              <Progress
                label={
                  packToolsInstall.job.status === 'extracting'
                    ? t('packs.tools.extracting')
                    : packToolsInstall.job.status === 'verifying'
                      ? t('packs.tools.verifying')
                      : packToolsPct != null
                        ? t('packs.tools.progress', { pct: packToolsPct })
                        : t('packs.tools.downloadingNoTotal')
                }
                value={packToolsPct != null ? packToolsInstall.job.receivedBytes : undefined}
                max={packToolsPct != null ? (packToolsInstall.job.totalBytes ?? undefined) : undefined}
              />
              <Button size="sm" onClick={() => void packToolsInstall.cancel()}>
                {t('models.download.cancel')}
              </Button>
            </div>
          ) : packToolsInstall.job?.status === 'failed' ? (
            <div className="download-progress">
              <p className="hint">{t('packs.tools.failed')}</p>
              {packToolsInstall.job.error && <p className="hint">{packToolsInstall.job.error}</p>}
              <Button size="sm" onClick={() => setPackToolsDialogOpen(true)}>
                {t('models.engine.retry')}
              </Button>
            </div>
          ) : (
            <Button size="sm" onClick={() => setPackToolsDialogOpen(true)}>
              {t('models.packTools.install')}
            </Button>
          )}
        </div>
      )}

      {/* #410: the quiet OCR row (a hint line, like the knowledge-pack tools row above). */}
      {ocrRowVisible && (
        <div className="ocr-install-row">
          <p className="hint">
            {t(ocrOnlyOrientationMissing ? 'models.ocr.rowOrientation' : 'models.ocr.row')}
          </p>
          <OcrInstallControl install={ocrInstall} onRequestInstall={() => setOcrDialogOpen(true)} t={t} />
        </div>
      )}

      {models.length === 0 && (
        <EmptyState
          title={t('models.empty.title')}
          line={
            <>
              {t('models.empty.lineBefore')}
              <code>model-manifests/</code>
              {t('models.empty.lineAfter')}
            </>
          }
        />
      )}

      {activeChat && (
        <>
          <div className="section-title">{t('models.section.yourModel')}</div>
          {card(activeChat)}
        </>
      )}

      {/* Context-size picker (2026-07-04 user report): the truncation notice already pointed
          users here to "raise the context size", and the setting existed but was never applied
          for catalog models (the manifest recommendation always won). "Auto" keeps the model's
          recommended window; a fixed pick becomes the launched --ctx-size at the next start. */}
      {settings && chat.length > 0 && (
        <div className="card">
          <h2>{t('models.context.title')}</h2>
          <label className="hint hint-block">
            {t('models.context.label')}{' '}
            <select
              className="select"
              value={settings.contextTokensOverride != null ? String(settings.contextTokensOverride) : 'auto'}
              onChange={(e) => void onContextSizeChange(e.target.value)}
            >
              {/* Issue #43: name the number "Auto" resolves to for the active model — it is
                  often the LARGEST choice in this list, and an unlabeled "Auto" read as
                  "small default", sending users into a fixed pick that capped the window. */}
              <option value="auto">
                {activeChat
                  ? contextSizeText(
                      'models.context.autoResolved',
                      activeChat.recommendedContextTokens || settings.contextTokens
                    )
                  : t('models.context.auto')}
              </option>
              {CONTEXT_SIZE_PRESETS.map((n) => (
                <option key={n} value={String(n)}>
                  {contextSizeText('models.tech.contextValue', n)}
                </option>
              ))}
              {/* RD-4: an override outside the preset rungs (an older release's preset, a hand-
                  edited settings file) must still render as the selected value — a <select> whose
                  value matches no option silently renders BLANK. Same label style as the rungs. */}
              {settings.contextTokensOverride != null &&
                !(CONTEXT_SIZE_PRESETS as readonly number[]).includes(settings.contextTokensOverride) && (
                  <option value={String(settings.contextTokensOverride)}>
                    {contextSizeText('models.tech.contextValue', settings.contextTokensOverride)}
                  </option>
                )}
            </select>
          </label>
          <p className="hint">{t('models.context.hint')}</p>
          {settings.contextTokensOverride != null &&
            settings.contextTokensOverride >= CONTEXT_SIZE_WARNING_MIN && (
              <p className="hint context-size-warning">{t('models.context.bigWarning')}</p>
            )}
          {runtime?.running && <p className="hint">{t('models.context.restartHint')}</p>}
        </div>
      )}

      <section ref={libraryRef} className="model-library" aria-label={t('models.library.title')}>
        <h2>{t('models.library.title')}</h2>
        <SegmentedControl
          ariaLabel={t('models.library.view')}
          value={libraryView ?? 'browse'}
          options={[
            { value: 'installed', label: t('models.library.onDrive') },
            { value: 'browse', label: t('models.library.browse') }
          ]}
          onChange={setLibraryView}
        />
        <div className="model-library-filters">
          <label className="model-library-search">
            {t('models.library.search')}
            <input className="input" type="search" value={query} onChange={(e) => setQuery(e.target.value)}
              placeholder={t('models.library.searchPlaceholder')} />
          </label>
          <label>
            {t('models.library.task')}
            <select className="select" value={task} onChange={(e) => setTask(e.target.value as ModelTask | 'all')}>
              <option value="all">{t('models.library.allTasks')}</option>
              {TASKS.map((entry) => <option key={entry.value} value={entry.value}>{t(entry.label)}</option>)}
            </select>
          </label>
          <label>
            {t('models.library.family')}
            <select className="select" value={family} onChange={(e) => setFamily(e.target.value)}>
              <option value="all">{t('models.library.allFamilies')}</option>
              {families.map((name) => <option key={name} value={name}>{name}</option>)}
              {/* #313 — a family already selected stays the rendered value even when the current
                  view/task can't yield it: never blank, never silently swapped to another family. */}
              {familyOutOfView && (
                <option value={family}>{t('models.library.familyNotInView', { name: family })}</option>
              )}
            </select>
          </label>
          {family !== 'all' && <Button size="sm" onClick={() => setFamily('all')}>
            {t('models.library.resetFamily')}
          </Button>}
          {hasFilters && <Button size="sm" onClick={() => { setQuery(''); setTask('all'); setFamily('all') }}>
            {t('models.library.clear')}
          </Button>}
        </div>
        {/* Progress/cancel remains reachable even when filters or a collapsed group hide its row —
            and a FAILED or unverified result stays here, named, with Retry / Dismiss, until the
            user acts, a new download is accepted, or the download ends verified/cancelled
            (design-guidelines §15 "Terminal download results"). */}
        {panelJob && <div className="model-library-download" role="region" aria-label={t('models.library.download')}>
          {/* #315 — named here only while the row below is NOT on screen; when the row is
              rendered (visible, single/face, or an expanded group member) it already carries
              the identity, so naming it twice would be redundant. */}
          {!panelRowRendered && <strong>{panelName}</strong>}
          {/* ONE always-mounted alert node for the whole panel lifetime: empty while the download
              runs, filled on the terminal transition. Same wrapper shape as ErrorBanner (audit
              M-U1) — a live region that only appears at failure is not reliably announced.
              The Banners inside pass role={null}: role="status" is itself a live region, and a
              nested one swallows the announcement (#436). Nothing in here may carry a role. */}
          <div className="error-banner-region" role="alert" aria-live="assertive">
            {panelJob.status === 'failed' && (
              <Banner tone="error" role={null}>
                <p>{t('models.download.failed', { name: panelName })}</p>
                {panelJob.error && <p>{panelJob.error}</p>}
              </Banner>
            )}
            {panelJob.status === 'done' && panelJob.unverified && (
              <Banner tone="warning" role={null}>
                {t('models.download.unverifiedBefore')}
                <code>verify-models --generate</code>
                {t('models.download.unverifiedAfter')}
              </Banner>
            )}
          </div>
          {panelLive ? (
            panelModel && downloadSection(panelModel)
          ) : (
            <>
              <div className="model-library-download-actions">
                <Button
                  size="sm"
                  variant="primary"
                  disabled={retryBlockedReason != null}
                  title={
                    retryBlockedReason ??
                    t('models.download.titled', {
                      name: panelName,
                      size: fmtGb(
                        retryTarget?.download?.sizeBytes ?? null,
                        retryTarget?.sizeOnDiskGb ?? 0,
                        lang
                      )
                    })
                  }
                  // The EXISTING confirmation, with this variant's license link and a reset
                  // acknowledgement — a retry never silently accepts a pending license.
                  onClick={() => {
                    if (!retryTarget) return
                    setLicenseAck(false)
                    setConfirming(retryTarget)
                  }}
                >
                  {t('models.download.retry')}
                </Button>
                <Button
                  size="sm"
                  onClick={() => {
                    dismissedJobId = panelJob.jobId
                    setDismissedJob(panelJob.jobId)
                    // #314: tell the main process too, so a renderer reload does not resurrect it.
                    // Fire-and-forget — the in-session hiding above is already done.
                    void window.api.dismissDownloadJob(panelJob.jobId).catch(() => undefined)
                  }}
                >
                  {t('models.download.dismiss')}
                </Button>
              </div>
              {retryBlockedReason && <p className="hint mb-0">{retryBlockedReason}</p>}
            </>
          )}
        </div>}
        <p className="hint" role="status">{tCount('models.library.results', visibleModels.length + newerRows.length)}</p>
        {visibleModels.length === 0 && newerRows.length === 0 ? (
          <div className="model-library-empty">
            {/* #313 — a selected family the view/task combo can never satisfy gets its own
                explanation instead of the generic "no models match" copy, naming the family and
                (On this drive) the count Browse would show for it. */}
            {familyOutOfView ? (
              currentView === 'installed' ? (
                <>
                  <p>{tCount('models.library.noFamilyOnDrive', browseRowCountForFamily, { family })}</p>
                  <Button onClick={() => setLibraryView('browse')}>
                    {t('models.library.browse')}
                  </Button>
                </>
              ) : (
                <p>{t('models.library.noFamilyForTask', { family })}</p>
              )
            ) : (
              <>
                <p>{t(hasFilters ? 'models.library.noMatches' : currentView === 'installed'
                  ? activeChat && isModelInstalled(activeChat) ? 'models.library.onlyActive' : 'models.library.noneInstalled'
                  : 'models.library.noAlternatives')}</p>
                {currentView === 'installed' && <Button onClick={() => setLibraryView('browse')}>
                  {t('models.library.browse')}
                </Button>}
              </>
            )}
          </div>
        ) : (
          <>
            {sections.map(({ entry, groups }) => {
              return groups.length > 0 && <section key={entry.value} aria-label={t(entry.label)}>
                <h3 className="model-task-heading">{t(entry.label)}</h3>
                {libraryRows(groups)}
              </section>
            })}
            {/* #847: after the five task sections, only when non-empty (design-guidelines §15). */}
            {newerRows.length > 0 && (
              <section key="newer-app" aria-label={t('models.newerApp.heading')}>
                <h3 className="model-task-heading">{t('models.newerApp.heading')}</h3>
                {newerRows.map(newerAppCard)}
              </section>
            )}
          </>
        )}
      </section>

      {/* Always-mounted alert region (audit M-U1) — announced on first appearance. */}
      <ErrorBanner message={error} t={t} />

      {confirming && confirmDialog(confirming)}

      {engineConfirm && (
        <EngineConfirmDialog
          open
          preview={engineConfirm.preview}
          title={t(engineConfirm.titleKey)}
          confirmLabel={t(engineConfirm.confirmKey)}
          downloadsEnabled={downloadsEnabled}
          blockedReason={downloadsBlockedReason}
          onConfirm={() => {
            const { request } = engineConfirm
            setEngineConfirm(null)
            void startEngineJob(request)
          }}
          onCancel={() => setEngineConfirm(null)}
          lang={lang}
          t={t}
        />
      )}

      {packToolsInstall.family && (
        <KnowledgePackToolsDialog
          open={packToolsDialogOpen}
          family={packToolsInstall.family}
          downloadsEnabled={packToolsInstall.downloadsEnabled}
          blockedReason={packToolsInstall.blockedReason}
          onConfirm={() => {
            setPackToolsDialogOpen(false)
            void packToolsInstall.start()
          }}
          onCancel={() => setPackToolsDialogOpen(false)}
          t={t}
          lang={lang}
        />
      )}

      {ocrInstall.status && (
        <OcrInstallDialog
          open={ocrDialogOpen}
          status={ocrInstall.status}
          downloadsEnabled={ocrInstall.downloadsEnabled}
          blockedReason={ocrInstall.blockedReason}
          onConfirm={() => {
            setOcrDialogOpen(false)
            void ocrInstall.start()
          }}
          onCancel={() => setOcrDialogOpen(false)}
          lang={lang}
          t={t}
        />
      )}
    </div>
  )
}