Skip to content

AI, fully local on your computer.

160 KB
Raw Blame
// @vitest-environment jsdom
import { describe, it, expect, vi, afterEach, beforeEach, type Mock } from 'vitest'
import { act, render, screen, cleanup, within, waitFor, getDefaultNormalizer } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
  ModelsScreen,
  __resetModelsScreenMemoryForTests
} from '../../src/renderer/screens/ModelsScreen'
import {
  DEFAULT_SETTINGS,
  type AppStatus,
  type DownloadJob,
  type EngineOptionalFamily,
  type EngineProblem,
  type EngineStatus,
  type EngineVersionInfo,
  type ModelInfo,
  type ModelVerifyProgress,
  type PolicyStatus,
  type RuntimeStatus
} from '../../src/shared/types'
import { t, tCount } from '../../src/shared/i18n'
import { I18nProvider, UI_LANGUAGE_STORAGE_KEY } from '../../src/renderer/i18n'
import { ENGINE_MISSING, engineJob, enginePreview, modelInfo, stubModelsApi } from '../helpers/model-fixtures'
import { catalogOf } from '../helpers/i18n-catalogs'
import { renderInLanguage } from '../helpers/render-language'
import { assertNoUnexpectedApiCalls } from '../helpers/renderer'
import { STOPPED_RUNTIME, appStatus, makePolicyStatus } from '../helpers/status'
import { groupModelVariants, variantGroupFace } from '../../src/renderer/lib/modelLibrary'
import { orderPickerModels } from '../../src/renderer/lib/modelAvailability'

// Phase 18 — the Models screen download surface: the gate states (why downloads are
// unavailable: policy vs. Settings), the per-download confirmation (license
// acknowledgement when the review is not approved), and the progress/cancel affordance.

function model(over: Partial<ModelInfo> = {}): ModelInfo {
  return modelInfo({
    id: 'qwen3-4b-instruct-q4',
    displayName: 'Qwen3 4B Instruct',
    family: 'qwen3',
    sizeOnDiskGb: 2.7,
    recommendedMinRamGb: 8,
    recommendedRamGb: 16,
    recommendedContextTokens: 4096,
    localPath: 'models/chat/qwen3-4b-instruct-q4.gguf',
    download: {
      url: 'https://example.test/qwen3-4b.gguf',
      sizeBytes: 2_900_000_000,
      licenseUrl: 'https://example.test/license',
      licenseApproved: true
    },
    ...over
  })
}

function policyStatus(opts: { downloadsAllowed: boolean; settingOn: boolean }): PolicyStatus {
  return makePolicyStatus({
    network: { allowModelDownloads: opts.downloadsAllowed },
    allowNetworkSetting: opts.settingOn
  })
}

/** #532: the chat engine is on the drive, but the OS found its own files damaged. */
const DAMAGED_ENGINE: EngineProblem = { family: 'llama_cpp', reason: 'files-damaged', os: 'win', exit: 'exit code 0xC0000135' }

function stub(opts: {
  models?: ModelInfo[]
  policy?: PolicyStatus
  activeModelId?: string | null
  downloadModel?: Mock
  getDownloadJob?: Mock
  /** Overrides on the base status (#527: `transcriberMissing`). */
  appStatus?: Partial<AppStatus>
  /** The engine status (#527 banner cases); absent = every engine in place. */
  engine?: EngineStatus
}): void {
  stubModelsApi({
    listModels: vi.fn(async () => opts.models ?? [model()]),
    getSettings: vi.fn(async () => ({ ...DEFAULT_SETTINGS, activeModelId: opts.activeModelId ?? null })),
    getAppStatus: vi.fn(async () => appStatus({ machineRamGb: 32, ...opts.appStatus })),
    ...(opts.policy ? { getPolicy: vi.fn(async () => opts.policy as PolicyStatus) } : {}),
    ...(opts.engine ? { getEngineStatus: vi.fn(async (): Promise<EngineStatus> => opts.engine as EngineStatus) } : {}),
    downloadModel: (opts.downloadModel ?? vi.fn()),
    getDownloadJob: (opts.getDownloadJob ?? vi.fn()),
    dismissDownloadJob: vi.fn(async () => undefined)
  })
}

afterEach(() => {
  try {
    assertNoUnexpectedApiCalls()
  } finally {
    cleanup()
  }
})

// The screen deliberately keeps the download job, its model's name and any dismissed result in
// MODULE state so leaving and re-entering the screen resumes/restores them. Tests must therefore
// start from a known state instead of inheriting whatever the previous case left behind.
beforeEach(() => {
  __resetModelsScreenMemoryForTests()
})

describe('ModelsScreen — download gates (plan §6.1: explain WHY, policy vs Settings)', () => {
  it('disables Download and explains when the drive policy denies downloads', async () => {
    stub({ policy: policyStatus({ downloadsAllowed: false, settingOn: true }) })
    render(<ModelsScreen />)
    const btn = await screen.findByRole('button', { name: 'Download' })
    expect(btn).toBeDisabled()
    expect(screen.getByText(/disabled by this drive’s policy/)).toBeInTheDocument()
    expect(screen.queryByText(/in Settings/)).not.toBeInTheDocument()
  })

  it('disables Download and points at the Settings toggle when allowNetwork is off', async () => {
    stub({ policy: policyStatus({ downloadsAllowed: true, settingOn: false }) })
    render(<ModelsScreen />)
    const btn = await screen.findByRole('button', { name: 'Download' })
    expect(btn).toBeDisabled()
    expect(
      screen.getByText(t('en', 'models.downloads.enableInSettings'))
    ).toBeInTheDocument()
    expect(screen.queryByText(/drive’s policy/)).not.toBeInTheDocument()
  })

  it('shows no Download affordance for an installed model', async () => {
    stub({ models: [model({ state: 'installed' })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument()
  })

  it('shows no Download affordance when the manifest has no download block', async () => {
    stub({ models: [model({ download: undefined })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument()
  })

  // Issue #196: unsloth deleted the Qwen3.8 files three manifests pin. A Download button there
  // could only end in an HTTP 404 that reads like a broken connection — so the card explains
  // instead, and says what still works.
  describe('a withdrawn upstream source (#196)', () => {
    const gone = (over: Partial<ModelInfo> = {}): ModelInfo =>
      model({
        download: {
          url: 'https://example.test/qwen3-4b.gguf',
          sizeBytes: 2_900_000_000,
          licenseUrl: 'https://example.test/license',
          licenseApproved: true,
          withdrawn: '2026-08-20: upstream deleted the file'
        },
        ...over
      })

    it('replaces the Download button with the reason, naming what still works', async () => {
      stub({ models: [gone()] })
      render(<ModelsScreen />)
      await screen.findByText('Qwen3 4B Instruct')
      expect(screen.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument()
      expect(screen.getByText(/No longer available for download/)).toBeInTheDocument()
      expect(screen.getByText(/2026-08-20: upstream deleted the file/)).toBeInTheDocument()
      expect(screen.getByText(/Copies already on a drive keep working/)).toBeInTheDocument()
    })

    it('does not raise the network-gate banner when the only "missing" model is unfetchable', async () => {
      // Downloads disabled by policy + nothing downloadable ⇒ the banner would blame the drive
      // policy for a model the policy has nothing to do with.
      stub({ models: [gone()], policy: policyStatus({ downloadsAllowed: false, settingOn: true }) })
      render(<ModelsScreen />)
      await screen.findByText('Qwen3 4B Instruct')
      expect(screen.queryByText(/disabled by this drive’s policy/)).not.toBeInTheDocument()
    })

    it('says nothing on a card whose weight is already installed', async () => {
      stub({ models: [gone({ state: 'installed' })] })
      render(<ModelsScreen />)
      await screen.findByText('Qwen3 4B Instruct')
      expect(screen.queryByText(/No longer available for download/)).not.toBeInTheDocument()
    })
  })

  // #933 review N4 (#932): a model with no checksum on record has no Download, so it must not raise the network-gate
  // banner either: the banner would blame the drive policy for a button that is not there.
  it('does not raise the network-gate banner for a model with no checksum on record (#932)', async () => {
    stub({
      models: [model({ state: 'checksum_failed', noChecksum: true })],
      policy: policyStatus({ downloadsAllowed: false, settingOn: true })
    })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.queryByText(/disabled by this drive’s policy/)).not.toBeInTheDocument()
  })
})

describe('ModelsScreen — "AI Model" reframe (Phase 26, guidelines §2)', () => {
  it('keeps checksums/paths/internals behind a closed-by-default "Technical details" disclosure', async () => {
    const user = userEvent.setup()
    stub({ models: [model({ state: 'installed' })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')

    // The plain-language hint is the everyday copy (2.7 GB → the "balanced" tier).
    expect(screen.getByText(/Balanced — works well on most laptops/)).toBeInTheDocument()

    // Closed by default: the technical content exists but is not shown.
    const details = document.querySelector('details.tech-details') as HTMLDetailsElement
    expect(details).not.toBeNull()
    expect(details.open).toBe(false)
    expect(screen.getByText('models/chat/qwen3-4b-instruct-q4.gguf')).not.toBeVisible()
    expect(screen.getByRole('button', { name: /verify checksum/i })).not.toBeVisible()

    // Opening the disclosure reveals path + checksum re-verify.
    await user.click(screen.getByText('Technical details'))
    expect(screen.getByText('models/chat/qwen3-4b-instruct-q4.gguf')).toBeVisible()
    expect(screen.getByRole('button', { name: /verify checksum/i })).toBeVisible()

    // M-U5: the manifest GB figures route through fmtGbNum (locale-aware). In EN the
    // value is byte-identical to the old raw render; the point is they go through the
    // formatter so a German UI gets "2,7 GB" / grouped numbers instead of raw output.
    const tech = within(details)
    expect(tech.getByText('2.7 GB')).toBeVisible() // size on disk
    expect(tech.getByText('8 GB')).toBeVisible() // minimum RAM
    expect(tech.getByText('16 GB')).toBeVisible() // recommended RAM
  })

  it('puts the active model first under "Your AI model"', async () => {
    stub({
      models: [
        model({ id: 'other-model', displayName: 'Other Model', state: 'installed' }),
        model({ id: 'active-model', displayName: 'Active Model', state: 'running' })
      ],
      activeModelId: 'active-model'
    })
    render(<ModelsScreen />)
    await screen.findByText('Active Model')

    expect(screen.getByText('Your AI model')).toBeInTheDocument()
    expect(screen.getByRole('region', { name: 'Model library' })).toBeInTheDocument()
    // DOM order: the active model's card precedes the picker.
    const titles = [...document.querySelectorAll('.model-title')].map((el) => el.textContent)
    expect(titles).toEqual(['Active Model', 'Other Model'])
  })
})

describe('ModelsScreen — automatic roles (Phase 36: reranker/transcriber)', () => {
  function transcriber(over: Partial<ModelInfo> = {}): ModelInfo {
    return model({
      id: 'whisper-small-multilingual',
      displayName: 'Whisper Small (multilingual transcriber)',
      family: 'whisper',
      role: 'transcriber',
      format: 'ggml',
      runtime: 'whisper_cpp',
      license: 'mit',
      sizeOnDiskGb: 0.49,
      localPath: 'models/transcriber/ggml-small.bin',
      ...over
    })
  }

  it('offers Download for a missing transcriber — never Select/Start', async () => {
    stub({ models: [transcriber({ state: 'missing' })] })
    render(<ModelsScreen />)
    await screen.findByText('Whisper Small (multilingual transcriber)')

    // The whole point of the support-matrix fix: the card is downloadable, not
    // "Unsupported", and explains it works automatically.
    expect(screen.getByText('Not downloaded')).toBeInTheDocument()
    expect(screen.queryByText('Unsupported')).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: /download/i })).toBeInTheDocument()
    expect(screen.getByText(/used automatically once installed/i)).toBeInTheDocument()
    // Selecting/starting a transcriber would claim the CHAT slot / feed GGML to
    // llama-server — those actions must not exist on automatic-role cards.
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start.*runtime/i })).not.toBeInTheDocument()
  })

  it('an installed transcriber says it is in use automatically (nothing to start)', async () => {
    stub({ models: [transcriber({ state: 'installed', download: undefined })] })
    render(<ModelsScreen />)
    await screen.findByText('Whisper Small (multilingual transcriber)')
    expect(screen.getByText('Installed')).toBeInTheDocument()
    expect(screen.getByText(/Installed — used automatically/i)).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.getByText(/Turns audio recordings into searchable text/)).toBeInTheDocument()
  })

  // #527: on Linux with the v1.8.6 pin (and on macOS) the voice engine has no build the app can
  // install. The card used to present the download as the way to dictation; it now says that the
  // model alone does not enable it here — and the download stays offered (a drive builder can
  // compile the engine, which then makes the model useful).
  it('#527 says the model does not enable dictation here when the voice engine has no build for this system', async () => {
    stub({
      models: [transcriber({ state: 'missing' })],
      appStatus: { transcriberMissing: 'engine-unsupported' }
    })
    render(<ModelsScreen />)
    expect(await screen.findByText(t('en', 'models.transcriber.engineUnsupported'))).toBeInTheDocument()
    expect(screen.getByRole('button', { name: /download/i })).toBeInTheDocument()
  })

  it('#527 shows no such note while the engine can be installed (or is installed)', async () => {
    for (const missing of ['model', 'engine', 'model-and-engine', null] as const) {
      stub({ models: [transcriber({ state: 'missing' })], appStatus: { transcriberMissing: missing } })
      const { unmount } = render(<ModelsScreen />)
      await screen.findByText('Whisper Small (multilingual transcriber)')
      expect(screen.queryByText(t('en', 'models.transcriber.engineUnsupported'))).not.toBeInTheDocument()
      unmount()
    }
  })

  it('#527 the note sits on the speech-model card only', async () => {
    stub({
      models: [model({ id: 'chat', displayName: 'Chat model' }), transcriber({ state: 'missing' })],
      appStatus: { transcriberMissing: 'engine-unsupported' }
    })
    render(<ModelsScreen />)
    const note = await screen.findByText(t('en', 'models.transcriber.engineUnsupported'))
    expect(note.closest('.model-card')).toHaveTextContent('Whisper Small (multilingual transcriber)')
    expect(screen.getAllByText(t('en', 'models.transcriber.engineUnsupported'))).toHaveLength(1)
  })

  it('offers Download for a missing vision model — never Select/Start', async () => {
    stub({
      models: [
        model({
          id: 'qwen2.5-vl-3b-instruct-q4',
          displayName: 'Qwen2.5-VL 3B Instruct Q4',
          role: 'vision',
          state: 'missing'
        })
      ]
    })
    render(<ModelsScreen onNavigate={vi.fn()} />)
    await screen.findByText('Qwen2.5-VL 3B Instruct Q4')
    // Downloadable in-app, and explained as an Images-screen capability — not the chat slot.
    expect(screen.getByRole('button', { name: /download/i })).toBeInTheDocument()
    expect(screen.getByText(/used automatically on the Images screen once installed/i)).toBeVisible()
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start.*runtime/i })).not.toBeInTheDocument()
    // #539: nothing to go to before the download.
    expect(screen.queryByRole('button', { name: 'Go to Images' })).not.toBeInTheDocument()
  })

  it('an installed vision model points to the Images screen — never Select/Start', async () => {
    stub({
      models: [
        model({
          id: 'qwen2.5-vl-3b-instruct-q4',
          displayName: 'Qwen2.5-VL 3B Instruct Q4',
          role: 'vision',
          state: 'installed',
          download: undefined
        })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('Qwen2.5-VL 3B Instruct Q4')
    expect(screen.getByText('Installed')).toBeInTheDocument()
    // #914: true whether this is the drive's only vision model or one of several (the Images screen runs one pick).
    expect(screen.getByText(/the Images screen picks its vision model automatically/i)).toBeVisible()
    // Selecting/starting a vision model would claim the CHAT runtime slot and throw
    // (registerModelIpc rejects a non-chat role) — those actions must not exist here.
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start.*runtime/i })).not.toBeInTheDocument()
  })

  it('offers Download for a missing translation model — never Select/Start (TG-1)', async () => {
    stub({
      models: [
        model({
          id: 'translategemma-12b-it-q4',
          displayName: 'TranslateGemma 12B (Q4_K_M)',
          role: 'translation',
          license: 'gemma',
          sizeOnDiskGb: 7.3,
          state: 'missing'
        })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('TranslateGemma 12B (Q4_K_M)')
    expect(screen.getByRole('button', { name: /download/i })).toBeInTheDocument()
    expect(screen.getByText(/used automatically for translation once installed/i)).toBeInTheDocument()
    // Availability-driven role (like reranker/vision): no chat-slot Select/Start.
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start.*runtime/i })).not.toBeInTheDocument()
  })

  it('an installed translation model says it is used automatically — never Select/Start (TG-1)', async () => {
    stub({
      models: [
        model({
          id: 'translategemma-12b-it-q4',
          displayName: 'TranslateGemma 12B (Q4_K_M)',
          role: 'translation',
          license: 'gemma',
          sizeOnDiskGb: 7.3,
          state: 'installed',
          download: undefined
        })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('TranslateGemma 12B (Q4_K_M)')
    expect(screen.getByText('Installed')).toBeInTheDocument()
    expect(screen.getByText(/used automatically for translation/i)).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start.*runtime/i })).not.toBeInTheDocument()
  })

  it('the reranker card gets the same automatic treatment', async () => {
    stub({
      models: [
        model({
          id: 'bge-reranker-v2-m3-f16',
          displayName: 'BGE Reranker v2 M3 (F16)',
          role: 'reranker',
          state: 'installed',
          download: undefined
        })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('BGE Reranker v2 M3 (F16)')
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start.*runtime/i })).not.toBeInTheDocument()
    expect(screen.getByText(/used automatically/i)).toBeInTheDocument()
  })
})

// #539: an automatic role has no action of its own, so its card says where it is used — visibly,
// not behind the closed Technical details (design-guidelines §15 amendment). The installed vision
// card also gets the one click there.
describe('ModelsScreen — where an automatic model is used (#539)', () => {
  const card = (name: string): HTMLElement => screen.getByText(name).closest('.model-card') as HTMLElement
  const vision = (over: Partial<ModelInfo> = {}): ModelInfo =>
    model({
      id: 'qwen2.5-vl-3b-instruct-q4',
      displayName: 'Qwen2.5-VL 3B Instruct Q4',
      role: 'vision',
      sizeOnDiskGb: 3.27,
      ...over
    })

  it.each([
    { role: 'embeddings', installed: 'models.automatic.installed', missing: 'models.automatic.notInstalled' },
    { role: 'reranker', installed: 'models.automatic.installed', missing: 'models.automatic.notInstalled' },
    { role: 'transcriber', installed: 'models.automatic.installed', missing: 'models.automatic.notInstalled' },
    { role: 'translation', installed: 'models.translation.installed', missing: 'models.translation.notInstalled' },
    { role: 'vision', installed: 'models.vision.installed', missing: 'models.vision.notInstalled' }
  ] as const)('the $role card shows its usage line once, without opening Technical details', async (row) => {
    for (const state of ['installed', 'missing'] as const) {
      stub({ models: [model({ id: `m-${row.role}`, displayName: `The ${row.role} model`, role: row.role, state })] })
      const { unmount } = render(<ModelsScreen />)
      await screen.findByText(`The ${row.role} model`)
      const lines = screen.getAllByText(t('en', state === 'installed' ? row.installed : row.missing))
      expect(lines).toHaveLength(1)
      expect(lines[0]).toBeVisible()
      expect(lines[0].closest('details')).toBeNull()
      unmount()
    }
  })

  it('a chat card carries no usage line', async () => {
    stub({ models: [model({ state: 'installed' })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.queryByText(/used automatically/i)).not.toBeInTheDocument()
  })

  it('the installed vision card offers Go to Images — its only button, no Download, no Use', async () => {
    const user = userEvent.setup()
    const onNavigate = vi.fn()
    stub({ models: [vision({ state: 'installed' })] })
    render(<ModelsScreen onNavigate={onNavigate} />)
    await screen.findByText('Qwen2.5-VL 3B Instruct Q4')
    const visionCard = within(card('Qwen2.5-VL 3B Instruct Q4'))
    await user.click(visionCard.getByRole('button', { name: 'Go to Images' }))
    expect(onNavigate).toHaveBeenCalledWith('images')
    expect(visionCard.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument()
    expect(visionCard.queryByRole('button', { name: 'Use this model' })).not.toBeInTheDocument()
  })

  it('no other automatic card gets the button, and without onNavigate the vision card has none', async () => {
    stub({
      models: [
        vision({ state: 'installed' }),
        model({ id: 'tg', displayName: 'Translation model', role: 'translation', state: 'installed' })
      ]
    })
    const { unmount } = render(<ModelsScreen onNavigate={vi.fn()} />)
    await screen.findByText('Translation model')
    expect(screen.getAllByRole('button', { name: /^go to/i })).toHaveLength(1)
    expect(within(card('Translation model')).queryByRole('button', { name: /^go to/i })).not.toBeInTheDocument()
    unmount()

    render(<ModelsScreen />)
    await screen.findByText('Qwen2.5-VL 3B Instruct Q4')
    expect(screen.queryByRole('button', { name: 'Go to Images' })).not.toBeInTheDocument()
  })

  it('the vision model’s plain hint says what it does, not the chat size tier', async () => {
    const user = userEvent.setup()
    stub({ models: [vision({ state: 'installed' })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen2.5-VL 3B Instruct Q4')
    await user.click(screen.getByText('Technical details'))
    expect(screen.getByText(t('en', 'models.hint.vision'))).toBeVisible()
    expect(screen.queryByText(t('en', 'models.hint.balanced'))).not.toBeInTheDocument()
  })
})

describe('ModelsScreen — de-jargoned + tidy per-card buttons (§3/§7)', () => {
  it('hides the disabled "Select" for a not-downloaded model — Download is the one clear action', async () => {
    stub({ models: [model({ state: 'missing' })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    // Before the weights exist, "Select" / "Start runtime" are noise — not rendered.
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start runtime/i })).not.toBeInTheDocument()
    // The single clear action remains.
    expect(screen.getByRole('button', { name: 'Download' })).toBeInTheDocument()
  })

  it('shows the merged "Use this model" action once the model is downloaded (installed)', async () => {
    // Beta #27 (D70): Select + Start runtime collapsed into ONE primary action.
    stub({ models: [model({ state: 'installed' })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.getByRole('button', { name: t('en', 'models.use') })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start runtime/i })).not.toBeInTheDocument()
  })

  it('labels the demo affordance "Try in demo mode" — no "mock runtime" jargon', async () => {
    // Developer-only, gated in MAIN via `startableAsMock`; when offered it reads as the
    // banner's "demo mode (visibly simulated answers)", not "Start mock runtime".
    stub({ models: [model({ state: 'missing', startableAsMock: true })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.getByRole('button', { name: 'Try in demo mode' })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /mock runtime/i })).not.toBeInTheDocument()
  })
})

// Beta #27 (D70): a first-time user faced a "Select" AND a "Start runtime" button per installed
// chat model and couldn't tell which led to chatting. They collapse into ONE primary "Use this
// model" action (select + start via the useModel IPC). Stop / Starting… / the demo card stay.
describe('ModelsScreen — one "Use this model" action (beta #27, D70 collapse)', () => {
  function startingStatus(modelId: string): RuntimeStatus {
    return { running: false, modelId: null, startingModelId: modelId, port: null, healthy: false, message: '' }
  }

  it('shows exactly ONE primary "Use this model" action per installed card — no Select / Start runtime', async () => {
    stub({ models: [model({ state: 'installed' })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.getByRole('button', { name: t('en', 'models.use') })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /^select$/i })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /start runtime/i })).not.toBeInTheDocument()
  })

  it('the action calls window.api.useModel (select + start in one) and is enabled for an installed model', async () => {
    const useModel = vi.fn(async () => ({ running: true }) as RuntimeStatus)
    stub({ models: [model({ state: 'installed' })] })
    ;(window.api as unknown as { useModel: typeof useModel }).useModel = useModel
    const user = userEvent.setup()
    render(<ModelsScreen />)
    const btn = await screen.findByRole('button', { name: t('en', 'models.use') })
    expect(btn).toBeEnabled()
    await user.click(btn)
    expect(useModel).toHaveBeenCalledWith('qwen3-4b-instruct-q4')
  })

  it('disables the action while this machine has too little RAM', async () => {
    stub({ models: [model({ state: 'installed', insufficientRam: true })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.getByRole('button', { name: t('en', 'models.use') })).toBeDisabled()
  })

  // #804: the RAM figures take the UI language's decimal separator (they were passed raw, so a 5.5 GB
  // minimum read "5.5" in every language, and so did the machine's RAM in the badge's hint), and the
  // card's code-built sizes put U+00A0 before "GB" (`fmtGbNum` and the manifest-size fallback of
  // `fmtGb`: the Ukrainian walk saw «23 GB» break there). Compared by code point: the default
  // normalizer folds U+00A0 into a plain space.
  it('in Ukrainian, fractional RAM figures read 5,5 and 3,5 in the badge and its hint, and the card’s sizes put U+00A0 before GB', async () => {
    const NBSP = String.fromCharCode(0xa0)
    try {
      stub({
        models: [model({ state: 'installed', insufficientRam: true, recommendedMinRamGb: 5.5 })],
        appStatus: { machineRamGb: 3.5 }
      })
      renderInLanguage(<ModelsScreen />, 'uk')
      await screen.findByText('Qwen3 4B Instruct')
      const badge = t('uk', 'models.badge.ramNeeded', { min: '5,5' })
      expect(badge).toContain(`5,5${NBSP}GB`) // the catalog's own U+00A0, so the row below compares it
      expect(screen.getByText(badge, { normalizer: getDefaultNormalizer({ collapseWhitespace: false }) })).toHaveAttribute(
        'title',
        t('uk', 'models.ram.needs', { min: '5,5' }) + t('uk', 'models.ram.machine', { ram: '3,5' }) + t('uk', 'models.ram.advice')
      )
      expect(document.querySelector('.model-sub')?.textContent).toContain(
        t('uk', 'models.library.memory', { size: `5,5${NBSP}GB` })
      )
      // The manifest's 2.7 GB (no byte size on this line), the fallback of `fmtGb`.
      expect(document.querySelector('.model-sub')?.textContent).toContain(t('uk', 'models.usesSpace', { size: `2,7${NBSP}GB` }))
    } finally {
      window.localStorage.removeItem(UI_LANGUAGE_STORAGE_KEY)
    }
  })

  it('shows the disabled Starting… spinner for the in-flight model instead of the action', async () => {
    stub({ models: [model({ state: 'installed' })] })
    ;(window.api as unknown as { getRuntimeStatus: () => Promise<RuntimeStatus> }).getRuntimeStatus =
      vi.fn(async () => startingStatus('qwen3-4b-instruct-q4'))
    render(<ModelsScreen />)
    expect(await screen.findByText(t('en', 'models.starting'))).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: t('en', 'models.use') })).not.toBeInTheDocument()
  })

  it('disables the action on OTHER cards while some model is starting (anyStarting)', async () => {
    stub({
      models: [
        model({ id: 'other-installed', displayName: 'Other Installed', state: 'installed' }),
        model({ id: 'loading', displayName: 'Loading Model', state: 'installed' })
      ]
    })
    ;(window.api as unknown as { getRuntimeStatus: () => Promise<RuntimeStatus> }).getRuntimeStatus =
      vi.fn(async () => startingStatus('loading'))
    render(<ModelsScreen />)
    await screen.findByText('Other Installed')
    // The one not starting still shows "Use this model", but it is disabled while another loads.
    expect(screen.getByRole('button', { name: t('en', 'models.use') })).toBeDisabled()
  })

  it('shows Stop (not the Use action) when the model is running', async () => {
    stub({ models: [model({ state: 'running' })], activeModelId: 'qwen3-4b-instruct-q4' })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.getByRole('button', { name: t('en', 'models.stopRuntime') })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: t('en', 'models.use') })).not.toBeInTheDocument()
  })

  it('says that stopping ends the answer being written — a calm note, no dialog (#600)', async () => {
    stub({ models: [model({ state: 'running' })], activeModelId: 'qwen3-4b-instruct-q4' })
    ;(window.api as unknown as { getRuntimeStatus: () => Promise<RuntimeStatus> }).getRuntimeStatus =
      vi.fn(async () => ({ running: true, modelId: 'qwen3-4b-instruct-q4', port: 1, healthy: true, message: '', answering: true }))
    render(<ModelsScreen />)
    expect(await screen.findByText(t('en', 'models.answeringNote'))).toBeInTheDocument()
    // The Stop action itself is unchanged: enabled, one click.
    expect(screen.getByRole('button', { name: t('en', 'models.stopRuntime') })).toBeEnabled()
  })

  it.each([
    ['a model that stopped answering: "Not responding" and a one-click Restart', true],
    ['a responding model: no badge and no Restart', false]
  ])('%s (#599)', async (_label, unresponsive) => {
    stub({ models: [model({ state: 'running' })], activeModelId: 'qwen3-4b-instruct-q4' })
    let restarting = false
    // The restart takes a while (a model load); the card must not keep saying "Not responding".
    const restartRuntime = vi.fn(() => {
      restarting = true
      return new Promise<null>(() => {})
    })
    Object.assign(window.api, {
      getRuntimeStatus: vi.fn(async () =>
        restarting
          ? { running: false, modelId: null, port: null, healthy: false, message: 'Starting', startingModelId: 'qwen3-4b-instruct-q4' }
          : {
              running: true,
              modelId: 'qwen3-4b-instruct-q4',
              port: 1,
              healthy: !unresponsive,
              message: '',
              ...(unresponsive ? { unresponsive: true } : {})
            }
      ),
      restartRuntime
    })
    render(<ModelsScreen />)
    await screen.findByRole('button', { name: t('en', 'models.stopRuntime') })
    const restart = screen.queryByRole('button', { name: t('en', 'models.restart') })
    if (!unresponsive) {
      expect(restart).not.toBeInTheDocument()
      expect(screen.queryByText(t('en', 'models.badge.notResponding'))).not.toBeInTheDocument()
      return
    }
    expect(screen.getByText(t('en', 'models.badge.notResponding'))).toBeInTheDocument()
    expect(screen.getByText(t('en', 'models.notRespondingHint'))).toBeInTheDocument()
    await userEvent.click(restart!)
    expect(restartRuntime).toHaveBeenCalledTimes(1)
    // The status read right after the request shows the restart under way.
    await waitFor(() => expect(screen.queryByText(t('en', 'models.badge.notResponding'))).not.toBeInTheDocument())
  })

  it('still offers the demo-mode button on the zero-weights developer card (no Use action)', async () => {
    stub({ models: [model({ state: 'missing', startableAsMock: true })] })
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(screen.getByRole('button', { name: t('en', 'models.startMock') })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: t('en', 'models.use') })).not.toBeInTheDocument()
  })

  it('renders the German label for the collapsed action (D-L8: asserted from the catalog)', async () => {
    stub({ models: [model({ state: 'installed' })] })
    window.localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, 'de')
    try {
      render(
        <I18nProvider>
          <ModelsScreen />
        </I18nProvider>
      )
      expect(await screen.findByRole('button', { name: t('de', 'models.use') })).toBeInTheDocument()
    } finally {
      window.localStorage.removeItem(UI_LANGUAGE_STORAGE_KEY)
    }
  })
})

describe('ModelsScreen — installed and catalog library views', () => {
  it('defaults to on-drive models; Browse includes downloads with installed models first', async () => {
    stub({
      models: [
        model({ id: 'a-installed', displayName: 'A Installed', state: 'installed' }),
        model({ id: 'b-missing', displayName: 'B Missing', state: 'missing' }),
        model({ id: 'c-installed', displayName: 'C Installed', state: 'installed' })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('A Installed')

    expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute('aria-checked', 'true')
    expect(screen.queryByText('B Missing')).not.toBeInTheDocument()
    await userEvent.setup().click(screen.getByRole('radio', { name: 'Browse models' }))
    const flow = [...document.querySelectorAll('.model-title')].map(
      (el) => el.textContent
    )
    expect(flow).toEqual([
      'A Installed',
      'C Installed',
      'B Missing'
    ])
  })

  it('renders flat — no group labels — when the section is homogeneous', async () => {
    stub({
      models: [
        model({ id: 'a-installed', displayName: 'A Installed', state: 'installed' }),
        model({ id: 'c-installed', displayName: 'C Installed', state: 'installed' })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('A Installed')
    // The old full-card picker's installed/needs-download subheading (#35) was removed with it
    // (PR #302 F7) — confirm neither its retired literal copy nor its CSS hook still renders.
    expect(screen.queryByText('On this drive — ready to use')).not.toBeInTheDocument()
    expect(screen.queryByText('Available to download')).not.toBeInTheDocument()
    expect(document.querySelector('.model-group-title')).not.toBeInTheDocument()
  })

  it('mutes not-yet-downloaded cards (.model-card-missing) so installed ones stand out', async () => {
    stub({
      models: [
        model({ id: 'a-installed', displayName: 'A Installed', state: 'installed' }),
        model({ id: 'b-missing', displayName: 'B Missing', state: 'missing' })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('A Installed')
    await userEvent.setup().click(screen.getByRole('radio', { name: 'Browse models' }))
    const cards = [...document.querySelectorAll('.model-card')]
    const missingCard = cards.find((c) => c.textContent?.includes('B Missing'))
    const installedCard = cards.find((c) => c.textContent?.includes('A Installed'))
    expect(missingCard?.classList.contains('model-card-missing')).toBe(true)
    expect(installedCard?.classList.contains('model-card-missing')).toBe(false)
  })

  it('groups the Document search (embeddings) section the same way', async () => {
    stub({
      models: [
        model({
          id: 'emb-installed',
          displayName: 'Embedder Installed',
          role: 'embeddings',
          state: 'installed',
          download: undefined
        }),
        model({
          id: 'emb-missing',
          displayName: 'Embedder Missing',
          role: 'embeddings',
          state: 'missing'
        })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('Embedder Installed')
    expect(screen.getByRole('heading', { name: t('en', 'models.section.docSearch') })).toBeInTheDocument()
    expect(screen.queryByText('Embedder Missing')).not.toBeInTheDocument()
    await userEvent.setup().click(screen.getByRole('radio', { name: 'Browse models' }))
    expect(screen.getByText('Embedder Missing')).toBeInTheDocument()
  })
})

// #847: a model for a newer HilbertRaum (a role this build does not know, or a `min_app_version` above this app) is
// listed in its own trailing section, with nothing to act on, instead of vanishing. Frozen old-reader contract: the
// app-update plan's Appendix B.
describe('ModelsScreen — a model for a newer HilbertRaum (#847)', () => {
  const newer = (over: Partial<ModelInfo>): ModelInfo =>
    model({
      role: 'unknown',
      declaredRole: 'hologram',
      needsNewerApp: true,
      state: 'unsupported',
      family: 'holo',
      download: undefined,
      ...over
    })
  const heading = (): string => t('en', 'models.newerApp.heading')

  it('lists it last under its own heading, with the hint and nothing to download, use or verify', async () => {
    const user = userEvent.setup()
    stub({
      models: [
        model({ id: 'chat-ok', displayName: 'Chat OK', state: 'installed' }),
        newer({ id: 'holo-here', displayName: 'Holo Here', filesPresent: true }),
        newer({ id: 'holo-elsewhere', displayName: 'Holo Elsewhere', filesPresent: false })
      ]
    })
    render(<ModelsScreen />)
    await screen.findByText('Chat OK')

    // On this drive: only the one whose files are here.
    expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute('aria-checked', 'true')
    const onDrive = within(screen.getByRole('region', { name: heading() }))
    expect(onDrive.getByText('Holo Here')).toBeVisible()
    expect(onDrive.queryByText('Holo Elsewhere')).not.toBeInTheDocument()
    expect(onDrive.getByText(t('en', 'models.newerApp.badge'))).toBeVisible()
    expect(onDrive.getByText(t('en', 'models.newerApp.hint'))).toBeVisible()
    expect(onDrive.queryAllByRole('button')).toEqual([])
    expect(onDrive.queryByText(t('en', 'models.tech.summary'))).not.toBeInTheDocument()
    expect(screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent).at(-1)).toBe(heading())
    expect(screen.getByText(tCount('en', 'models.library.results', 2))).toBeInTheDocument() // counted with the rows

    // Browse lists both; the family options never offer its family.
    await user.click(screen.getByRole('radio', { name: 'Browse models' }))
    expect(within(screen.getByRole('region', { name: heading() })).getByText('Holo Elsewhere')).toBeVisible()
    const families = within(screen.getByRole('combobox', { name: 'Family' }))
      .getAllByRole('option')
      .map((o) => o.textContent)
    expect(families).not.toContain('holo')

    // It is no task's model: a task filter hides the section.
    await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'chat')
    expect(screen.queryByRole('region', { name: heading() })).not.toBeInTheDocument()
  })

  it('is listed even when nothing else matches: no "no models" message hides it', async () => {
    stub({ models: [newer({ id: 'holo-only', displayName: 'Holo Only', filesPresent: false })] })
    render(<ModelsScreen />)
    expect(await screen.findByText('Holo Only')).toBeVisible()
    expect(screen.queryByText(t('en', 'models.library.noAlternatives'))).not.toBeInTheDocument()
  })
})

// #527: the composer's dictation hint ("Get the speech model") opens this screen through the
// 'models:voice' deep link. It used to land on "On this drive" — where a missing speech model, by
// definition, is not listed — so the user had to find Browse and the Voice task themselves.
describe('ModelsScreen — the speech-model deep link (#527)', () => {
  const library = (): ModelInfo[] => [
    model({ id: 'chat-installed', displayName: 'Installed chat model', state: 'installed' }),
    model({ id: 'chat-missing', displayName: 'Another chat model', state: 'missing' }),
    model({
      id: 'whisper-small-multilingual',
      displayName: 'Whisper Small (multilingual transcriber)',
      family: 'whisper',
      role: 'transcriber',
      format: 'ggml',
      runtime: 'whisper_cpp',
      state: 'missing'
    })
  ]

  it('focus "voice" opens Browse filtered to the Voice task, even on a drive with installed models', async () => {
    stub({ models: library() })
    render(<ModelsScreen focus="voice" />)
    expect(await screen.findByText('Whisper Small (multilingual transcriber)')).toBeVisible()
    expect(screen.getByRole('radio', { name: 'Browse models' })).toHaveAttribute('aria-checked', 'true')
    expect(screen.getByRole('combobox', { name: 'Task' })).toHaveValue('transcriber')
    expect(screen.queryByText('Another chat model')).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Download' })).toBeInTheDocument()
  })

  it('without a focus the screen keeps its own default (On this drive, all tasks)', async () => {
    stub({ models: library() })
    render(<ModelsScreen />)
    expect(await screen.findByText('Installed chat model')).toBeVisible()
    expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute('aria-checked', 'true')
    expect(screen.getByRole('combobox', { name: 'Task' })).toHaveValue('all')
    expect(screen.queryByText('Whisper Small (multilingual transcriber)')).not.toBeInTheDocument()
  })

  describe('scrolls the library into view — unless an engine banner is the first thing to act on', () => {
    let scrolled: Element[]
    beforeEach(() => {
      scrolled = []
      // jsdom has no layout, so scrollIntoView does not exist there: record the calls instead.
      Element.prototype.scrollIntoView = vi.fn(function (this: Element) {
        scrolled.push(this)
      })
    })
    afterEach(() => {
      delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView
    })
    const engine = (missing: string[]): EngineStatus => ({
      installed: missing.length === 0,
      available: true,
      version: 'btest',
      backend: 'vulkan',
      missingFamilies: missing
    })

    it('only the model missing: the library (with the speech model) is scrolled to, once', async () => {
      stub({ models: library(), engine: engine([]) })
      render(<ModelsScreen focus="voice" />)
      await screen.findByText('Whisper Small (multilingual transcriber)')
      await waitFor(() => expect(scrolled).toHaveLength(1))
      expect(scrolled[0]).toBe(screen.getByRole('region', { name: t('en', 'models.library.title') }))
    })

    it('the voice engine missing: stays at the top, where its banner is', async () => {
      stub({ models: library(), engine: engine(['whisper_cpp']) })
      render(<ModelsScreen focus="voice" />)
      expect(await screen.findByText(t('en', 'models.voiceEngine.title'))).toBeInTheDocument()
      expect(screen.getByText('Whisper Small (multilingual transcriber)')).toBeInTheDocument()
      expect(scrolled).toHaveLength(0)
    })

    // #532 (the #539 note on it): the AI engine's "can't run" banner — with its reinstall — sits at
    // the top too. The voice engine's notice is a hint ON the speech-model card, so it does not.
    it('the AI engine can\'t run: stays at the top, where its banner is', async () => {
      stub({ models: library(), engine: engine([]), appStatus: { engineProblems: [DAMAGED_ENGINE] } })
      render(<ModelsScreen focus="voice" />)
      expect(await screen.findByText(t('en', 'models.engineProblem.title'))).toBeInTheDocument()
      expect(screen.getByText('Whisper Small (multilingual transcriber)')).toBeInTheDocument()
      expect(scrolled).toHaveLength(0)
    })

    it('only the voice engine can\'t run: its hint is on the speech-model card, so the library is scrolled to', async () => {
      stub({ models: library(), engine: engine([]), appStatus: { engineProblems: [{ ...DAMAGED_ENGINE, family: 'whisper_cpp' }] } })
      render(<ModelsScreen focus="voice" />)
      await screen.findByText('Whisper Small (multilingual transcriber)')
      await waitFor(() => expect(scrolled).toHaveLength(1))
    })

    it('no focus: never scrolls', async () => {
      stub({ models: library(), engine: engine([]) })
      render(<ModelsScreen />)
      await screen.findByText('Installed chat model')
      expect(scrolled).toHaveLength(0)
    })
  })

  it('the screen’s own controls take over after the deep link', async () => {
    const user = userEvent.setup()
    stub({ models: library() })
    render(<ModelsScreen focus="voice" />)
    await screen.findByText('Whisper Small (multilingual transcriber)')
    await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'all')
    expect(screen.getByText('Another chat model')).toBeVisible()
  })
})

// #539: the #527 landing, generalised — the Images and Translate availability cards and the
// Documents row's "Get the translation model…" open the screen on that model, not on "On this
// drive". Both models run on the AI engine, so only its banner keeps the screen at the top.
describe.each([
  { focus: 'images', task: 'vision', role: 'vision', name: 'Qwen2.5-VL 3B Instruct Q4' },
  { focus: 'translation', task: 'translation', role: 'translation', name: 'TranslateGemma 12B (Q4_K_M)' }
] as const)('ModelsScreen — the $focus deep link (#539)', ({ focus, task, role, name }) => {
  const library = (): ModelInfo[] => [
    model({ id: 'chat-installed', displayName: 'Installed chat model', state: 'installed' }),
    model({ id: 'chat-missing', displayName: 'Another chat model', state: 'missing' }),
    model({ id: `${role}-model`, displayName: name, role, state: 'missing' })
  ]

  it(`opens Browse filtered to the ${task} task, even on a drive with installed models`, async () => {
    stub({ models: library() })
    render(<ModelsScreen focus={focus} />)
    expect(await screen.findByText(name)).toBeVisible()
    expect(screen.getByRole('radio', { name: 'Browse models' })).toHaveAttribute('aria-checked', 'true')
    expect(screen.getByRole('combobox', { name: 'Task' })).toHaveValue(task)
    expect(screen.queryByText('Another chat model')).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Download' })).toBeInTheDocument()
  })

  describe('scrolls the library into view — unless the AI engine banner is the first thing to act on', () => {
    let scrolled: Element[]
    beforeEach(() => {
      scrolled = []
      Element.prototype.scrollIntoView = vi.fn(function (this: Element) {
        scrolled.push(this)
      })
    })
    afterEach(() => {
      delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView
    })
    const engine = (missing: string[]): EngineStatus => ({
      installed: missing.length === 0,
      available: true,
      version: 'btest',
      backend: 'vulkan',
      missingFamilies: missing
    })

    it('only the model missing: the library is scrolled to, once', async () => {
      stub({ models: library(), engine: engine([]) })
      render(<ModelsScreen focus={focus} />)
      await screen.findByText(name)
      await waitFor(() => expect(scrolled).toHaveLength(1))
      expect(scrolled[0]).toBe(screen.getByRole('region', { name: t('en', 'models.library.title') }))
    })

    it('the AI engine missing: stays at the top, where its banner is', async () => {
      stub({ models: library(), engine: engine(['llama_cpp']) })
      render(<ModelsScreen focus={focus} />)
      expect(await screen.findByText(t('en', 'models.engine.title'))).toBeInTheDocument()
      expect(screen.getByText(name)).toBeInTheDocument()
      expect(scrolled).toHaveLength(0)
    })

    it('only the voice engine missing: its banner is not about this model, so the library is scrolled to', async () => {
      stub({ models: library(), engine: engine(['whisper_cpp']) })
      render(<ModelsScreen focus={focus} />)
      expect(await screen.findByText(t('en', 'models.voiceEngine.title'))).toBeInTheDocument()
      await waitFor(() => expect(scrolled).toHaveLength(1))
    })

    it('the AI engine can\'t run (#532): stays at the top, where its banner is', async () => {
      stub({ models: library(), engine: engine([]), appStatus: { engineProblems: [DAMAGED_ENGINE] } })
      render(<ModelsScreen focus={focus} />)
      expect(await screen.findByText(t('en', 'models.engineProblem.title'))).toBeInTheDocument()
      expect(screen.getByText(name)).toBeInTheDocument()
      expect(scrolled).toHaveLength(0)
    })

    it('an AI engine update is available (#516): stays at the top, where its notice is', async () => {
      const older: EngineVersionInfo = {
        family: 'llama_cpp',
        optional: false,
        installed: 'b9849',
        installedBackend: 'vulkan',
        pinned: 'b11146',
        pinnedBackend: 'vulkan',
        relation: 'older'
      }
      stub({ models: library(), engine: { ...engine([]), engineVersions: [older] } })
      render(<ModelsScreen focus={focus} />)
      expect(await screen.findByText(t('en', 'models.engineUpdate.title'))).toBeInTheDocument()
      expect(screen.getByText(name)).toBeInTheDocument()
      expect(scrolled).toHaveLength(0)
    })
  })

  it('the screen’s own controls take over after the deep link', async () => {
    const user = userEvent.setup()
    stub({ models: library() })
    render(<ModelsScreen focus={focus} />)
    await screen.findByText(name)
    await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'all')
    expect(screen.getByText('Another chat model')).toBeVisible()
  })
})

describe('ModelsScreen — search, tasks and model variants', () => {
  it('starts in Browse on a fresh drive and expands exact variants with the recommended one first', async () => {
    const user = userEvent.setup()
    stub({ models: [
      model({ id: 'qwen-q4', displayName: 'Qwen3.8 27B Q4_K_M' }),
      model({ id: 'qwen-ud', displayName: 'Qwen3.8 27B UD-Q4_K_M', recommended: true }),
      model({ id: 'qwen-q6', displayName: 'Qwen3.8 27B Q6_K' })
    ] })
    render(<ModelsScreen />)
    expect(await screen.findByRole('radio', { name: 'Browse models' })).toHaveAttribute('aria-checked', 'true')
    const group = within(screen.getByRole('region', { name: 'Qwen3.8 27B' }))
    expect(group.getByText('Qwen3.8 27B UD-Q4_K_M')).toBeVisible()
    expect(group.queryByText('Qwen3.8 27B Q4_K_M')).not.toBeInTheDocument()
    const expand = group.getByRole('button', { name: 'Show all variants (3)' })
    expand.focus()
    await user.keyboard('{Enter}')
    expect(expand).toHaveAttribute('aria-expanded', 'true')
    expect(group.getByText('Qwen3.8 27B Q4_K_M')).toBeVisible()
    // Each variant's action still targets its exact catalog id.
    await user.click(within(group.getByText('Qwen3.8 27B Q6_K').closest('.model-card') as HTMLElement)
      .getByRole('button', { name: 'Download' }))
    expect(screen.getByRole('dialog')).toHaveTextContent('Qwen3.8 27B Q6_K')
    await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Cancel' }))
    await user.click(expand)
    expect(group.queryByText('Qwen3.8 27B Q6_K')).not.toBeInTheDocument()
    // A search finds a collapsed variant directly, without first expanding its group.
    await user.type(screen.getByRole('searchbox', { name: 'Search models' }), 'qwen Q6')
    expect(screen.getByText('Qwen3.8 27B Q6_K')).toBeVisible()
    expect(screen.queryByText('Qwen3.8 27B UD-Q4_K_M')).not.toBeInTheDocument()
  })

  it('combines task, family and case-insensitive search; reset restores results and keeps the active model pinned', async () => {
    const user = userEvent.setup()
    stub({ activeModelId: 'active', models: [
      model({ id: 'active', displayName: 'Active model', state: 'running' }),
      model({ id: 'embed', displayName: 'Document embedder', family: 'e5', role: 'embeddings', state: 'installed' }),
      model({ id: 'rerank', displayName: 'Document reranker', family: 'bge', role: 'reranker', state: 'installed' }),
      model({ id: 'voice', displayName: 'Voice model', family: 'whisper', role: 'transcriber', state: 'installed' })
    ] })
    render(<ModelsScreen />)
    await screen.findByText('Active model')
    await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'documents')
    expect(screen.getByText('Document embedder')).toBeVisible()
    expect(screen.getByText('Document reranker')).toBeVisible()
    expect(screen.queryByText('Voice model')).not.toBeInTheDocument()
    await user.selectOptions(screen.getByRole('combobox', { name: 'Family' }), 'bge')
    await user.type(screen.getByRole('searchbox'), 'RERANK')
    expect(screen.getByText('Document reranker')).toBeVisible()
    expect(screen.queryByText('Document embedder')).not.toBeInTheDocument()
    await user.type(screen.getByRole('searchbox'), ' xyz')
    expect(screen.getByText(/No models match/)).toBeVisible()
    expect(screen.getByText('Active model')).toBeVisible()
    await user.click(screen.getByRole('button', { name: 'Clear filters' }))
    expect(screen.getByText('Voice model')).toBeVisible()
    expect(screen.getByText('Document embedder')).toBeVisible()
  })

  describe('#313 family options follow the view and task', () => {
    // active/newchat are chat; embed/rerank are the "documents" task (embeddings + reranker);
    // voice is transcriber. bge/e5/whisper are installed (on this drive); colbert/phi are
    // download-only, so they only ever appear in Browse.
    function fixture(): ModelInfo[] {
      return [
        model({ id: 'active', displayName: 'Active model', family: 'llama', state: 'running' }),
        model({ id: 'embed', displayName: 'Document embedder', family: 'e5', role: 'embeddings', state: 'installed' }),
        model({ id: 'rerank', displayName: 'Document reranker', family: 'bge', role: 'reranker', state: 'installed' }),
        model({ id: 'rerank-big', displayName: 'Big reranker', family: 'colbert', role: 'reranker', state: 'missing' }),
        model({ id: 'voice', displayName: 'Voice model', family: 'whisper', role: 'transcriber', state: 'installed' }),
        model({ id: 'newchat', displayName: 'New chat model', family: 'phi', role: 'chat', state: 'missing' })
      ]
    }

    function familySelect(): HTMLElement {
      return screen.getByRole('combobox', { name: 'Family' })
    }

    function familyOptionNames(): string[] {
      return within(familySelect())
        .getAllByRole('option')
        .map((o) => o.textContent ?? '')
    }

    // The rule itself is `availableFamilies`' (unit/model-library): this row proves the <select> reads the current view and task.
    it('the family options follow the view and the task', async () => {
      const user = userEvent.setup()
      stub({ activeModelId: 'active', models: fixture() })
      render(<ModelsScreen />)
      await screen.findByText('Active model')
      // Something is installed here, so the screen opens on "On this drive" (design-guidelines §15).
      expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute('aria-checked', 'true')
      expect(familyOptionNames()).toEqual(['All families', 'bge', 'e5', 'whisper'])
      await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'documents')
      expect(familyOptionNames()).toEqual(['All families', 'bge', 'e5'])
      await user.click(screen.getByRole('radio', { name: 'Browse models' }))
      expect(familyOptionNames()).toEqual(['All families', 'bge', 'colbert', 'e5'])
      await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'all')
      expect(familyOptionNames()).toEqual(['All families', 'bge', 'colbert', 'e5', 'phi', 'whisper'])
    })

    it('keeps a family selected in Browse, marked and explained, after switching to On this drive', async () => {
      const user = userEvent.setup()
      stub({ activeModelId: 'active', models: fixture() })
      render(<ModelsScreen />)
      await screen.findByText('Active model')
      await user.click(screen.getByRole('radio', { name: 'Browse models' }))
      await user.selectOptions(familySelect(), 'phi')
      expect(await screen.findByText('New chat model')).toBeVisible()
      await user.click(screen.getByRole('radio', { name: 'On this drive' }))
      // The selection survives the view change — never silently dropped or swapped to another family.
      expect(familySelect()).toHaveValue('phi')
      expect(
        within(familySelect()).getByRole('option', { name: 'phi (none in this view)' })
      ).toBeInTheDocument()
      expect(
        await screen.findByText('No phi models are on this drive. Browse models shows 1 model.')
      ).toBeVisible()
      await user.click(screen.getByRole('button', { name: 'Browse models' }))
      // The advertised count matches exactly what Browse then lists.
      expect(await screen.findByText('New chat model')).toBeVisible()
      expect(screen.getByText('1 matching variant')).toBeVisible()
    })

    it('resets only the family, keeping the search text and task intact', async () => {
      const user = userEvent.setup()
      stub({ activeModelId: 'active', models: fixture() })
      render(<ModelsScreen />)
      await screen.findByText('Active model')
      await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'documents')
      await user.type(screen.getByRole('searchbox'), 'reranker')
      expect(screen.getByText('Document reranker')).toBeVisible()
      await user.selectOptions(familySelect(), 'e5')
      expect(await screen.findByText(/No models match/)).toBeVisible()
      await user.click(screen.getByRole('button', { name: 'All families' }))
      expect(familySelect()).toHaveValue('all')
      expect(screen.getByRole('combobox', { name: 'Task' })).toHaveValue('documents')
      expect(screen.getByRole('searchbox')).toHaveValue('reranker')
      expect(await screen.findByText('Document reranker')).toBeVisible()
    })

    it('never changes the selected family when Task changes underneath it', async () => {
      const user = userEvent.setup()
      stub({ activeModelId: 'active', models: fixture() })
      render(<ModelsScreen />)
      await screen.findByText('Active model')
      await user.selectOptions(familySelect(), 'bge')
      expect(screen.getByText('Document reranker')).toBeVisible()
      await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'chat')
      expect(familySelect()).toHaveValue('bge')
    })
  })

  it('does not hide an installed variant when this computer has too little memory', async () => {
    stub({ models: [model({ state: 'installed', insufficientRam: true })] })
    render(<ModelsScreen />)
    expect(await screen.findByRole('button', { name: 'Use this model' })).toBeDisabled()
    expect(screen.getByText('Qwen3 4B Instruct')).toBeVisible()
  })

  it('keeps a filtered-out download cancellable and preserves the chosen view', async () => {
    const user = userEvent.setup()
    const downloading = model({ id: 'filtered-download', displayName: 'Filtered download Q4' })
    let currentJob: DownloadJob = {
      jobId: 'filtered-job', modelId: downloading.id, status: 'downloading',
      receivedBytes: 10, totalBytes: 1000, unverified: false, error: null
    }
    stub({ models: [downloading], downloadModel: vi.fn(async () => currentJob),
      getDownloadJob: vi.fn(async () => currentJob) })
    const cancel = vi.fn(async () => {
      currentJob = { ...currentJob, status: 'cancelled' }
      return currentJob
    })
    window.api.cancelDownload = cancel
    render(<ModelsScreen />)
    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    await user.click(screen.getByRole('radio', { name: 'On this drive' }))
    await user.type(screen.getByRole('searchbox'), 'no match')
    const progress = within(screen.getByRole('region', { name: 'Current model download' }))
    expect(progress.getByText(downloading.displayName)).toBeVisible()
    await user.click(progress.getByRole('button', { name: 'Cancel download' }))
    expect(cancel).toHaveBeenCalledWith('filtered-job')
    expect(screen.queryByRole('region', { name: 'Current model download' })).not.toBeInTheDocument()
    expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute('aria-checked', 'true')
  })

  // The check takes minutes on a USB stick. Main has honoured a cancel there since BE-4, but this
  // button stayed disabled, so nobody could ask (#752).
  it('a download can be cancelled during its final check', async () => {
    const user = userEvent.setup()
    const verifying = model({ id: 'verifying-download', displayName: 'Verifying Q4' })
    let currentJob: DownloadJob = {
      jobId: 'verifying-job', modelId: verifying.id, status: 'verifying',
      receivedBytes: 1000, totalBytes: 1000, unverified: false, error: null
    }
    stub({ models: [verifying], downloadModel: vi.fn(async () => currentJob),
      getDownloadJob: vi.fn(async () => currentJob) })
    const cancel = vi.fn(async () => {
      currentJob = { ...currentJob, status: 'cancelled' }
      return currentJob
    })
    window.api.cancelDownload = cancel
    render(<ModelsScreen />)
    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    const progress = within(screen.getByRole('region', { name: 'Current model download' }))
    await user.click(progress.getByRole('button', { name: 'Cancel download' }))
    expect(cancel).toHaveBeenCalledWith('verifying-job')
  })

  // #782: when switching internet access off stopped the download, nobody pressed Cancel, and the card says why.
  it.each([
    ['a cancel the user asked for', undefined, 'models.download.cancelled', 'models.download.stoppedNetworkOff'],
    ['internet access switched off', 'networkOff' as const, 'models.download.stoppedNetworkOff', 'models.download.cancelled']
  ] as const)('a download stopped by %s says so on its card', async (_title, stoppedBy, shown, notShown) => {
    const user = userEvent.setup()
    const m = model({ id: 'stopped-download', displayName: 'Stopped Q4' })
    const running: DownloadJob = {
      jobId: 'stopped-job', modelId: m.id, status: 'downloading',
      receivedBytes: 10, totalBytes: 1000, unverified: false, error: null
    }
    const stopped: DownloadJob = { ...running, status: 'cancelled', ...(stoppedBy ? { stoppedBy } : {}) }
    stub({ models: [m], downloadModel: vi.fn(async () => running), getDownloadJob: vi.fn(async () => stopped) })
    render(<ModelsScreen />)
    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    expect(await screen.findByText(t('en', shown))).toBeVisible()
    expect(screen.queryByText(t('en', notShown))).not.toBeInTheDocument()
  })

  // The screen polls once a second, so the check can finish behind a Cancel the user can still
  // click. The `done` that comes back stops the poll, and only the poll refreshed the cards.
  it('a Cancel that arrives after the check finished still shows the model as installed (#752)', async () => {
    const user = userEvent.setup()
    const verifying = model({ id: 'late-cancel', displayName: 'Late cancel Q4' })
    const job: DownloadJob = {
      jobId: 'late-job', modelId: verifying.id, status: 'verifying',
      receivedBytes: 1000, totalBytes: 1000, unverified: false, error: null
    }
    stub({ models: [verifying], downloadModel: vi.fn(async () => job), getDownloadJob: vi.fn(async () => job) })
    window.api.cancelDownload = vi.fn(async () => {
      window.api.listModels = vi.fn(async () => [{ ...verifying, state: 'installed' as const }])
      return { ...job, status: 'done' as const }
    })
    render(<ModelsScreen />)
    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    const progress = within(screen.getByRole('region', { name: 'Current model download' }))
    await user.click(progress.getByRole('button', { name: 'Cancel download' }))
    expect(await screen.findByRole('button', { name: 'Use this model' })).toBeVisible()
    expect(screen.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument()
  })
})

describe('ModelsScreen — context-size picker beyond 32k (issue #43)', () => {
  function stubWithSettings(
    settingsOver: Record<string, unknown>,
    models: ModelInfo[] = [model({ state: 'installed' })]
  ): void {
    stubModelsApi({
      listModels: vi.fn(async () => models),
      getSettings: vi.fn(async () => ({ ...DEFAULT_SETTINGS, ...settingsOver })),
    })
  }

  it('offers the 65,536 and 131,072 rungs — the old 32k ceiling dead-ended long-document workflows', async () => {
    stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4' })
    render(<ModelsScreen />)
    const select = await screen.findByRole('combobox', { name: /Context window for answers/ })
    expect(within(select).getByRole('option', { name: '65,536 tokens' })).toBeInTheDocument()
    expect(within(select).getByRole('option', { name: '131,072 tokens' })).toBeInTheDocument()
  })

  it('labels Automatic with the number it resolves to for the active model', async () => {
    stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4' }, [
      model({ state: 'installed', recommendedContextTokens: 98_304 })
    ])
    render(<ModelsScreen />)
    const select = await screen.findByRole('combobox', { name: /Context window for answers/ })
    // "Auto" is often the LARGEST choice in the list; naming its resolved size stops it
    // reading as a small default (issue #43).
    expect(within(select).getByRole('option', { name: /Automatic.*98,304/ })).toBeInTheDocument()
  })

  it('locale-formats the tech-details context row via the catalog — DE gets grouping + the "Token" plural (RD-3)', async () => {
    // RD-3 (full-audit 2026-07-10): the tech-details row used to interpolate the RAW number
    // (98304) while its sibling call sites already went through toLocaleString(lang); de.ts also
    // said "Tokens" where the neighboring autoResolved key correctly uses the German plural
    // "Token". Both asserted from the catalog (D-L8) — never re-typed literals.
    stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4' }, [
      model({ state: 'installed', recommendedContextTokens: 98_304 })
    ])
    render(<ModelsScreen />)
    await screen.findByText('Qwen3 4B Instruct')
    expect(
      screen.getByText(tCount('en', 'models.tech.contextValue', 98_304, { count: (98_304).toLocaleString('en') }))
    ).toBeInTheDocument()
    cleanup()

    window.localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, 'de')
    try {
      stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4' }, [
        model({ state: 'installed', recommendedContextTokens: 98_304 })
      ])
      render(
        <I18nProvider>
          <ModelsScreen />
        </I18nProvider>
      )
      await screen.findByText('Qwen3 4B Instruct')
      expect(
        screen.getByText(tCount('de', 'models.tech.contextValue', 98_304, { count: (98_304).toLocaleString('de') }))
      ).toBeInTheDocument()
    } finally {
      window.localStorage.removeItem(UI_LANGUAGE_STORAGE_KEY)
    }
  })

  // English and German say "tokens"/"Token" in both forms, so only a language with more forms shows
  // whether the count is the figure the row shows (i18n record §5: raw count, grouped param).
  // Two figures no picker option shows, in two Russian forms: 40,960 is `many` («токенов») and
  // 98,304 is `few` («токена»), so no single constant selector passes both. The figure is compared
  // with `Intl` output, never a typed literal: Russian groups with a no-break space.
  it.each([
    { tokens: 40_960, form: 'many' },
    { tokens: 98_304, form: 'few' }
  ] as const)('in Russian, the tech-details context row picks its form by the figure it shows: $tokens ($form)', async ({ tokens, form }) => {
    const shown = catalogOf('ru')[`models.tech.contextValue.${form}`].split('{count}').join(new Intl.NumberFormat('ru').format(tokens))
    try {
      stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4' }, [
        model({ state: 'installed', recommendedContextTokens: tokens })
      ])
      renderInLanguage(<ModelsScreen />, 'ru')
      await screen.findByText('Qwen3 4B Instruct')
      // The default normalizer would turn the no-break space into a plain one.
      expect(screen.getByText(shown, { normalizer: getDefaultNormalizer({ collapseWhitespace: false }) })).toBeInTheDocument()
    } finally {
      window.localStorage.removeItem(UI_LANGUAGE_STORAGE_KEY)
    }
  })

  it('renders an off-preset override as a selected option — the select never goes blank (RD-4)', async () => {
    // RD-4 (full-audit 2026-07-10): a persisted override outside CONTEXT_SIZE_PRESETS (an older
    // release's rung, a hand-edited settings file) matched no <option>, so the select rendered
    // BLANK. It now gets an extra option in the same label style, selected.
    stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4', contextTokensOverride: 24_576 })
    render(<ModelsScreen />)
    const select = (await screen.findByRole('combobox', { name: /Context window for answers/ })) as HTMLSelectElement
    const option = within(select).getByRole('option', {
      name: tCount('en', 'models.tech.contextValue', 24_576, { count: (24_576).toLocaleString('en') })
    }) as HTMLOptionElement
    expect(option.selected).toBe(true)
    expect(select.value).toBe('24576')
  })

  it('shows the honest memory warning for a big fixed pick — and not for a small one', async () => {
    stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4', contextTokensOverride: 131_072 })
    render(<ModelsScreen />)
    await screen.findByRole('combobox', { name: /Context window for answers/ })
    expect(document.querySelector('.context-size-warning')).not.toBeNull()
    cleanup()

    stubWithSettings({ activeModelId: 'qwen3-4b-instruct-q4', contextTokensOverride: 8192 })
    render(<ModelsScreen />)
    await screen.findByRole('combobox', { name: /Context window for answers/ })
    expect(document.querySelector('.context-size-warning')).toBeNull()
  })
})

describe('ModelsScreen — per-download confirmation (plan §6.1 gate 3)', () => {
  it('confirms size, license, and URL before starting; approved license needs no checkbox', async () => {
    const downloadModel = vi.fn(async (): Promise<DownloadJob> => ({
      jobId: 'j1',
      modelId: 'qwen3-4b-instruct-q4',
      status: 'queued',
      receivedBytes: 0,
      totalBytes: 2_900_000_000,
      unverified: false,
      error: null
    }))
    const getDownloadJob = vi.fn(async (): Promise<DownloadJob> => ({
      jobId: 'j1',
      modelId: 'qwen3-4b-instruct-q4',
      status: 'done',
      receivedBytes: 2_900_000_000,
      totalBytes: 2_900_000_000,
      unverified: false,
      error: null
    }))
    stub({ downloadModel, getDownloadJob })
    const user = userEvent.setup()
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    const dialog = within(screen.getByRole('dialog'))
    expect(dialog.getByText('2.9 GB')).toBeInTheDocument() // 2.9e9 bytes: decimal GB, as the card's figures are (#768)
    expect(dialog.getByText(/apache-2\.0/)).toBeInTheDocument()
    expect(dialog.getByText('https://example.test/qwen3-4b.gguf')).toBeInTheDocument()
    expect(dialog.queryByText(/accept this model’s license/)).not.toBeInTheDocument()

    await user.click(dialog.getByRole('button', { name: 'Start download' }))
    expect(downloadModel).toHaveBeenCalledWith('qwen3-4b-instruct-q4', { licenseAccepted: false })

    // Drive the polled job to its terminal state so the module-level "remembered job"
    // (the leave-and-return resume affordance) cannot leak a live job into later tests.
    expect(await screen.findByText(/Downloading…|Verifying/)).toBeInTheDocument()
    expect(
      await screen.findByRole('button', { name: 'Download' })
    ).toBeInTheDocument()
  })

  // #768: one decimal from 10 GB up as below it. This weight's 14,439,363,584 bytes read "13 GB" in its dialog (GiB,
  // rounded whole) beside a card saying 14.4: under by 1.4 GB, the direction that lets a too-full drive look fine.
  it('states a 14.4 GB weight as 14.4 GB on its card and in its dialog (#768)', async () => {
    stub({
      models: [
        model({
          sizeOnDiskGb: 14.4,
          download: {
            url: 'https://example.test/qwen3-4b.gguf',
            sizeBytes: 14_439_363_584,
            licenseUrl: 'https://example.test/license',
            licenseApproved: true
          }
        })
      ]
    })
    const user = userEvent.setup()
    render(<ModelsScreen />)
    expect(await screen.findByText(/Uses 14\.4 GB of drive space/)).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'Download' }))
    expect(within(screen.getByRole('dialog')).getByText('14.4 GB')).toBeInTheDocument()
  })

  it('requires the explicit license acknowledgement when the review is not approved', async () => {
    const downloadModel = vi.fn(async (): Promise<DownloadJob> => ({
      jobId: 'j2',
      modelId: 'qwen3-4b-instruct-q4',
      status: 'queued',
      receivedBytes: 0,
      totalBytes: null,
      unverified: false,
      error: null
    }))
    const getDownloadJob = vi.fn(async (): Promise<DownloadJob> => ({
      jobId: 'j2',
      modelId: 'qwen3-4b-instruct-q4',
      status: 'cancelled',
      receivedBytes: 0,
      totalBytes: null,
      unverified: false,
      error: null
    }))
    stub({
      models: [
        model({
          download: {
            url: 'https://example.test/qwen3-4b.gguf',
            sizeBytes: null,
            licenseUrl: 'https://example.test/license',
            licenseApproved: false
          }
        })
      ],
      downloadModel,
      getDownloadJob
    })
    const user = userEvent.setup()
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    const start = screen.getByRole('button', { name: 'Start download' })
    expect(start).toBeDisabled()

    await user.click(screen.getByRole('checkbox'))
    expect(start).toBeEnabled()
    await user.click(start)
    expect(downloadModel).toHaveBeenCalledWith('qwen3-4b-instruct-q4', { licenseAccepted: true })
  })

  // FE-2: the Cancel control now has a .catch, so a rejecting cancelDownload surfaces a friendly
  // error instead of an unhandled promise rejection.
  it('surfaces a friendly error (no unhandled rejection) when cancelling a download rejects', async () => {
    // A unique model id so a job remembered by an earlier test in this file (module-level
    // `rememberedJob`, keyed by the default qwen id) can't render a stale live download over our
    // card. Our model starts at the Download affordance.
    const myModel = model({ id: 'cancel-test-model', displayName: 'Cancel Test Model' })
    const downloadModel = vi.fn(async (): Promise<DownloadJob> => ({
      jobId: 'jc',
      modelId: 'cancel-test-model',
      status: 'queued',
      receivedBytes: 0,
      totalBytes: 1000,
      unverified: false,
      error: null
    }))
    // Keep OUR job ('jc') live so the Cancel control stays mounted; drain any leaked job
    // (different jobId) to a terminal state so it disappears.
    const getDownloadJob = vi.fn(
      async (jobId: string): Promise<DownloadJob> =>
        jobId === 'jc'
          ? {
              jobId: 'jc',
              modelId: 'cancel-test-model',
              status: 'downloading',
              receivedBytes: 100,
              totalBytes: 1000,
              unverified: false,
              error: null
            }
          : {
              jobId,
              modelId: 'qwen3-4b-instruct-q4',
              status: 'cancelled',
              receivedBytes: 0,
              totalBytes: null,
              unverified: false,
              error: null
            }
    )
    const cancelDownload = vi.fn(async () => {
      throw new Error("Error invoking remote method 'cancelDownload': Error: cancel exploded")
    })
    stub({ models: [myModel], downloadModel, getDownloadJob })
    ;(window.api as unknown as { cancelDownload: typeof cancelDownload }).cancelDownload =
      cancelDownload
    const user = userEvent.setup()
    render(<ModelsScreen />)

    // A live job remembered by an earlier test would disable every Download button (the global
    // "another download is running" gate); our getDownloadJob drains it on the first poll, so
    // wait for the button to enable before clicking.
    const downloadBtn = await screen.findByRole('button', { name: 'Download' })
    await waitFor(() => expect(downloadBtn).toBeEnabled())
    await user.click(downloadBtn)
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    await user.click(await screen.findByRole('button', { name: 'Cancel download' }))
    // friendlyIpcError strips the transport + Error-class prefix → only the message shows; the
    // .catch means the rejection never escapes as an unhandled promise rejection.
    expect(await screen.findByText('cancel exploded')).toBeInTheDocument()
    // The CODE-28 test below drains this still-live remembered job on its first poll (its
    // getDownloadJob returns a terminal status for foreign job ids); cleanup() unmounts the
    // screen and clears the poll interval.
  })

  // full-audit 2026-07-11 CODE-28: the poll-completion `void refresh()` had no catch — a
  // refresh failing exactly at the download's live→terminal transition left stale cards and
  // an unhandled promise rejection. Now it routes through runAndSurface → the error banner.
  it('surfaces a failing poll-completion refresh on the error banner (no unhandled rejection)', async () => {
    const myModel = model({ id: 'refresh-fail-model', displayName: 'Refresh Fail Model' })
    let failRefresh = false
    const listModels = vi.fn(async () => {
      if (failRefresh) {
        throw new Error("Error invoking remote method 'models:list': Error: refresh exploded")
      }
      return [myModel]
    })
    const downloadModel = vi.fn(async (): Promise<DownloadJob> => ({
      jobId: 'jr',
      modelId: 'refresh-fail-model',
      status: 'queued',
      receivedBytes: 0,
      totalBytes: 1000,
      unverified: false,
      error: null
    }))
    // OUR job ('jr') completes on its first poll — and from that moment every refresh fails,
    // so the completion refresh is the one that rejects. Foreign (leaked) jobs drain terminal.
    const getDownloadJob = vi.fn(async (jobId: string): Promise<DownloadJob> => {
      if (jobId === 'jr') {
        failRefresh = true
        return {
          jobId: 'jr',
          modelId: 'refresh-fail-model',
          status: 'done',
          receivedBytes: 1000,
          totalBytes: 1000,
          unverified: false,
          error: null
        }
      }
      return { jobId, modelId: 'qwen3-4b-instruct-q4', status: 'cancelled', receivedBytes: 0, totalBytes: null, unverified: false, error: null }
    })
    stubModelsApi({
      listModels,
      getSettings: vi.fn(async () => ({ ...DEFAULT_SETTINGS, activeModelId: null })),
      downloadModel: downloadModel,
      getDownloadJob: getDownloadJob
    })
    const user = userEvent.setup()
    render(<ModelsScreen />)

    // Wait out any leaked live job (see the cancel test above) so Download is clickable.
    const downloadBtn = await screen.findByRole('button', { name: 'Download' })
    await waitFor(() => expect(downloadBtn).toBeEnabled())
    await user.click(downloadBtn)
    await user.click(screen.getByRole('button', { name: 'Start download' }))

    // The first poll flips the job queued→done → the completion refresh runs → listModels
    // rejects → the friendly message (transport prefix stripped) lands on the error banner.
    expect(await screen.findByText('refresh exploded')).toBeInTheDocument()
    // The remembered job ends terminal ('done'), so nothing live leaks into later tests.
  })
})

describe('ModelsScreen — the licence link names its host and is https-only (#236)', () => {
  async function openConfirm(m: ModelInfo): Promise<ReturnType<typeof within>> {
    stub({ models: [m] })
    const user = userEvent.setup()
    render(<ModelsScreen />)
    await user.click(await screen.findByRole('button', { name: 'Download' }))
    return within(screen.getByRole('dialog'))
  }

  it('shows the licence host beside the link, and the href is the https URL', async () => {
    const dialog = await openConfirm(
      model({
        download: {
          url: 'https://example.test/qwen3-4b.gguf',
          sizeBytes: 2_900_000_000,
          licenseUrl: 'https://licenses.example.test/qwen/LICENSE',
          licenseApproved: true
        }
      })
    )
    const link = dialog.getByRole('link', { name: t('en', 'models.confirm.readLicense') })
    expect(link).toHaveAttribute('href', 'https://licenses.example.test/qwen/LICENSE')
    expect(dialog.getByText(/licenses\.example\.test/)).toBeInTheDocument()
  })

  it('a non-https licence URL (a stale or hostile manifest) never renders as a link', async () => {
    const dialog = await openConfirm(
      model({
        download: {
          url: 'https://example.test/qwen3-4b.gguf',
          sizeBytes: 2_900_000_000,
          licenseUrl: 'http://licenses.example.test/qwen/LICENSE',
          licenseApproved: true
        }
      })
    )
    expect(dialog.queryByRole('link', { name: t('en', 'models.confirm.readLicense') })).not.toBeInTheDocument()
    expect(dialog.getByText(/apache-2\.0/)).toBeInTheDocument() // the licence name still shows
  })
})

// PR #302 fix wave P3 (audit finding F2, gate B1): a download that FAILS, or completes without a
// verifiable checksum, used to lose its independent panel at exactly the moment the user needed
// it — the result then only lived on the model's own row, which a search, a task/family/view
// filter or a collapsed variant group may be hiding. The panel now keeps a NAMED result with
// Retry / Dismiss until the user acts, a new download is accepted, or the download ends verified
// or cancelled. The first seven cases are ports of the audit's `model-library.probe.tsx`; the
// rest pin the lifecycle, gating and stale-response contract of the fix.
describe('ModelsScreen — terminal download results stay visible (PR #302 F2, B1)', () => {
  const REGION = 'Current model download'
  const RETRY = t('en', 'models.download.retry')
  const DISMISS = t('en', 'models.download.dismiss')

  function variant(id: string, displayName: string, over: Partial<ModelInfo> = {}): ModelInfo {
    return model({ id, displayName, family: 'qwen3.8', ...over })
  }

  function jobOf(jobId: string, modelId: string, over: Partial<DownloadJob> = {}): DownloadJob {
    return {
      jobId,
      modelId,
      status: 'downloading',
      receivedBytes: 10,
      totalBytes: 1000,
      unverified: false,
      error: null,
      ...over
    }
  }

  /** Every bridge method the screen actually calls, so `assertNoUnexpectedApiCalls` has teeth. */
  function stubLive(opts: {
    models: () => ModelInfo[]
    job?: () => DownloadJob
    policy?: () => PolicyStatus
    activeModelId?: string | null
    downloadModel?: (id: string, o?: { licenseAccepted?: boolean }) => Promise<DownloadJob>
    getDownloadJob?: (jobId: string) => Promise<DownloadJob>
    listModels?: () => Promise<ModelInfo[]>
    useModel?: Mock
    /** #314: what the MAIN process still holds — what a reloaded screen adopts on mount. */
    listDownloadJobs?: () => Promise<DownloadJob[]>
  }): {
    listModels: Mock
    downloadModel: Mock
    getDownloadJob: Mock
    listDownloadJobs: Mock
    dismissDownloadJob: Mock
  } {
    const listModels = vi.fn(opts.listModels ?? (async () => opts.models()))
    const downloadModel = vi.fn(opts.downloadModel ?? (async () => opts.job!()))
    const getDownloadJob = vi.fn(opts.getDownloadJob ?? (async () => opts.job!()))
    const listDownloadJobs = vi.fn(opts.listDownloadJobs ?? (async () => []))
    const dismissDownloadJob = vi.fn(async () => undefined)
    stubModelsApi({
      listModels,
      getSettings: vi.fn(async () => ({
        ...DEFAULT_SETTINGS,
        activeModelId: opts.activeModelId ?? null
      })),
      getPolicy: vi.fn(async () =>
        (opts.policy ?? (() => policyStatus({ downloadsAllowed: true, settingOn: true })))()
      ),
      downloadModel,
      getDownloadJob,
      listDownloadJobs,
      dismissDownloadJob,
      ...(opts.useModel ? { useModel: opts.useModel } : {})
    })
    return { listModels, downloadModel, getDownloadJob, listDownloadJobs, dismissDownloadJob }
  }

  const panel = (): ReturnType<typeof within> =>
    within(screen.getByRole('region', { name: REGION }))

  /** The `.model-card` for a display name — never the panel's own <strong> heading. */
  function cardFor(displayName: string): HTMLElement {
    const card = screen
      .getAllByText(displayName)
      .map((el) => el.closest('.model-card'))
      .find((el): el is HTMLElement => el != null)
    expect(card).toBeTruthy()
    return card as HTMLElement
  }

  function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
    let resolve!: (value: T) => void
    const promise = new Promise<T>((r) => {
      resolve = r
    })
    return { promise, resolve }
  }

  afterEach(() => {
    cleanup()
    assertNoUnexpectedApiCalls()
  })

  // ---- Ported audit probes (`model-library.probe.tsx`) -----------------------------------------

  it.each(['search', 'collapsed group'] as const)(
    'keeps a failed download visible after hiding its row via %s',
    async (hide) => {
      const user = userEvent.setup()
      const first = variant(`f1-${hide}`, 'Result group Q4_K_M')
      const second = variant(`f2-${hide}`, 'Result group Q6_K')
      let current = jobOf(`failed-${hide}`, second.id)
      stubLive({ models: () => [first, second], job: () => current })
      render(<ModelsScreen />)

      await user.click(await screen.findByRole('button', { name: 'Show all variants (2)' }))
      await user.click(within(cardFor(second.displayName)).getByRole('button', { name: 'Download' }))
      await user.click(screen.getByRole('button', { name: 'Start download' }))
      await screen.findByRole('region', { name: REGION })
      if (hide === 'search') await user.type(screen.getByRole('searchbox'), 'no match')
      else await user.click(screen.getByRole('button', { name: 'Show fewer variants (2)' }))

      current = { ...current, status: 'failed', error: `download failed (${hide})` }

      // The result names its model and carries its own recovery actions, wherever it renders.
      expect(await panel().findByText(`download failed (${hide})`)).toBeVisible()
      expect(panel().getByText(second.displayName)).toBeVisible()
      expect(panel().getByRole('button', { name: RETRY })).toBeEnabled()
      expect(panel().getByRole('button', { name: DISMISS })).toBeEnabled()
    }
  )

  it.each(['search', 'collapsed group'] as const)(
    'keeps an unverified completion warning visible through %s',
    async (hide) => {
      const user = userEvent.setup()
      const first = variant(`u1-${hide}`, 'Unverified group Q4_K_M')
      let second = variant(`u2-${hide}`, 'Unverified group Q6_K')
      let current = jobOf(`unverified-${hide}`, second.id)
      stubLive({ models: () => [first, second], job: () => current })
      render(<ModelsScreen />)

      await user.click(await screen.findByRole('button', { name: 'Show all variants (2)' }))
      await user.click(within(cardFor(second.displayName)).getByRole('button', { name: 'Download' }))
      await user.click(screen.getByRole('button', { name: 'Start download' }))
      await screen.findByRole('region', { name: REGION })
      if (hide === 'search') await user.type(screen.getByRole('searchbox'), 'no match')
      else await user.click(screen.getByRole('button', { name: 'Show fewer variants (2)' }))

      second = { ...second, state: 'installed' }
      current = { ...current, status: 'done', unverified: true, receivedBytes: 1000 }

      expect(await panel().findByText('verify-models --generate')).toBeVisible()
      if (hide === 'search') {
        // The search still excludes it entirely — no row anywhere — so the panel names it.
        expect(panel().getByText(second.displayName)).toBeVisible()
      } else {
        // #315 — now installed, it outranks its still-missing sibling and becomes the
        // collapsed group's FACE (`variantGroupFace`), so its row renders despite the
        // collapse: the panel drops its own name line, the row (the face) carries it.
        expect(panel().queryByText(second.displayName)).toBeNull()
        expect(cardFor(second.displayName)).toBeVisible()
      }
      expect(panel().getByRole('button', { name: DISMISS })).toBeEnabled()
    }
  )

  it('#315 the panel names the model only while its row is off screen', async () => {
    const user = userEvent.setup()
    const first = variant('r315-q4', 'Row swap group Q4_K_M')
    const second = variant('r315-q6', 'Row swap group Q6_K')
    let current = jobOf('r315-job', second.id)
    stubLive({ models: () => [first, second], job: () => current })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Show all variants (2)' }))
    await user.click(within(cardFor(second.displayName)).getByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    const region = await screen.findByRole('region', { name: REGION })
    const alert = within(region).getByRole('alert')

    current = { ...current, status: 'failed', error: 'row swap failure' }
    await panel().findByText('row swap failure')

    // Collapsed: the row is off screen, so the panel names the model.
    await user.click(screen.getByRole('button', { name: 'Show fewer variants (2)' }))
    expect(panel().getByText(second.displayName)).toBeVisible()
    expect(panel().getByRole('button', { name: RETRY })).toBeEnabled()
    expect(panel().getByRole('button', { name: DISMISS })).toBeEnabled()

    // Expanded: the row is back, so the panel drops its own name line — the row carries it.
    await user.click(screen.getByRole('button', { name: 'Show all variants (2)' }))
    expect(panel().queryByText(second.displayName)).toBeNull()
    expect(cardFor(second.displayName)).toBeVisible()

    // A non-matching search hides the row again, so the name returns to the panel.
    await user.type(screen.getByRole('searchbox'), 'no match')
    expect(await panel().findByText(second.displayName)).toBeVisible()

    // Clearing the search restores the (still expanded) row: the name leaves the panel again.
    await user.clear(screen.getByRole('searchbox'))
    await waitFor(() => expect(panel().queryByText(second.displayName)).toBeNull())
    expect(cardFor(second.displayName)).toBeVisible()

    // The region label, the alert node identity and the Retry/Dismiss names never changed.
    expect(screen.getByRole('region', { name: REGION })).toBe(region)
    expect(within(region).getByRole('alert')).toBe(alert)
    expect(panel().getByRole('button', { name: RETRY })).toBeEnabled()
    expect(panel().getByRole('button', { name: DISMISS })).toBeEnabled()
  })

  it('sends the exact expanded variant ID and its own license acknowledgement to downloadModel', async () => {
    const user = userEvent.setup()
    const first = variant('q4-action-control', 'Action control Q4_K_M')
    const second = variant('q6-action-control', 'Action control Q6_K', {
      download: {
        url: 'https://example.test/q6.gguf',
        sizeBytes: 1000,
        licenseUrl: 'https://example.test/license',
        licenseApproved: false
      }
    })
    const api = stubLive({
      models: () => [first, second],
      job: () => jobOf('action-control', second.id, { status: 'cancelled' })
    })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Show all variants (2)' }))
    await user.click(within(cardFor(second.displayName)).getByRole('button', { name: 'Download' }))
    const dialog = within(screen.getByRole('dialog'))
    expect(dialog.getByRole('button', { name: 'Start download' })).toBeDisabled()
    expect(api.downloadModel).not.toHaveBeenCalled()
    await user.click(dialog.getByRole('checkbox'))
    await user.click(dialog.getByRole('button', { name: 'Start download' }))
    expect(api.downloadModel).toHaveBeenCalledExactlyOnceWith(second.id, { licenseAccepted: true })
  })

  it('sends the exact expanded installed variant ID to useModel', async () => {
    const user = userEvent.setup()
    const first = variant('q4-use-control', 'Use control Q4_K_M', { state: 'installed' })
    const second = variant('q6-use-control', 'Use control Q6_K', { state: 'installed' })
    const useModel = vi.fn(async () => STOPPED_RUNTIME)
    stubLive({ models: () => [first, second], useModel })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Show all variants (2)' }))
    await user.click(
      within(cardFor(second.displayName)).getByRole('button', { name: t('en', 'models.use') })
    )
    expect(useModel).toHaveBeenCalledExactlyOnceWith(second.id)
  })

  it('preserves Browse and finds the installed model after a filtered verified completion', async () => {
    const user = userEvent.setup()
    let entry = variant('completion-control', 'Completed model Q4')
    let current = jobOf('completion-control-job', entry.id)
    stubLive({ models: () => [entry], job: () => current })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    await user.type(screen.getByRole('searchbox'), 'no match')

    entry = { ...entry, state: 'installed' }
    current = { ...current, status: 'done', receivedBytes: 1000 }

    // A VERIFIED completion needs no result surface — today's behaviour is preserved exactly.
    // (No positive query settles this: the panel disappears, so a `waitFor` around the actual
    // absence assertion replaces the call-count wait, per the flake-fix's `findBy` alternative.)
    await waitFor(() => expect(screen.queryByRole('region', { name: REGION })).not.toBeInTheDocument())
    expect(screen.getByRole('radio', { name: 'Browse models' })).toHaveAttribute(
      'aria-checked',
      'true'
    )
    await user.click(screen.getByRole('button', { name: 'Clear filters' }))
    expect(screen.getByRole('button', { name: t('en', 'models.use') })).toBeEnabled()
  })

  // ---- Hiding controls beyond search / collapse -------------------------------------------------

  it.each(['task', 'family', 'view'] as const)(
    'keeps a failed result visible when the %s filter hides its row',
    async (control) => {
      const user = userEvent.setup()
      const chatModel = variant(`hidden-${control}`, `Hidden chat model ${control}`)
      const other = model({
        id: `other-${control}`,
        displayName: `Other embedder ${control}`,
        family: 'e5',
        role: 'embeddings'
      })
      let current = jobOf(`hide-${control}`, chatModel.id)
      stubLive({ models: () => [chatModel, other], job: () => current })
      render(<ModelsScreen />)

      await screen.findByText(chatModel.displayName)
      await user.click(
        within(cardFor(chatModel.displayName)).getByRole('button', { name: 'Download' })
      )
      await user.click(screen.getByRole('button', { name: 'Start download' }))
      current = { ...current, status: 'failed', error: `hidden by ${control}` }

      if (control === 'task') {
        await user.selectOptions(screen.getByRole('combobox', { name: 'Task' }), 'documents')
      } else if (control === 'family') {
        await user.selectOptions(screen.getByRole('combobox', { name: 'Family' }), 'e5')
      } else {
        await user.click(screen.getByRole('radio', { name: 'On this drive' }))
      }

      // No ROW carries the model any more — only the panel does.
      const rows = [...document.querySelectorAll('.model-card')]
      expect(rows.some((row) => row.textContent?.includes(chatModel.displayName))).toBe(false)
      expect(await panel().findByText(`hidden by ${control}`)).toBeVisible()
      expect(panel().getByText(chatModel.displayName)).toBeVisible()
      expect(panel().getByRole('button', { name: RETRY })).toBeInTheDocument()
    }
  )

  // ---- Structural: one panel node, one always-mounted alert node --------------------------------

  it('keeps the SAME panel and alert nodes across the live → failed transition', async () => {
    const user = userEvent.setup()
    const entry = variant('same-node', 'Same node model')
    let current = jobOf('same-node-job', entry.id)
    stubLive({ models: () => [entry], job: () => current })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    const region = await screen.findByRole('region', { name: REGION })
    const alert = within(region).getByRole('alert')
    // Mounted and EMPTY during progress: a live region that only appears at failure is not
    // reliably announced (the SH-2 / M-U1 discipline applied to the download panel).
    expect(alert).toBeInTheDocument()
    expect(alert).toHaveTextContent('')

    current = { ...current, status: 'failed', error: 'the connection dropped' }

    // Identity is unaffected by the pending refresh (the node was mounted before it); only the
    // alert's own text depends on the refresh landing, so that is the one assertion worth a wait.
    expect(screen.getByRole('region', { name: REGION })).toBe(region)
    expect(within(region).getByRole('alert')).toBe(alert)
    await waitFor(() => expect(alert).toHaveTextContent('the connection dropped'))
    // #436: the panel keeps its own hand-rolled copy of the ErrorBanner wrapper, and it had the
    // same defect — a nested Banner role="status" is a live region itself, so it swallowed the
    // announcement. Nothing inside this alert may carry a live-region role.
    expect(alert.querySelectorAll('[role], [aria-live]')).toHaveLength(0)
  })

  // ---- Refresh at the terminal transition -------------------------------------------------------

  it.each(['as installed', 'not at all'] as const)(
    'keeps the named result when the refresh returns the model %s',
    async (how) => {
      const user = userEvent.setup()
      let entry = variant(
        `refresh-${how === 'as installed' ? 'installed' : 'gone'}`,
        'Refreshed model Q4'
      )
      let listed: ModelInfo[] = [entry]
      let current = jobOf(`refresh-job-${how === 'as installed' ? 'installed' : 'gone'}`, entry.id)
      stubLive({ models: () => listed, job: () => current })
      render(<ModelsScreen />)

      await user.click(await screen.findByRole('button', { name: 'Download' }))
      await user.click(screen.getByRole('button', { name: 'Start download' }))

      entry = { ...entry, state: 'installed' }
      listed = how === 'as installed' ? [entry] : []
      current = { ...current, status: 'failed', error: 'checksum mismatch after retry' }

      expect(await panel().findByText('checksum mismatch after retry')).toBeVisible()
      if (how === 'not at all') {
        // The refresh dropped the model entirely — no row anywhere — so the panel is the
        // only place left to name it.
        expect(panel().getByText('Refreshed model Q4')).toBeVisible()
        // No retry target left: explained, not a button that could only fail.
        expect(panel().getByRole('button', { name: RETRY })).toBeDisabled()
        expect(panel().getByText(t('en', 'models.download.retryUnavailable'))).toBeVisible()
      } else {
        // #315 — the refresh kept it (now installed) and Browse lists it regardless of state,
        // so its row is on screen: the panel does not repeat the name, the row still carries it.
        expect(panel().queryByText('Refreshed model Q4')).toBeNull()
        expect(cardFor('Refreshed model Q4')).toBeVisible()
      }
    }
  )

  it('keeps the result and shows the friendly error when the completion refresh rejects', async () => {
    const user = userEvent.setup()
    const entry = variant('refresh-reject', 'Refresh reject model')
    let failRefresh = false
    let current = jobOf('refresh-reject-job', entry.id)
    stubLive({
      models: () => [entry],
      job: () => current,
      listModels: async () => {
        if (failRefresh) {
          throw new Error("Error invoking remote method 'models:list': Error: refresh exploded")
        }
        return [entry]
      }
    })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    failRefresh = true
    current = { ...current, status: 'failed', error: 'server closed the connection' }

    expect(
      await screen.findByText('refresh exploded')
    ).toBeInTheDocument()
    expect(panel().getByText('server closed the connection')).toBeVisible()
    // #315 — the failed refresh left the previous model list (and its row) in place, so the
    // panel does not repeat the name; the row still carries it.
    expect(panel().queryByText(entry.displayName)).toBeNull()
    expect(cardFor(entry.displayName)).toBeVisible()
  })

  // ---- Dismiss ----------------------------------------------------------------------------------

  it('Dismiss drops the panel and hands the row back its own recovery UI', async () => {
    const user = userEvent.setup()
    const entry = variant('dismiss-model', 'Dismiss model Q4')
    let current = jobOf('dismiss-job', entry.id)
    stubLive({ models: () => [entry], job: () => current })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    current = { ...current, status: 'failed', error: 'disk full' }
    // While the panel owns the job the row does not repeat the outcome.
    expect(within(cardFor(entry.displayName)).queryByText('disk full')).not.toBeInTheDocument()

    await user.click(await panel().findByRole('button', { name: DISMISS }))
    expect(screen.queryByRole('region', { name: REGION })).not.toBeInTheDocument()
    const row = within(cardFor(entry.displayName))
    expect(row.getByRole('button', { name: t('en', 'models.download.resume') })).toBeEnabled()
    expect(row.getByText('disk full')).toBeVisible()
  })

  it('a dismissed result does not come back on a re-render or a remount', async () => {
    const user = userEvent.setup()
    const entry = variant('dismiss-sticky', 'Dismiss sticky Q4')
    let current = jobOf('dismiss-sticky-job', entry.id)
    stubLive({ models: () => [entry], job: () => current })
    const view = render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    current = { ...current, status: 'failed', error: 'gone for good' }
    await user.click(await panel().findByRole('button', { name: DISMISS }))

    // A re-render driven by a filter change must not resurrect it…
    await user.click(screen.getByRole('radio', { name: 'Browse models' }))
    expect(screen.queryByRole('region', { name: REGION })).not.toBeInTheDocument()

    // …and neither must leaving and re-entering the screen (the dismissal is remembered by id).
    view.unmount()
    render(<ModelsScreen />)
    await screen.findByText(entry.displayName)
    expect(screen.queryByRole('region', { name: REGION })).not.toBeInTheDocument()
    expect(screen.getByText('gone for good')).toBeVisible() // the row still explains it
  })

  // ---- Retry ------------------------------------------------------------------------------------

  it('Retry opens the existing confirmation for the exact variant; cancelling keeps the result', async () => {
    const user = userEvent.setup()
    const first = variant('retry-q4', 'Retry group Q4_K_M')
    const second = variant('retry-q6', 'Retry group Q6_K', {
      download: {
        url: 'https://example.test/retry-q6.gguf',
        sizeBytes: 1000,
        licenseUrl: 'https://licenses.example.test/q6/LICENSE',
        licenseApproved: true
      }
    })
    let current = jobOf('retry-dialog-job', second.id)
    const api = stubLive({ models: () => [first, second], job: () => current })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Show all variants (2)' }))
    await user.click(within(cardFor(second.displayName)).getByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    current = { ...current, status: 'failed', error: 'retry me' }

    await user.click(await panel().findByRole('button', { name: RETRY }))
    const dialog = within(screen.getByRole('dialog'))
    expect(screen.getByRole('dialog')).toHaveTextContent(second.displayName)
    expect(dialog.getByText('https://example.test/retry-q6.gguf')).toBeInTheDocument()
    expect(dialog.getByRole('link', { name: t('en', 'models.confirm.readLicense') })).toHaveAttribute(
      'href',
      'https://licenses.example.test/q6/LICENSE'
    )
    await user.click(dialog.getByRole('button', { name: 'Cancel' }))
    expect(api.downloadModel).toHaveBeenCalledTimes(1) // the original start only
    expect(panel().getByText('retry me')).toBeVisible()
  })

  it('a rejected retry keeps the result and surfaces the friendly error', async () => {
    const user = userEvent.setup()
    const entry = variant('retry-reject', 'Retry reject Q4')
    let current = jobOf('retry-reject-job', entry.id)
    let rejectNext = false
    stubLive({
      models: () => [entry],
      job: () => current,
      downloadModel: async () => {
        if (rejectNext) {
          throw new Error("Error invoking remote method 'downloads:start': Error: start refused")
        }
        return current
      }
    })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    current = { ...current, status: 'failed', error: 'first attempt failed' }

    rejectNext = true
    await user.click(await panel().findByRole('button', { name: RETRY }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))

    expect(await screen.findByText('start refused')).toBeInTheDocument()
    expect(panel().getByText('first attempt failed')).toBeVisible()
  })

  it('a successful retry re-asks for the licence, reuses the exact id and replaces the panel', async () => {
    const user = userEvent.setup()
    const entry = variant('retry-ok', 'Retry ok Q4', {
      download: {
        url: 'https://example.test/retry-ok.gguf',
        sizeBytes: 1000,
        licenseUrl: 'https://example.test/license',
        licenseApproved: false
      }
    })
    let current = jobOf('retry-ok-job-1', entry.id)
    const api = stubLive({
      models: () => [entry],
      job: () => current,
      downloadModel: async () => current
    })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('checkbox'))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    current = { ...current, status: 'failed', error: 'first attempt failed' }

    await user.click(await panel().findByRole('button', { name: RETRY }))
    // The acknowledgement is RESET — a retry never silently accepts a pending license.
    const dialog = within(screen.getByRole('dialog'))
    expect(dialog.getByRole('checkbox')).not.toBeChecked()
    expect(dialog.getByRole('button', { name: 'Start download' })).toBeDisabled()
    current = jobOf('retry-ok-job-2', entry.id)
    await user.click(dialog.getByRole('checkbox'))
    await user.click(dialog.getByRole('button', { name: 'Start download' }))

    expect(api.downloadModel).toHaveBeenCalledTimes(2)
    expect(api.downloadModel).toHaveBeenLastCalledWith(entry.id, { licenseAccepted: true })
    // The accepted job REPLACES the result: live progress, and the old failure is gone.
    expect(panel().getByRole('button', { name: 'Cancel download' })).toBeInTheDocument()
    expect(screen.queryByText('first attempt failed')).not.toBeInTheDocument()
  })

  it('disables Retry with the policy reason when downloads are gated at the refresh', async () => {
    const user = userEvent.setup()
    const entry = variant('retry-gated', 'Retry gated Q4')
    let current = jobOf('retry-gated-job', entry.id)
    let allowed = true
    stubLive({
      models: () => [entry],
      job: () => current,
      policy: () => policyStatus({ downloadsAllowed: allowed, settingOn: true })
    })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    allowed = false
    current = { ...current, status: 'failed', error: 'network went away' }

    const retry = await panel().findByRole('button', { name: RETRY })
    expect(retry).toBeDisabled()
    expect(retry).toHaveAttribute('title', t('en', 'models.downloads.blockedByPolicy'))
    expect(panel().getByText('network went away')).toBeVisible()
  })

  it('disables Retry and explains when the download was withdrawn at the refresh (#196)', async () => {
    const user = userEvent.setup()
    let entry = variant('retry-withdrawn', 'Retry withdrawn Q4')
    let current = jobOf('retry-withdrawn-job', entry.id)
    stubLive({ models: () => [entry], job: () => current })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    entry = {
      ...entry,
      download: { ...entry.download!, withdrawn: '2026-09-01: upstream deleted the file' }
    }
    current = { ...current, status: 'failed', error: 'HTTP 404' }

    expect(await panel().findByRole('button', { name: RETRY })).toBeDisabled()
    expect(panel().getByText(/No longer available for download/)).toBeVisible()
    expect(panel().getByText('HTTP 404')).toBeVisible()
  })

  // ---- A retained result must never behave like a live job --------------------------------------

  it('never blocks another model: Download and Use stay enabled, and a new job replaces the result', async () => {
    const user = userEvent.setup()
    const failing = variant('stale-failing', 'Stale failing Q4')
    const another = model({
      id: 'stale-other',
      displayName: 'Another downloadable model',
      family: 'gemma'
    })
    const installed = model({
      id: 'stale-installed',
      displayName: 'Another installed model',
      family: 'phi',
      state: 'installed'
    })
    let current = jobOf('stale-failing-job', failing.id)
    stubLive({
      models: () => [failing, another, installed],
      job: () => current,
      downloadModel: async (id) => {
        if (id === another.id) current = jobOf('stale-new-job', id)
        return current
      },
      useModel: vi.fn(async () => STOPPED_RUNTIME)
    })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('radio', { name: 'Browse models' }))
    await user.click(within(cardFor(failing.displayName)).getByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    current = { ...current, status: 'failed', error: 'stale result' }

    // The ONLY gate on other rows is still a LIVE job (`JOB_LIVE`) — a retained result is not one.
    // The button exists throughout (only its disabled state depends on the refresh landing), so
    // the wait belongs on the enabled assertion itself, not on the button's mere presence.
    await waitFor(() =>
      expect(
        within(cardFor(another.displayName)).getByRole('button', { name: 'Download' })
      ).toBeEnabled()
    )
    expect(
      within(cardFor(installed.displayName)).getByRole('button', { name: t('en', 'models.use') })
    ).toBeEnabled()

    await user.click(within(cardFor(another.displayName)).getByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    // #315 — Browse lists every row regardless of state, so `another`'s row is on screen: the
    // panel does not repeat the name, the row still carries it.
    expect(panel().queryByText(another.displayName)).toBeNull()
    expect(cardFor(another.displayName)).toBeVisible()
    expect(screen.queryByText('stale result')).not.toBeInTheDocument()
  })

  it('ignores a late poll response for a job that is no longer current', async () => {
    const user = userEvent.setup()
    const first = variant('late-first', 'Late first Q4')
    const second = model({ id: 'late-second', displayName: 'Late second model', family: 'gemma' })
    const late = deferred<DownloadJob>()
    const firstFailed = jobOf('late-job-1', first.id, { status: 'failed', error: 'late failure' })
    let currentSecond = jobOf('late-job-2', second.id)
    let firstPolls = 0
    const api = stubLive({
      models: () => [first, second],
      getDownloadJob: async (jobId) => {
        if (jobId === 'late-job-1') {
          firstPolls += 1
          // The FIRST poll never settles until the test releases it; the second reports the
          // failure, so the panel reaches its terminal state with one response still in flight.
          return firstPolls === 1 ? late.promise : firstFailed
        }
        return currentSecond
      },
      downloadModel: async (id) => {
        if (id === second.id) {
          currentSecond = jobOf('late-job-2', second.id)
          return currentSecond
        }
        return jobOf('late-job-1', first.id)
      }
    })
    render(<ModelsScreen />)

    await screen.findByText(first.displayName)
    await user.click(within(cardFor(first.displayName)).getByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    await waitFor(() => expect(panel().getByText('late failure')).toBeVisible())

    await user.click(within(cardFor(second.displayName)).getByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    // #315 — Browse lists `second`'s row throughout, so the panel does not repeat its name.
    expect(panel().queryByText(second.displayName)).toBeNull()
    expect(cardFor(second.displayName)).toBeVisible()

    late.resolve(firstFailed)
    await act(async () => {
      await late.promise
    })
    // The stale response must not resurrect the replaced result.
    expect(screen.queryByText('late failure')).not.toBeInTheDocument()
    expect(panel().queryByText(second.displayName)).toBeNull()
    expect(cardFor(second.displayName)).toBeVisible()
    expect(api.listModels).toHaveBeenCalled()
  })

  // ---- Remembered job across ordinary screen navigation -----------------------------------------

  it('shows the named result on return when the download failed while the screen was away', async () => {
    const user = userEvent.setup()
    const entry = variant('away-model', 'Away model Q4')
    let current = jobOf('away-job', entry.id)
    stubLive({ models: () => [entry], job: () => current })
    const view = render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    await screen.findByRole('region', { name: REGION })

    view.unmount() // leaving the screen; the job keeps running in the main process
    current = { ...current, status: 'failed', error: 'failed while away' }

    render(<ModelsScreen />) // …and coming back resumes the remembered job and shows its result
    await waitFor(() => expect(panel().getByText('failed while away')).toBeVisible())
    // #315 — Browse lists the row regardless of state, so it is on screen here too: the panel
    // does not repeat the name, the row still carries it.
    expect(panel().queryByText(entry.displayName)).toBeNull()
    expect(cardFor(entry.displayName)).toBeVisible()
    expect(panel().getByRole('button', { name: RETRY })).toBeEnabled()
  })

  // ---- Automatic roles share the surface --------------------------------------------------------

  it('names the result for an automatic-role download (embeddings) in the default view', async () => {
    const user = userEvent.setup()
    const embedder = model({
      id: 'auto-embedder',
      displayName: 'Document embedder (E5)',
      family: 'e5',
      role: 'embeddings'
    })
    let current = jobOf('auto-embedder-job', embedder.id)
    stubLive({ models: () => [embedder], job: () => current })
    render(<ModelsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Download' }))
    await user.click(screen.getByRole('button', { name: 'Start download' }))
    current = { ...current, status: 'failed', error: 'embedder download failed' }

    expect(await panel().findByText('embedder download failed')).toBeVisible()
    // #315 — the default view lists this automatic-role row too, so the panel does not repeat
    // the name; the row is where it is actually named.
    expect(panel().queryByText(embedder.displayName)).toBeNull()
    expect(cardFor(embedder.displayName)).toBeVisible()
  })

  // ---- EN + DE ----------------------------------------------------------------------------------

  it('renders the failed result, Retry and Dismiss from the German catalog (D-L8)', async () => {
    const user = userEvent.setup()
    const entry = variant('de-model', 'DE Modell Q4')
    let current = jobOf('de-job', entry.id)
    stubLive({ models: () => [entry], job: () => current })
    window.localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, 'de')
    try {
      render(
        <I18nProvider>
          <ModelsScreen />
        </I18nProvider>
      )
      await user.click(await screen.findByRole('button', { name: t('de', 'models.download.start') }))
      await user.click(screen.getByRole('button', { name: t('de', 'models.confirm.start') }))
      current = { ...current, status: 'failed', error: 'Verbindung abgebrochen' }

      const de = within(screen.getByRole('region', { name: t('de', 'models.library.download') }))
      expect(
        await de.findByText(t('de', 'models.download.failed', { name: entry.displayName }))
      ).toBeVisible()
      expect(de.getByText('Verbindung abgebrochen')).toBeVisible()
      expect(de.getByRole('button', { name: t('de', 'models.download.retry') })).toBeEnabled()
      expect(de.getByRole('button', { name: t('de', 'models.download.dismiss') })).toBeEnabled()
    } finally {
      window.localStorage.removeItem(UI_LANGUAGE_STORAGE_KEY)
    }
  })

  // ---- A renderer reload (#314) -----------------------------------------------------------------

  describe('#314 — a download survives a renderer reload', () => {
    /**
     * A renderer reload as far as this screen can tell: the component goes away AND the module
     * memory it normally recovers from is recreated empty. Everything the screen shows afterwards
     * has to come back from the main process, through `listDownloadJobs`.
     */
    function reload(view: ReturnType<typeof render>): void {
      view.unmount()
      __resetModelsScreenMemoryForTests()
    }

    it('re-attaches progress and Cancel to the right model when the download is still running', async () => {
      const user = userEvent.setup()
      const entry = variant('reload-live', 'Reload live Q4')
      const bystander = model({
        id: 'reload-bystander',
        displayName: 'Bystander model',
        family: 'gemma'
      })
      const live = jobOf('reload-live-job', entry.id, { receivedBytes: 500, totalBytes: 1000 })
      let mainSide: DownloadJob[] = []
      const api = stubLive({
        models: () => [entry, bystander],
        job: () => live,
        listDownloadJobs: async () => mainSide
      })

      const view = render(<ModelsScreen />)
      await screen.findByText(entry.displayName)
      await user.click(within(cardFor(entry.displayName)).getByRole('button', { name: 'Download' }))
      await user.click(screen.getByRole('button', { name: 'Start download' }))
      await screen.findByRole('region', { name: REGION })

      mainSide = [live] // what the main process is still holding when the page reloads
      reload(view)

      render(<ModelsScreen />)
      await screen.findByRole('region', { name: REGION })
      // #315 — Browse lists the row again after the reload, so the panel does not repeat the
      // name; the row still carries it.
      expect(panel().queryByText(entry.displayName)).toBeNull()
      expect(cardFor(entry.displayName)).toBeVisible()
      expect(panel().queryByText(bystander.displayName)).not.toBeInTheDocument()
      expect(panel().getByRole('button', { name: t('en', 'models.download.cancel') })).toBeEnabled()
      // …and the poll resumes against the adopted id, not a remembered one.
      await waitFor(() => expect(api.getDownloadJob).toHaveBeenCalledWith(live.jobId))
    })

    it('shows an undismissed failed result again — named, with its error and gated actions', async () => {
      const user = userEvent.setup()
      const entry = variant('reload-failed', 'Reload failed Q4')
      let current = jobOf('reload-failed-job', entry.id)
      let mainSide: DownloadJob[] = []
      stubLive({ models: () => [entry], job: () => current, listDownloadJobs: async () => mainSide })

      const view = render(<ModelsScreen />)
      await user.click(await screen.findByRole('button', { name: 'Download' }))
      await user.click(screen.getByRole('button', { name: 'Start download' }))
      current = { ...current, status: 'failed', error: 'connection reset' }
      expect(
        await panel().findByText('connection reset')
      ).toBeVisible()

      mainSide = [current]
      reload(view)

      render(<ModelsScreen />)
      await screen.findByRole('region', { name: REGION })
      // #315 — the row is on screen after the reload too, so the panel's own name line is
      // gone; the failed banner sentence still names the model inside a longer sentence, which
      // is fine, and the row carries the bare name.
      expect(panel().queryByText(entry.displayName)).toBeNull()
      expect(cardFor(entry.displayName)).toBeVisible()
      expect(panel().getByText('connection reset')).toBeVisible()
      expect(
        panel().getByText(t('en', 'models.download.failed', { name: entry.displayName }))
      ).toBeVisible()
      expect(panel().getByRole('button', { name: RETRY })).toBeEnabled()
      expect(panel().getByRole('button', { name: DISMISS })).toBeEnabled()
    })

    it('never resurrects a result the user dismissed before the reload', async () => {
      const user = userEvent.setup()
      const entry = variant('reload-dismissed', 'Reload dismissed Q4')
      let current = jobOf('reload-dismissed-job', entry.id)
      let mainSide: DownloadJob[] = []
      const api = stubLive({
        models: () => [entry],
        job: () => current,
        listDownloadJobs: async () => mainSide
      })

      const view = render(<ModelsScreen />)
      await user.click(await screen.findByRole('button', { name: 'Download' }))
      await user.click(screen.getByRole('button', { name: 'Start download' }))
      current = { ...current, status: 'failed', error: 'dismissed for good' }
      mainSide = [current]
      await user.click(await panel().findByRole('button', { name: DISMISS }))
      // Dismiss told the MAIN process too — which is why its list comes back empty.
      expect(api.dismissDownloadJob).toHaveBeenCalledWith(current.jobId)
      mainSide = []

      reload(view)
      render(<ModelsScreen />)
      await screen.findByText(entry.displayName)
      expect(screen.queryByRole('region', { name: REGION })).not.toBeInTheDocument()
    })

    it.each(['verified' as const, 'cancelled' as const])(
      'shows no panel after the reload when the download ended %s',
      async (how) => {
        const user = userEvent.setup()
        const entry = variant(`reload-${how}`, 'Reload settled Q4')
        let current = jobOf(`reload-settled-${how}-job`, entry.id)
        // A verified `done` and a `cancelled` job are exactly what `downloads:list` withholds.
        stubLive({ models: () => [entry], job: () => current, listDownloadJobs: async () => [] })

        const view = render(<ModelsScreen />)
        await user.click(await screen.findByRole('button', { name: 'Download' }))
        await user.click(screen.getByRole('button', { name: 'Start download' }))
        current =
          how === 'verified'
            ? { ...current, status: 'done', receivedBytes: 1000 }
            : { ...current, status: 'cancelled' }
        await waitFor(
          () => expect(screen.queryByRole('region', { name: REGION })).not.toBeInTheDocument()
        )

        reload(view)
        render(<ModelsScreen />)
        await screen.findByText(entry.displayName)
        expect(screen.queryByRole('region', { name: REGION })).not.toBeInTheDocument()
      }
    )

    it('disables Retry and says the model is already here when the refresh reports it installed', async () => {
      const user = userEvent.setup()
      let entry = variant('retry-installed', 'Retry installed Q4')
      let current = jobOf('retry-installed-job', entry.id)
      stubLive({ models: () => [entry], job: () => current })

      render(<ModelsScreen />)
      await user.click(await screen.findByRole('button', { name: 'Download' }))
      await user.click(screen.getByRole('button', { name: 'Start download' }))
      // The weight is on the drive after all (a repair, a copy, a parallel install) while the job
      // itself still ended badly: re-downloading gigabytes would be pointless, not just risky.
      entry = { ...entry, state: 'installed' }
      current = { ...current, status: 'failed', error: 'verification failed' }

      const retry = await panel().findByRole('button', { name: RETRY })
      expect(retry).toBeDisabled()
      expect(retry).toHaveAttribute('title', t('en', 'models.download.retryInstalled'))
      expect(panel().getByText(t('en', 'models.download.retryInstalled'))).toBeVisible()
    })
  })
})

describe('ModelsScreen — repair visibility and group face (PR #302 F3/F5, C1)', () => {
  const OBTAINABLE = {
    url: 'https://example.test/weights.gguf',
    sizeBytes: 1000,
    licenseUrl: 'https://example.test/license',
    licenseApproved: true
  }
  const WITHDRAWN = { ...OBTAINABLE, withdrawn: 'the publisher removed the pinned file' }

  function variant(id: string, displayName: string, over: Partial<ModelInfo> = {}): ModelInfo {
    return model({ id, displayName, family: 'qwen3.8', download: OBTAINABLE, ...over })
  }

  /** Every bridge method the screen calls, so `assertNoUnexpectedApiCalls` has teeth. */
  function stubLibrary(opts: {
    models: () => ModelInfo[]
    activeModelId?: string | null
    machineRamGb?: number
    useModel?: Mock
  }): { listModels: Mock } {
    const listModels = vi.fn(async () => opts.models())
    stubModelsApi({
      listModels,
      getSettings: vi.fn(async () => ({
        ...DEFAULT_SETTINGS,
        activeModelId: opts.activeModelId ?? null
      })),
      getAppStatus: vi.fn(async () => appStatus({ machineRamGb: opts.machineRamGb ?? 32 })),
      ...(opts.useModel ? { useModel: opts.useModel } : {})
    })
    return { listModels }
  }

  function cardFor(displayName: string): HTMLElement {
    const card = screen
      .getAllByText(displayName)
      .map((el) => el.closest('.model-card'))
      .find((el): el is HTMLElement => el != null)
    expect(card, `a .model-card for ${displayName}`).toBeTruthy()
    return card as HTMLElement
  }

  /** Titles of the cards rendered inside one variant group, in DOM order. */
  function groupTitles(name: string): string[] {
    const region = screen.getByRole('region', { name })
    return [...region.querySelectorAll('.model-title')].map((el) => el.textContent ?? '')
  }

  afterEach(() => {
    cleanup()
    assertNoUnexpectedApiCalls()
  })

  // ---- Ported audit probes (`model-library.probe.tsx`, F3) --------------------------------------

  it.each(['different model', 'sibling variant'] as const)(
    'shows a damaged %s in the default drive view so it can be repaired',
    async (kind) => {
      const active = variant('active', 'Active model', { state: 'running' })
      const healthy = variant('healthy', 'Repair control Q4_K_M', { state: 'installed' })
      const damaged = variant(
        'damaged',
        kind === 'sibling variant' ? 'Repair control Q6_K' : 'Damaged model',
        { state: 'checksum_failed' }
      )
      stubLibrary({ models: () => [active, healthy, damaged], activeModelId: active.id })
      render(<ModelsScreen />)
      await screen.findByText(active.displayName)

      // The default view is On this drive; the damaged model is ON the drive (its files are
      // there, they just failed verification) and its whole recovery action lives on this row.
      expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute(
        'aria-checked',
        'true'
      )
      // The sibling case must NOT need "Show all variants" first: a group holding a damaged
      // member starts expanded (C1).
      expect(screen.getByText(damaged.displayName)).toBeVisible()
      expect(
        within(cardFor(damaged.displayName)).getByRole('button', { name: 'Download' })
      ).toBeEnabled()
      expect(within(cardFor(damaged.displayName)).getByText('Can’t verify')).toBeVisible()
    }
  )

  it('finds the damaged model by its exact name while On this drive is selected', async () => {
    const healthy = variant('healthy', 'Healthy model', { state: 'installed' })
    const damaged = variant('damaged', 'Damaged model Q6_K', { state: 'checksum_failed' })
    stubLibrary({ models: () => [healthy, damaged] })
    render(<ModelsScreen />)
    await screen.findByText(healthy.displayName)
    expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute(
      'aria-checked',
      'true'
    )

    // On the reviewed head this reported "No models match" — the search ran over a list the view
    // filter had already emptied of repair states.
    await userEvent.setup().type(screen.getByRole('searchbox'), damaged.displayName)
    expect(screen.getByText(damaged.displayName)).toBeVisible()
    expect(screen.queryByText(/No models match/)).not.toBeInTheDocument()
  })

  it.each(['embeddings', 'reranker', 'translation', 'vision', 'transcriber'] as const)(
    'lists a damaged %s model in the default view with its Download action',
    async (role) => {
      const chat = variant('chat-installed', 'Chat model', { state: 'installed' })
      const damaged = variant(`damaged-${role}`, `Damaged ${role} model`, {
        role,
        family: role,
        state: 'checksum_failed'
      })
      stubLibrary({ models: () => [chat, damaged] })
      render(<ModelsScreen onNavigate={vi.fn()} />)
      await screen.findByText(damaged.displayName)

      expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute(
        'aria-checked',
        'true'
      )
      const card = within(cardFor(damaged.displayName))
      expect(card.getByRole('button', { name: 'Download' })).toBeEnabled()
      // Automatic roles never gain Select/Start from being visible here.
      expect(card.queryByRole('button', { name: 'Use this model' })).not.toBeInTheDocument()
      // #539: a damaged vision model cannot run, so nothing points to Images from it.
      expect(card.queryByRole('button', { name: 'Go to Images' })).not.toBeInTheDocument()
    }
  )

  it('keeps the withdrawn explanation — never a promised Download — on a damaged withdrawn row', async () => {
    const healthy = variant('healthy', 'Healthy model', { state: 'installed' })
    const damaged = variant('damaged-withdrawn', 'Withdrawn damaged model', {
      state: 'checksum_failed',
      download: WITHDRAWN
    })
    stubLibrary({ models: () => [healthy, damaged] })
    render(<ModelsScreen />)
    await screen.findByText(damaged.displayName)

    const card = within(cardFor(damaged.displayName))
    expect(card.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument()
    expect(
      card.getByText(t('en', 'models.download.withdrawn', { reason: WITHDRAWN.withdrawn }))
    ).toBeVisible()
  })

  // #932 (G-2 (d), A S-A9): a model with no checksum on record (`noChecksum`, decided main-side from the manifest) is
  // not a damaged file. Its card says "No checksum" and what the model needs, and offers no Download even with a
  // download block: a download cannot give the manifest a checksum, and main refuses it. A damaged file keeps both.
  it('a no-checksum card names what it needs and offers no Download; a damaged card keeps "Can’t verify" and Download (#932)', async () => {
    const healthy = variant('healthy', 'Healthy model', { state: 'installed' })
    const placeholder = variant('placeholder', 'Placeholder model', {
      family: 'gemma4',
      state: 'checksum_failed',
      noChecksum: true
    })
    const damaged = variant('damaged', 'Damaged model', { family: 'llama3', state: 'checksum_failed' })
    stubLibrary({ models: () => [healthy, placeholder, damaged] })
    render(<ModelsScreen />)
    await screen.findByText(placeholder.displayName)

    const card = within(cardFor(placeholder.displayName))
    expect(card.getByText(t('en', 'models.state.noChecksum'))).toBeVisible()
    expect(card.getByText(t('en', 'models.noChecksum.hint'))).toBeVisible()
    expect(card.queryByText(t('en', 'models.state.checksumFailed'))).not.toBeInTheDocument()
    expect(card.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument()
    const control = within(cardFor(damaged.displayName))
    expect(control.getByText(t('en', 'models.state.checksumFailed'))).toBeVisible()
    expect(control.queryByText(t('en', 'models.noChecksum.hint'))).not.toBeInTheDocument()
    expect(control.getByRole('button', { name: 'Download' })).toBeEnabled()
  })

  it('a damaged-only drive still starts in Browse, and On this drive lists the damaged row', async () => {
    const damaged = variant('damaged-only', 'Only damaged model', { state: 'checksum_failed' })
    stubLibrary({ models: () => [damaged] })
    render(<ModelsScreen />)
    await screen.findByText(damaged.displayName)

    // The INITIAL view choice is unchanged: it asks whether anything is usable right now
    // (`isModelInstalled`), and a model that fails its checksum is not.
    expect(screen.getByRole('radio', { name: 'Browse models' })).toHaveAttribute(
      'aria-checked',
      'true'
    )
    await userEvent.setup().click(screen.getByRole('radio', { name: 'On this drive' }))
    expect(screen.getByText(damaged.displayName)).toBeVisible()
    expect(screen.queryByText(t('en', 'models.library.noneInstalled'))).not.toBeInTheDocument()
  })

  it('still shows the "only your active model" empty state when nothing else is on the drive', async () => {
    const active = variant('active', 'Active model', { state: 'installed' })
    stubLibrary({ models: () => [active], activeModelId: active.id })
    render(<ModelsScreen />)
    await screen.findByText(active.displayName)

    expect(screen.getByRole('radio', { name: 'On this drive' })).toHaveAttribute(
      'aria-checked',
      'true'
    )
    expect(screen.getByText(t('en', 'models.library.onlyActive'))).toBeVisible()
  })

  it('keeps the active model pinned above the library, listed exactly once', async () => {
    const active = variant('active', 'Active model', { state: 'running' })
    const damaged = variant('damaged', 'Damaged model', { state: 'checksum_failed' })
    stubLibrary({ models: () => [active, damaged], activeModelId: active.id })
    render(<ModelsScreen />)
    await screen.findByText(active.displayName)

    expect([...document.querySelectorAll('.model-title')].map((el) => el.textContent)).toEqual([
      'Active model',
      'Damaged model'
    ])
    expect(screen.getAllByText('Active model')).toHaveLength(1)
  })

  // ---- Default expansion vs. the user's explicit toggle (C1) ------------------------------------

  it('expands the group on its own when a refresh introduces damage', async () => {
    const healthy = variant('pair-q4', 'Refresh pair Q4_K_M', { state: 'installed' })
    const sibling = variant('pair-q6', 'Refresh pair Q6_K', { state: 'installed' })
    let damagedYet = false
    const useModel = vi.fn(async () => STOPPED_RUNTIME)
    stubLibrary({
      models: () =>
        damagedYet ? [healthy, { ...sibling, state: 'checksum_failed' as const }] : [healthy, sibling],
      useModel
    })
    render(<ModelsScreen />)
    await screen.findByText(healthy.displayName)

    // Healthy pair: collapsed, so only the face shows.
    expect(screen.getByRole('button', { name: 'Show all variants (2)' })).toHaveAttribute(
      'aria-expanded',
      'false'
    )
    expect(screen.queryByText(sibling.displayName)).not.toBeInTheDocument()

    // Any refresh (here: the row's own Use action) re-derives expansion from the new states.
    damagedYet = true
    await userEvent.setup().click(
      within(cardFor(healthy.displayName)).getByRole('button', { name: 'Use this model' })
    )
    await waitFor(() => expect(screen.getByText(sibling.displayName)).toBeVisible())
    expect(screen.getByRole('button', { name: 'Show fewer variants (2)' })).toHaveAttribute(
      'aria-expanded',
      'true'
    )
    expect(useModel).toHaveBeenCalledExactlyOnceWith(healthy.id)
  })

  it('an explicit collapse survives a refresh and a filter change — and re-expansion works', async () => {
    const user = userEvent.setup()
    const healthy = variant('toggle-q4', 'Toggle pair Q4_K_M', { state: 'installed' })
    const damaged = variant('toggle-q6', 'Toggle pair Q6_K', { state: 'checksum_failed' })
    const useModel = vi.fn(async () => STOPPED_RUNTIME)
    const api = stubLibrary({ models: () => [healthy, damaged], useModel })
    render(<ModelsScreen />)
    await screen.findByText(damaged.displayName)

    // Starts expanded because of the damaged member; the user disagrees.
    await user.click(screen.getByRole('button', { name: 'Show fewer variants (2)' }))
    expect(screen.queryByText(damaged.displayName)).not.toBeInTheDocument()

    // A refresh must not re-open what the user closed, even though the damage is still there.
    await user.click(
      within(cardFor(healthy.displayName)).getByRole('button', { name: 'Use this model' })
    )
    await waitFor(() => expect(api.listModels).toHaveBeenCalledTimes(2))
    expect(screen.queryByText(damaged.displayName)).not.toBeInTheDocument()

    // Nor a filter change: the choice is keyed by the stable group key.
    await user.type(screen.getByRole('searchbox'), 'toggle')
    expect(screen.queryByText(damaged.displayName)).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Show all variants (2)' })).toHaveAttribute(
      'aria-expanded',
      'false'
    )

    // And re-expanding still works.
    await user.click(screen.getByRole('button', { name: 'Show all variants (2)' }))
    expect(screen.getByText(damaged.displayName)).toBeVisible()
  })

  // ---- The rendered group face (F5) ------------------------------------------------------------

  it('renders the variantGroupFace choice on the collapsed card, and every variant once when expanded', async () => {
    const tie = { state: 'missing' as const, recommended: false, insufficientRam: true }
    const models = [
      variant('tie-q4km', 'Tie group Q4_K_M', { ...tie, download: WITHDRAWN }),
      variant('tie-udq4kxl', 'Tie group UD-Q4_K_XL', { ...tie, download: OBTAINABLE }),
      variant('tie-q4ks', 'Tie group Q4_K_S', { ...tie, download: WITHDRAWN }),
      variant('tie-q6k', 'Tie group Q6_K', { ...tie, download: OBTAINABLE }),
      variant('tie-q80', 'Tie group Q8_0', { ...tie, download: OBTAINABLE }),
      variant('tie-udq6kxl', 'Tie group UD-Q6_K_XL', { ...tie, download: OBTAINABLE })
    ]
    stubLibrary({ models: () => models })
    render(<ModelsScreen />)
    await screen.findByRole('region', { name: 'Tie group' })

    // The selector's answer, computed independently from the same inputs the screen receives.
    const group = groupModelVariants(orderPickerModels(models)).find((g) => g.name === 'Tie group')
    const face = variantGroupFace(group!)
    expect(face.displayName).toBe('Tie group UD-Q4_K_XL')

    // Collapsed: the DOM shows exactly that member — not the withdrawn catalog-first one.
    expect(groupTitles('Tie group')).toEqual([face.displayName])
    expect(screen.queryByText('Tie group Q4_K_M')).not.toBeInTheDocument()
    expect(group!.models[0].displayName).toBe('Tie group Q4_K_M') // the sort is untouched

    // Expanded: face first, then every other variant exactly once in its original order.
    await userEvent.setup().click(screen.getByRole('button', { name: 'Show all variants (6)' }))
    expect(groupTitles('Tie group')).toEqual([
      'Tie group UD-Q4_K_XL',
      'Tie group Q4_K_M',
      'Tie group Q4_K_S',
      'Tie group Q6_K',
      'Tie group Q8_0',
      'Tie group UD-Q6_K_XL'
    ])
    expect(new Set(groupTitles('Tie group')).size).toBe(models.length)
  })

  // ---- O1 / O5 — the RAM badge and the heading outline ------------------------------------------

  it('shows the ⚠ RAM badge and its full hint while Technical details is closed (O1)', async () => {
    const tight = variant('ram-gated', 'RAM gated model', {
      state: 'installed',
      insufficientRam: true,
      recommendedMinRamGb: 24
    })
    stubLibrary({ models: () => [tight], machineRamGb: 8 })
    render(<ModelsScreen />)
    await screen.findByText(tight.displayName)

    expect((document.querySelector('details.tech-details') as HTMLDetailsElement).open).toBe(false)
    // The BADGE itself (the disabled Use action carries the same hint as its title).
    const badge = within(cardFor(tight.displayName)).getByText('Needs ≥24 GB RAM')
    expect(badge).toBeVisible()
    expect(badge.className).toContain('pill-warning')
    expect(badge).toHaveAttribute(
      'title',
      t('en', 'models.ram.needs', { min: 24 }) +
        t('en', 'models.ram.machine', { ram: 8 }) +
        t('en', 'models.ram.advice')
    )
  })

  it('nests the heading outline h2 → h3 (task) → h4 (group) and toggles aria-expanded (O5)', async () => {
    const models = [
      variant('outline-q4', 'Outline group Q4_K_M'),
      variant('outline-q6', 'Outline group Q6_K')
    ]
    stubLibrary({ models: () => models })
    render(<ModelsScreen />)
    await screen.findByRole('region', { name: 'Outline group' })

    expect(screen.getByRole('heading', { level: 2, name: 'Model library' })).toBeInTheDocument()
    expect(screen.getByRole('heading', { level: 3, name: 'Chat' })).toBeInTheDocument()
    const groupHeading = screen.getByRole('heading', { level: 4, name: 'Outline group' })
    expect(groupHeading).toBeInTheDocument()
    // No heading skips a level and the group heading is not a sibling-rank h3 any more.
    expect(screen.queryByRole('heading', { level: 3, name: 'Outline group' })).not.toBeInTheDocument()

    const toggle = screen.getByRole('button', { name: 'Show all variants (2)' })
    expect(toggle).toHaveAttribute('aria-expanded', 'false')
    await userEvent.setup().click(toggle)
    expect(screen.getByRole('button', { name: 'Show fewer variants (2)' })).toHaveAttribute(
      'aria-expanded',
      'true'
    )
  })
})

// #339 P8-2 (the owner's ruling, 2026-09-06): the Models screen's quiet "knowledge-pack tools"
// row — the same consent dialog the Knowledge-packs panel notice opens — and the existing
// engine-install action's own argument-less `downloadEngine()` call, unchanged by this feature.
describe('ModelsScreen — knowledge-pack tools row (#339 P8-2)', () => {
  function engineOptionalFamily(over: Partial<EngineOptionalFamily> = {}): EngineOptionalFamily {
    return {
      family: 'kiwix_tools',
      version: '3.8.1',
      sizeBytes: 18301924,
      url: 'https://download.kiwix.org/release/kiwix-tools/kiwix-tools_win-i686-3.8.1.zip',
      license: 'GPL-3.0-or-later',
      installed: false,
      ...over
    }
  }

  function engineWithMissingTools(over: Partial<EngineStatus> = {}): EngineStatus {
    return {
      installed: true,
      available: true,
      version: '1.0.0',
      backend: 'cpu',
      missingFamilies: [],
      missingOptionalFamilies: ['kiwix_tools'],
      optionalFamilies: [engineOptionalFamily()],
      ...over
    }
  }

  it('missingOptionalFamilies names kiwix_tools → the quiet row and Install… render and open the consent dialog', async () => {
    const user = userEvent.setup()
    stubModelsApi({
      getEngineStatus: vi.fn(async () => engineWithMissingTools())
    })
    render(<ModelsScreen />)
    expect(await screen.findByText('Knowledge-pack tools: not installed')).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'Install…' }))
    expect(await screen.findByText('Install the knowledge-pack tools?')).toBeInTheDocument()
  })

  it('an installed family (missingOptionalFamilies empty) shows no row', async () => {
    stubModelsApi({
      getEngineStatus: vi.fn(async () =>
        engineWithMissingTools({
          missingOptionalFamilies: [],
          optionalFamilies: [engineOptionalFamily({ installed: true })]
        })
      )
    })
    render(<ModelsScreen />)
    expect(await screen.findByRole('heading', { name: 'AI Model' })).toBeInTheDocument()
    // Give the (idle) hook effect a tick to have run, then assert the row never appears.
    await new Promise((resolve) => setTimeout(resolve, 20))
    expect(screen.queryByText('Knowledge-pack tools: not installed')).not.toBeInTheDocument()
  })

  // An `optionalFamilies`-less / `missingOptionalFamilies`-less EngineStatus (an older main) must
  // render exactly like "absent" — never a crash, never a phantom row.
  it('an EngineStatus with neither field (an older main) shows no row', async () => {
    stubModelsApi({
      getEngineStatus: vi.fn(async () => ({
        installed: true,
        available: true,
        version: '1.0.0',
        backend: 'cpu',
        missingFamilies: []
      }))
    })
    render(<ModelsScreen />)
    expect(await screen.findByRole('heading', { name: 'AI Model' })).toBeInTheDocument()
    expect(screen.queryByText('Knowledge-pack tools: not installed')).not.toBeInTheDocument()
  })

  // SH-1-style regression guard for #339 P8-2: the pre-existing "Install AI engine" banner
  // action must keep calling the argument-less default install — only the NEW consent dialog
  // is allowed to pass `{ families: ['kiwix_tools'] }`.
  it('the existing "Install AI engine" action still calls downloadEngine with NO arguments', async () => {
    const user = userEvent.setup()
    const downloadEngine = vi.fn(async () => ({
      jobId: 'e1',
      status: 'cancelled' as const,
      receivedBytes: 0,
      totalBytes: null,
      unverified: false,
      binaryPath: null,
      error: null
    }))
    stubModelsApi({
      getEngineStatus: vi.fn(
        async (): Promise<EngineStatus> => ({
          installed: false,
          available: true,
          version: null,
          backend: null,
          missingFamilies: ['llama_cpp']
        })
      ),
      downloadEngine,
      getEnginePlan: vi.fn(async () => enginePreview())
    })
    render(<ModelsScreen />)
    await user.click(await screen.findByRole('button', { name: 'Install AI engine' }))
    // #843: the action asks first; Confirm sends the same argument-less request.
    const dialog = await screen.findByRole('dialog')
    await user.click(within(dialog).getByRole('button', { name: 'Install AI engine' }))
    expect(downloadEngine).toHaveBeenCalledTimes(1)
    expect(downloadEngine).toHaveBeenCalledWith()
    expect(downloadEngine.mock.calls[0]).toHaveLength(0)
  })
})

// #382 — lazy verification on the Models screen. A fresh workspace on a slow drive used to
// hash EVERY present weight before a single card rendered: 39.44 GB in 25.5 min at a mean
// 25.8 MB/s on the #330 round trip, and this screen is the only route to a first model. The
// screen now verifies lazily on every ordinary visit; the full pass moved to one explicit
// opt-in action, which needs its own in-place progress bar (before #382 the only bar lived
// inside the `!models` branch, which lazy verification skips).
describe('lazy verification + "Check all model files" (#382)', () => {
  /** Stubs the screen's bridge and hands back the listModels spy + the progress emitter. */
  function stubVerify(models: ModelInfo[]): {
    listModels: Mock
    emit: (p: Partial<ModelVerifyProgress>) => void
  } {
    const listModels = vi.fn(async () => models)
    let sink: ((p: ModelVerifyProgress) => void) | null = null
    stubModelsApi({
      listModels,
      getSettings: vi.fn(async () => ({ ...DEFAULT_SETTINGS, activeModelId: models[0]?.id ?? null })),
      onModelVerifyProgress: vi.fn((cb: (p: ModelVerifyProgress) => void) => {
        sink = cb
        return () => {
          sink = null
        }
      }),
    })
    const emit = (p: Partial<ModelVerifyProgress>): void => {
      act(() =>
        sink?.({
          runId: 'run-1',
          modelIndex: 1,
          modelCount: 2,
          modelId: 'big',
          displayName: 'Big weight',
          overallBytesHashed: 4_000_000_000,
          overallBytesTotal: 10_000_000_000,
          done: false,
          ...p
        })
      )
    }
    return { listModels, emit }
  }

  it('the mount refresh asks for LAZY verification and the cards render straight away', async () => {
    const installed = model({ id: 'big', displayName: 'Big weight', state: 'installed' })
    const { listModels } = stubVerify([installed])
    render(<ModelsScreen />)

    expect(await screen.findByText('Big weight')).toBeVisible()
    expect(listModels).toHaveBeenCalledTimes(1)
    expect(listModels).toHaveBeenCalledWith(true)
    assertNoUnexpectedApiCalls()
  })

  it('"Check all model files" runs the FULL pass (the flag omitted), then refreshes lazily', async () => {
    const user = userEvent.setup()
    const installed = model({ id: 'big', displayName: 'Big weight', state: 'installed' })
    const { listModels } = stubVerify([installed])
    render(<ModelsScreen />)
    await screen.findByText('Big weight')

    await user.click(screen.getByRole('button', { name: 'Check all model files' }))

    await waitFor(() => expect(listModels).toHaveBeenCalledTimes(3))
    // The explicit full pass: `lazyVerify` still omitted (undefined), now carrying the #420
    // renderer-minted run id that is also the Cancel handle.
    expect(listModels.mock.calls[1][0]).toBeUndefined()
    expect(listModels.mock.calls[1][1]).toEqual(expect.any(String))
    expect(listModels.mock.calls[2]).toEqual([true]) // run()'s trailing refresh, lazy again
  })

  it('the progress bar renders IN PLACE on the loaded screen while the full pass hashes', async () => {
    const installed = model({ id: 'big', displayName: 'Big weight', state: 'installed' })
    const { emit } = stubVerify([installed])
    render(<ModelsScreen />)
    await screen.findByText('Big weight')

    // Nothing hashing yet: no bar, and the cards are on screen.
    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()

    emit({})
    expect(screen.getByText('Checking model 1 of 2: Big weight — 40%')).toBeVisible()
    expect(screen.getByRole('progressbar')).toBeVisible()
    // The regression this pins: the bar must not replace the screen (pre-#382 its only render
    // site was the `!models` branch, so a full pass here would have shown nothing at all).
    expect(screen.getByText('Big weight')).toBeVisible()

    emit({ done: true })
    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
  })
})
// #420 — the pass the user starts on purpose can now be stopped. Before this it ran to the
// end whatever the user did: ~25 minutes of USB I/O on the #330 slow drive, surviving even
// navigating away. Cancelling is not a failure, so the screen must settle calmly.
describe('cancelling "Check all model files" (#420)', () => {
  /** Like the #382 stub, but the full pass is held open so a Cancel can land mid-pass. */
  function stubCancellable(models: ModelInfo[]): {
    listModels: Mock
    cancelModelVerify: Mock
    /** Let the held-open full pass resolve, as main does after an abort. */
    settleFullPass: () => void
    emit: (p: Partial<ModelVerifyProgress>) => void
    runIdOf: () => string | undefined
  } {
    let releaseFullPass: (() => void) | null = null
    const listModels = vi.fn(async (lazy?: boolean, _verifyRunId?: string) => {
      if (lazy) return models
      await new Promise<void>((resolve) => {
        releaseFullPass = resolve
      })
      return models
    })
    const cancelModelVerify = vi.fn(async () => true)
    let sink: ((p: ModelVerifyProgress) => void) | null = null
    stubModelsApi({
      listModels,
      cancelModelVerify,
      getSettings: vi.fn(async () => ({ ...DEFAULT_SETTINGS, activeModelId: models[0]?.id ?? null })),
      onModelVerifyProgress: vi.fn((cb: (p: ModelVerifyProgress) => void) => {
        sink = cb
        return () => {
          sink = null
        }
      }),
    })
    const runIdOf = (): string | undefined =>
      listModels.mock.calls.find((c) => !c[0])?.[1] as string | undefined
    const emit = (p: Partial<ModelVerifyProgress>): void => {
      act(() =>
        sink?.({
          runId: runIdOf() ?? 'run-1',
          modelIndex: 1,
          modelCount: 2,
          modelId: 'big',
          displayName: 'Big weight',
          overallBytesHashed: 4_000_000_000,
          overallBytesTotal: 10_000_000_000,
          done: false,
          ...p
        })
      )
    }
    return {
      listModels,
      cancelModelVerify,
      settleFullPass: () => act(() => releaseFullPass?.()),
      emit,
      runIdOf
    }
  }

  it('offers Stop checking as soon as the pass starts — before any progress event', async () => {
    const user = userEvent.setup()
    const installed = model({ id: 'big', displayName: 'Big weight', state: 'installed' })
    const { settleFullPass } = stubCancellable([installed])
    render(<ModelsScreen />)
    await screen.findByText('Big weight')
    expect(screen.queryByRole('button', { name: 'Stop checking' })).not.toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: 'Check all model files' }))

    // The regression this pins: `runId` used to be minted in MAIN and only reached the
    // renderer on the FIRST progress event, so a cancel clicked in this window (and on a pass
    // that emits no events at all) had nothing to send.
    expect(await screen.findByRole('button', { name: 'Stop checking' })).toBeVisible()
    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
    settleFullPass()
  })

  it('clicking it cancels the run the pass was started under, and the screen settles calmly', async () => {
    const user = userEvent.setup()
    const installed = model({ id: 'big', displayName: 'Big weight', state: 'installed' })
    const { cancelModelVerify, settleFullPass, emit, runIdOf } = stubCancellable([installed])
    render(<ModelsScreen />)
    await screen.findByText('Big weight')
    await user.click(screen.getByRole('button', { name: 'Check all model files' }))
    await screen.findByRole('button', { name: 'Stop checking' })
    emit({})
    expect(screen.getByRole('progressbar')).toBeVisible()

    await user.click(screen.getByRole('button', { name: 'Stop checking' }))
    expect(cancelModelVerify).toHaveBeenCalledWith(runIdOf())
    // Disabled while the cancel unwinds, so it cannot be fired twice.
    expect(await screen.findByRole('button', { name: 'Stopping…' })).toBeDisabled()

    // Main answers a cancelled pass with a complete list, not an error — so no banner, the
    // bar goes, the action is offered again and the cards are still there.
    settleFullPass()
    await waitFor(() =>
      expect(
        screen.queryByRole('button', { name: /Stop checking|Stopping…/ })
      ).not.toBeInTheDocument()
    )
    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
    // The live region always exists; what matters is that it stays EMPTY — cancelling is
    // not a failure, so no error copy lands in it.
    expect(screen.getByRole('alert')).toBeEmptyDOMElement()
    expect(screen.getByRole('button', { name: 'Check all model files' })).toBeEnabled()
    expect(screen.getByText('Big weight')).toBeVisible()
  })

  it('a pass survives leaving the screen — the revisit shows the bar and can still stop it', async () => {
    const user = userEvent.setup()
    const installed = model({ id: 'big', displayName: 'Big weight', state: 'installed' })
    const { cancelModelVerify, settleFullPass, emit, runIdOf } = stubCancellable([installed])
    const first = render(<ModelsScreen />)
    await screen.findByText('Big weight')
    await user.click(screen.getByRole('button', { name: 'Check all model files' }))
    await screen.findByRole('button', { name: 'Stop checking' })
    emit({})

    // Navigate away and back. The hash keeps running in MAIN either way; before #420 the
    // revisited screen looked idle and the only way to stop it was gone with the component.
    first.unmount()
    render(<ModelsScreen />)
    await screen.findByText('Big weight')
    expect(screen.getByRole('progressbar')).toBeVisible()
    expect(screen.getByText('Checking model 1 of 2: Big weight — 40%')).toBeVisible()
    expect(screen.getByRole('button', { name: 'Checking all model files…' })).toBeDisabled()

    await user.click(screen.getByRole('button', { name: 'Stop checking' }))
    expect(cancelModelVerify).toHaveBeenCalledWith(runIdOf())
    settleFullPass()
  })

  it('a pass that finished while the user was away leaves no stale bar behind', async () => {
    const user = userEvent.setup()
    const installed = model({ id: 'big', displayName: 'Big weight', state: 'installed' })
    const { settleFullPass, emit } = stubCancellable([installed])
    const first = render(<ModelsScreen />)
    await screen.findByText('Big weight')
    await user.click(screen.getByRole('button', { name: 'Check all model files' }))
    await screen.findByRole('button', { name: 'Stop checking' })
    emit({})
    first.unmount()

    // The pass finishes with nobody watching: its `finally` still clears the module memory.
    settleFullPass()
    await act(async () => undefined)

    render(<ModelsScreen />)
    await screen.findByText('Big weight')
    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Stop checking' })).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Check all model files' })).toBeEnabled()
  })
})

// SH-1 (frontend audit 2026-08-09, #144): the engine download (multi-hundred-MB llama.cpp
// fetch) had NO Cancel — cancelEngineDownload was exposed on the bridge with zero callers.
// The live branch of the engine banner now carries a Cancel mirroring the model-download one.
describe('ModelsScreen — engine download Cancel (SH-1, #144)', () => {
  it('offers Cancel while the engine fetch is live and cancelling ends the job', async () => {
    const user = userEvent.setup()
    const live = engineJob()
    const cancelled = engineJob({ status: 'cancelled' })
    const downloadEngine = vi.fn(async () => live)
    const cancelEngineDownload = vi.fn(async () => cancelled)
    stubModelsApi({
      getEngineStatus: vi.fn(async () => ENGINE_MISSING),
      getEngineJob: vi.fn(async () => live),
      downloadEngine,
      cancelEngineDownload,
      getEnginePlan: vi.fn(async () => enginePreview())
    })
    render(<ModelsScreen />)

    // The demo-mode warning offers the install; confirming it (#843) shows progress + Cancel.
    await user.click(await screen.findByRole('button', { name: 'Install AI engine' }))
    await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Install AI engine' }))
    // Pre-fix TEETH: the live branch rendered ONLY the Progress — no Cancel existed anywhere.
    const cancelBtn = await screen.findByRole('button', { name: 'Cancel download' })
    await user.click(cancelBtn)
    expect(cancelEngineDownload).toHaveBeenCalledWith('e1')

    // The cancelled job leaves the live branch: the install affordance returns.
    expect(await screen.findByRole('button', { name: 'Install AI engine' })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Cancel download' })).not.toBeInTheDocument()
  })
})