Skip to content

AI, fully local on your computer.

38.1 KB
Raw Blame
// @vitest-environment jsdom
import { describe, it, expect, vi, afterEach, beforeEach, type Mock } from 'vitest'
import { act, render, screen, cleanup, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { EngineProblemNotice, ToastProvider } from '../../src/renderer/components'
import { HomeScreen } from '../../src/renderer/screens/HomeScreen'
import { ModelsScreen, __resetModelsScreenMemoryForTests } from '../../src/renderer/screens/ModelsScreen'
import { PerformanceScreen } from '../../src/renderer/screens/PerformanceScreen'
import { SettingsScreen } from '../../src/renderer/screens/SettingsScreen'
import { AnswerThread, type ImageTurn } from '../../src/renderer/images'
import { App } from '../../src/renderer/App'
import { t } from '../../src/shared/i18n'
import {
  DEFAULT_SETTINGS,
  type AppStatus,
  type EngineDownloadJob,
  type EngineProblem,
  type EngineRecheckResult,
  type EngineStatus,
  type ModelInfo,
  type PerformanceSnapshot,
  type RuntimeStatus
} from '../../src/shared/types'
import type { Translator } from '../../src/renderer/components/translator'
import { appShellStubs } from '../helpers/app-shell'
import { deferred } from '../helpers/deferred'
import { stubHomeApi } from '../helpers/home-screen'
import { ENGINE_INSTALLED, engineJob, enginePreview, modelsScreenStubs, stubModelsApi } from '../helpers/model-fixtures'
import { laptopResult } from '../helpers/performance-screen'
import { stubApi, assertNoUnexpectedApiCalls } from '../helpers/renderer'
import { diagnosticsEngineStubs } from '../helpers/settings-diagnostics'
import { hangBudgetMs } from '../helpers/hang-budget'
import { STOPPED_RUNTIME, appStatus, driveStatus, makePolicyStatus, performanceSnapshot } from '../helpers/status'

// #530: an engine program that is on the drive but that the OS loader refuses to start (Linux:
// libgomp.so.1 missing; Windows: Visual C++ runtime / Smart App Control) is recorded as a session
// verdict (`EngineProblem`). These tests pin what each surface SAYS about it: the AI Model banner
// and its Check again flow, the voice hint, Home's model row + primary, the App notice button,
// Diagnostics (line + copy report), Performance's graphics tile and the Images error-code copy.
// Copy is asserted against the catalog (`t('en', key)`), not hard-coded English.

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

const en = (key: Parameters<typeof t>[1], params?: Record<string, string | number>): string =>
  t('en', key, params)

const LIBGOMP: EngineProblem = {
  family: 'llama_cpp',
  reason: 'library-missing',
  os: 'linux',
  name: 'libgomp.so.1',
  exit: 'exit code 127'
}
const WHISPER: EngineProblem = { ...LIBGOMP, family: 'whisper_cpp' }

// ---- 1-4: the notice component ---------------------------------------------------------------

function renderNotice(
  problem: EngineProblem,
  opts: {
    variant?: 'banner' | 'hint'
    onRecheck?: () => Promise<EngineRecheckResult>
    t?: Translator
  } = {}
): ReturnType<typeof render> {
  return render(
    <ToastProvider>
      <EngineProblemNotice
        problem={problem}
        variant={opts.variant ?? 'banner'}
        onRecheck={opts.onRecheck ?? (async () => ({ problems: [problem] }))}
        t={opts.t}
      />
    </ToastProvider>
  )
}

describe('EngineProblemNotice — banner reason copy (#530)', () => {
  it('libgomp.so.1 on Linux names the library and BOTH packages, and the demo-mode note', () => {
    renderNotice(LIBGOMP)
    expect(screen.getByText(en('models.engineProblem.title'))).toBeInTheDocument()
    expect(
      screen.getByText(
        en('models.engineProblem.libraryMissingPackage', {
          library: 'libgomp.so.1',
          debPackage: 'libgomp1',
          rpmPackage: 'libgomp'
        })
      )
    ).toBeInTheDocument()
    expect(screen.getByText(en('models.engineProblem.demoNote'))).toBeInTheDocument()
    // The banner is a polite status region (design-guidelines §6), not an alert.
    // (the toast host is a status region too, so find the banner by class)
    const banner = document.querySelector('.banner') as HTMLElement
    expect(banner).toHaveAttribute('role', 'status')
    expect(within(banner).getByText(en('models.engineProblem.title'))).toBeInTheDocument()
    // §7: the exit code never reaches the everyday surface.
    expect(document.body.textContent).not.toContain('127')
  })

  const CASES: Array<[string, EngineProblem, Parameters<typeof t>[1], Record<string, string>?]> = [
    ['library-missing with an unknown library (the generic sentence, no package)', { ...LIBGOMP, name: 'libfoo.so.2' }, 'models.engineProblem.libraryMissing', { library: 'libfoo.so.2' }],
    ['library-missing on win (never a Linux package hint)', { ...LIBGOMP, os: 'win' }, 'models.engineProblem.libraryMissing', { library: 'libgomp.so.1' }],
    ['system-too-old on linux', { ...LIBGOMP, reason: 'system-too-old', os: 'linux' }, 'models.engineProblem.systemTooOldLinux'],
    ['system-too-old on mac', { ...LIBGOMP, reason: 'system-too-old', os: 'mac' }, 'models.engineProblem.systemTooOldMac'],
    ['system-too-old on win', { ...LIBGOMP, reason: 'system-too-old', os: 'win' }, 'models.engineProblem.systemTooOld'],
    ['vc-runtime-missing', { ...LIBGOMP, reason: 'vc-runtime-missing', os: 'win' }, 'models.engineProblem.vcRuntimeMissing'],
    ['files-damaged', { ...LIBGOMP, reason: 'files-damaged' }, 'models.engineProblem.filesDamaged'],
    // #532: a fresh, verified copy that still does not load — the files are not the likely cause.
    ['files-damaged after a fresh install', { ...LIBGOMP, reason: 'files-damaged', afterInstall: true }, 'models.engineProblem.filesDamagedAfterInstall'],
    ['files-damaged after a fresh install on win', { ...LIBGOMP, reason: 'files-damaged', os: 'win', afterInstall: true }, 'models.engineProblem.filesDamagedAfterInstallWin'],
    ['blocked', { ...LIBGOMP, reason: 'blocked', os: 'win' }, 'models.engineProblem.blocked']
  ]
  it.each(CASES)('%s shows its own sentence', (_label, problem, key, params) => {
    renderNotice(problem)
    expect(screen.getByText(en(key, params))).toBeInTheDocument()
  })
})

describe('EngineProblemNotice — Check again (#530)', () => {
  it('is disabled and reads "Checking…" while the re-check is pending', async () => {
    const user = userEvent.setup()
    const d = deferred<EngineRecheckResult>()
    const onRecheck = vi.fn(() => d.promise)
    renderNotice(LIBGOMP, { onRecheck })
    await user.click(screen.getByRole('button', { name: en('models.engineProblem.check') }))
    const busy = await screen.findByRole('button', { name: new RegExp(en('models.engineProblem.checking')) })
    expect(busy).toBeDisabled()
    expect(onRecheck).toHaveBeenCalledTimes(1)
    await act(async () => d.resolve({ problems: [LIBGOMP] }))
    expect(await screen.findByRole('button', { name: en('models.engineProblem.check') })).toBeEnabled()
  })

  it('the same family still failing shows the "still can\'t start" line', async () => {
    const user = userEvent.setup()
    renderNotice(LIBGOMP, { onRecheck: async () => ({ problems: [LIBGOMP] }) })
    await user.click(screen.getByRole('button', { name: en('models.engineProblem.check') }))
    expect(await screen.findByText(en('models.engineProblem.stillFailing'))).toBeInTheDocument()
  })

  it('another family failing does not count as "still failing" for this one', async () => {
    const user = userEvent.setup()
    renderNotice(LIBGOMP, { onRecheck: async () => ({ problems: [WHISPER] }) })
    await user.click(screen.getByRole('button', { name: en('models.engineProblem.check') }))
    expect(await screen.findByText(en('models.engineProblem.fixed'))).toBeInTheDocument()
    expect(screen.queryByText(en('models.engineProblem.stillFailing'))).not.toBeInTheDocument()
  })

  it('a healed voice engine toasts the voice wording', async () => {
    const user = userEvent.setup()
    renderNotice(WHISPER, { variant: 'hint', onRecheck: async () => ({ problems: [] }) })
    await user.click(screen.getByRole('button', { name: en('models.engineProblem.check') }))
    expect(await screen.findByText(en('models.engineProblem.voiceFixed'))).toBeInTheDocument()
  })

  it('a rejection shows the rejection message as-is and re-enables the button', async () => {
    const user = userEvent.setup()
    renderNotice(LIBGOMP, {
      onRecheck: async () => {
        throw new Error('Could not check right now.')
      }
    })
    await user.click(screen.getByRole('button', { name: en('models.engineProblem.check') }))
    expect(await screen.findByText('Could not check right now.')).toBeInTheDocument()
    expect(screen.getByRole('button', { name: en('models.engineProblem.check') })).toBeEnabled()
  })
})

describe('EngineProblemNotice — hint variant (#530)', () => {
  it('shows the voice title + reason in a .hint paragraph', () => {
    renderNotice(WHISPER, { variant: 'hint' })
    const reason = en('models.engineProblem.libraryMissingPackage', {
      library: 'libgomp.so.1',
      debPackage: 'libgomp1',
      rpmPackage: 'libgomp'
    })
    const line = screen.getByText(`${en('models.engineProblem.voiceTitle')} ${reason}`)
    expect(line.tagName).toBe('P')
    expect(line).toHaveClass('hint')
    // The hint is quiet: no banner, no demo-mode note (chat is unaffected).
    expect(document.querySelector('.banner')).toBeNull()
    expect(screen.queryByText(en('models.engineProblem.demoNote'))).not.toBeInTheDocument()
  })

  it('the outcome status region is mounted from the start, empty — an a11y rule (M-U1)', async () => {
    const user = userEvent.setup()
    renderNotice(WHISPER, { variant: 'hint', onRecheck: async () => ({ problems: [WHISPER] }) })
    // Present and EMPTY before any check: a status region inserted already holding text is missed.
    const statusIn = (): HTMLElement => document.querySelector('.engine-problem-hint [role=status]') as HTMLElement
    const status = statusIn()
    expect(status).toBeInTheDocument()
    expect(status).toHaveTextContent('')
    await user.click(screen.getByRole('button', { name: en('models.engineProblem.check') }))
    await waitFor(() => expect(status).toHaveTextContent(en('models.engineProblem.stillFailing')))
    // Same node all along (updated in place, not re-inserted).
    expect(statusIn()).toBe(status)
  })
})

describe('EngineProblemNotice — German (#530)', () => {
  const de: Translator = (k, p) => t('de', k, p)

  it('renders the German reason and button', () => {
    renderNotice(LIBGOMP, { t: de })
    expect(screen.getByText(t('de', 'models.engineProblem.title'))).toBeInTheDocument()
    const reason = screen.getByText(/Eine Systembibliothek, die sie braucht, fehlt: libgomp\.so\.1\./)
    expect(reason).toHaveTextContent('„Erneut prüfen“')
    expect(reason).toHaveTextContent('libgomp1')
    expect(screen.getByRole('button', { name: 'Erneut prüfen' })).toBeInTheDocument()
  })
})

// ---- 5: ModelsScreen -------------------------------------------------------------------------

/** #532: the speech model on the drive — the card the voice engine's hint sits on. */
const SPEECH_MODEL: ModelInfo = {
  id: 'whisper-small',
  displayName: 'Whisper Small',
  family: 'whisper',
  role: 'transcriber',
  format: 'ggml',
  runtime: 'whisper_cpp',
  license: 'mit',
  sizeOnDiskGb: 0.5,
  recommendedMinRamGb: 2,
  recommendedRamGb: 4,
  recommendedContextTokens: 0,
  localPath: 'models/transcriber/whisper-small.bin',
  state: 'installed',
  recommended: false
}
describe('ModelsScreen — engine problem banner (#530)', () => {
  beforeEach(() => {
    __resetModelsScreenMemoryForTests()
  })

  function stubModels(opts: {
    problems: () => EngineProblem[]
    recheckEngine?: Mock
    engine?: EngineStatus
    runtime?: RuntimeStatus
    /** #532: the download gate (default: policy and setting allow). */
    policy?: { allowModelDownloads: boolean; allowNetworkSetting: boolean }
    models?: ModelInfo[]
    downloadEngine?: Mock
    getEngineJob?: Mock
  }): { push: () => void; recheckEngine: Mock } {
    let subscriber: (() => void) | null = null
    const recheckEngine = opts.recheckEngine ?? vi.fn(async (): Promise<EngineRecheckResult> => ({ problems: opts.problems() }))
    const gate = opts.policy ?? { allowModelDownloads: true, allowNetworkSetting: true }
    stubModelsApi({
      listModels: vi.fn(async () => opts.models ?? []),
      getPolicy: vi.fn(async () =>
        makePolicyStatus({ network: { allowModelDownloads: gate.allowModelDownloads }, allowNetworkSetting: gate.allowNetworkSetting })
      ),
      ...(opts.downloadEngine ? { downloadEngine: opts.downloadEngine } : {}),
      ...(opts.getEngineJob ? { getEngineJob: opts.getEngineJob } : {}),
      // #843: what the reinstall's confirmation states (one archive is enough for these rows).
      getEnginePlan: vi.fn(async () => enginePreview({ kind: 'reinstall' })),
      getAppStatus: vi.fn(async () => appStatus({ engineProblems: opts.problems() })),
      getEngineStatus: vi.fn(async () => opts.engine ?? ENGINE_INSTALLED),
      onEngineProblemsChanged: vi.fn((cb: () => void) => {
        subscriber = cb
        return () => {
          subscriber = null
        }
      }),
      recheckEngine,
      getRuntimeStatus: vi.fn(async () => opts.runtime ?? STOPPED_RUNTIME)
    })
    return { push: () => subscriber?.(), recheckEngine }
  }

  const renderModels = (): ReturnType<typeof render> =>
    render(
      <ToastProvider>
        <ModelsScreen />
      </ToastProvider>
    )

  it('hides the optional voice-engine banner while the chat engine cannot run (its copy says chat works)', async () => {
    const voiceMissing: EngineStatus = { ...ENGINE_INSTALLED, missingFamilies: ['whisper_cpp'] }
    stubModels({ problems: () => [LIBGOMP], engine: voiceMissing })
    const { unmount } = renderModels()
    expect(await screen.findByText(en('models.engineProblem.title'))).toBeInTheDocument()
    expect(screen.queryByText(en('models.voiceEngine.title'))).not.toBeInTheDocument()
    unmount()
    __resetModelsScreenMemoryForTests()
    stubModels({ problems: () => [], engine: voiceMissing })
    renderModels()
    expect(await screen.findByText(en('models.voiceEngine.title'))).toBeInTheDocument()
  })

  it('drops the demo note while a REAL runtime answers (a cpu/ build beside a damaged main folder)', async () => {
    stubModels({
      problems: () => [LIBGOMP],
      runtime: { ...STOPPED_RUNTIME, running: true, modelId: 'm', backend: 'cpu', healthy: true }
    })
    renderModels()
    expect(await screen.findByText(en('models.engineProblem.title'))).toBeInTheDocument()
    await waitFor(() => expect(window.api.getRuntimeStatus).toHaveBeenCalled())
    await waitFor(() => expect(screen.queryByText(en('models.engineProblem.demoNote'))).not.toBeInTheDocument())
  })

  it('the engine:problemsChanged push re-reads the status and removes the banner', async () => {
    let problems: EngineProblem[] = [LIBGOMP]
    const s = stubModels({ problems: () => problems })
    renderModels()
    expect(await screen.findByText(en('models.engineProblem.title'))).toBeInTheDocument()
    problems = []
    act(() => s.push())
    await waitFor(() => expect(screen.queryByText(en('models.engineProblem.title'))).not.toBeInTheDocument())
  })

  it('a verdict that lands after mount shows up on the push', async () => {
    let problems: EngineProblem[] = []
    const s = stubModels({ problems: () => problems })
    renderModels()
    // Loaded — and the first verdict read with it (issued first, one hop; refresh() is a Promise.all of five): no verdict, no banner.
    expect(await screen.findByText(en('models.lead'))).toBeInTheDocument()
    expect(screen.queryByText(en('models.engineProblem.title'))).not.toBeInTheDocument()
    problems = [LIBGOMP]
    act(() => s.push())
    expect(await screen.findByText(en('models.engineProblem.title'))).toBeInTheDocument()
  })

  it('a rejected recheckEngine surfaces a friendly message in the banner', async () => {
    const user = userEvent.setup()
    const recheckEngine = vi.fn(async () => {
      throw new Error("Error invoking remote method 'engine:recheck': Error: Could not check right now.")
    })
    stubModels({ problems: () => [LIBGOMP], recheckEngine })
    renderModels()
    await user.click(await screen.findByRole('button', { name: en('models.engineProblem.check') }))
    const banner = screen.getByText(en('models.engineProblem.title')).closest('.banner') as HTMLElement
    // ModelsScreen's recheckEngine strips the transport prefix (friendlyIpcError); the notice shows the rest as-is.
    expect(await within(banner).findByText('Could not check right now.')).toBeInTheDocument()
    expect(recheckEngine).toHaveBeenCalledTimes(1)
    expect(within(banner).getByRole('button', { name: en('models.engineProblem.check') })).toBeEnabled()
  })

  // #532: damaged engine files are the one refusal a fresh copy fixes, so the banner (and the voice
  // hint) offer "Install … again" — the same job, gates and progress as the install banners.
  describe('Install the engine again (#532)', () => {
    const DAMAGED: EngineProblem = { family: 'llama_cpp', reason: 'files-damaged', os: 'win', exit: 'exit code 0xC0000135' }
    const REPAIRABLE: EngineStatus = { ...ENGINE_INSTALLED, reinstallableFamilies: ['llama_cpp', 'whisper_cpp'] }
    const job = (over: Partial<EngineDownloadJob>): EngineDownloadJob =>
      engineJob({ jobId: 'r1', receivedBytes: 50, totalBytes: 100, families: ['llama_cpp'], reinstall: true, ...over })
    const banner = (): HTMLElement =>
      screen.getByText(en('models.engineProblem.title')).closest('.banner') as HTMLElement

    it('offers it first, names it in the reason, runs the reinstall in the banner and confirms it when done', async () => {
      const user = userEvent.setup()
      const downloadEngine = vi.fn(async () => job({}))
      stubModels({
        problems: () => [DAMAGED],
        engine: REPAIRABLE,
        downloadEngine,
        getEngineJob: vi.fn(async () => job({ status: 'done' }))
      })
      renderModels()
      const reinstall = await screen.findByRole('button', { name: en('models.engineProblem.reinstall') })
      const check = screen.getByRole('button', { name: en('models.engineProblem.check') })
      expect(within(banner()).getByText(en('models.engineProblem.filesDamagedReinstall'))).toBeInTheDocument()
      // The fix leads; Check again (for a fix made elsewhere) follows it.
      expect(reinstall.compareDocumentPosition(check) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
      await user.click(reinstall)
      // #843: it asks first, under the action's own name.
      await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: en('models.engineProblem.reinstall') }))
      expect(downloadEngine).toHaveBeenCalledWith({ families: ['llama_cpp'], reinstall: true })
      // The progress is this banner's: the missing-engine banner never shows a reinstall.
      expect(await within(banner()).findByText(en('models.engine.progress', { pct: 50 }))).toBeInTheDocument()
      expect(screen.queryByText(en('models.engine.title'))).not.toBeInTheDocument()
      // Checking a program that is being replaced would say nothing.
      expect(within(banner()).getByRole('button', { name: en('models.engineProblem.check') })).toBeDisabled()
      // Main drops the verdict as the job ends, and the banner with it — the toast says what happened.
      expect(await screen.findByText(en('models.engineProblem.reinstalled'))).toBeInTheDocument()
    })

    it.each([
      [
        'the drive policy forbids downloads: disabled with the policy reason, the reason keeps the guide',
        { allowModelDownloads: false, allowNetworkSetting: true },
        'models.engineProblem.filesDamaged',
        'models.downloads.blockedByPolicy'
      ],
      [
        'internet access is off in Settings: disabled with that reason, the reason names the reinstall',
        { allowModelDownloads: true, allowNetworkSetting: false },
        'models.engineProblem.filesDamagedReinstall',
        'models.downloads.enableInSettings'
      ]
    ] as const)('%s', async (_label, policy, reasonKey, gateKey) => {
      stubModels({ problems: () => [DAMAGED], engine: REPAIRABLE, policy })
      renderModels()
      expect(await screen.findByRole('button', { name: en('models.engineProblem.reinstall') })).toBeDisabled()
      await waitFor(() => expect(within(banner()).getByText(en(reasonKey))).toBeInTheDocument())
      expect(within(banner()).getByText(en(gateKey))).toBeInTheDocument()
      // Check again stays usable: a fix made outside the app needs no download.
      expect(screen.getByRole('button', { name: en('models.engineProblem.check') })).toBeEnabled()
    })

    it.each<[string, EngineProblem, EngineStatus]>([
      ['a fresh copy that failed too (afterInstall)', { ...DAMAGED, afterInstall: true }, REPAIRABLE],
      ['a refusal a reinstall cannot fix (Windows security)', { ...DAMAGED, reason: 'blocked', exit: 'exit code 0xC0E90002' }, REPAIRABLE],
      ['an engine the installer cannot fetch here (or an older main)', DAMAGED, ENGINE_INSTALLED]
    ])('offers no reinstall for %s — only Check again', async (_label, problem, engine) => {
      stubModels({ problems: () => [problem], engine })
      renderModels()
      expect(await screen.findByRole('button', { name: en('models.engineProblem.check') })).toBeInTheDocument()
      await waitFor(() => expect(window.api.getEngineStatus).toHaveBeenCalled())
      expect(screen.queryByRole('button', { name: en('models.engineProblem.reinstall') })).not.toBeInTheDocument()
    })

    it('the voice engine hint offers its own quieter reinstall, and its progress stays on the speech-model card', async () => {
      const user = userEvent.setup()
      const downloadEngine = vi.fn(async () => job({ families: ['whisper_cpp'] }))
      stubModels({
        problems: () => [{ ...DAMAGED, family: 'whisper_cpp' }],
        // The AI engine is missing at the same time: its install banner is on screen too.
        engine: { ...ENGINE_INSTALLED, installed: false, missingFamilies: ['llama_cpp'], reinstallableFamilies: ['whisper_cpp'] },
        models: [SPEECH_MODEL],
        downloadEngine,
        getEngineJob: vi.fn(async () => job({ families: ['whisper_cpp'] }))
      })
      renderModels()
      const reinstall = await screen.findByRole('button', { name: en('models.engineProblem.voiceReinstall') })
      // The hint stays quiet (§11.17 #5): chat is unaffected, so this is no loud primary.
      expect(reinstall).not.toHaveClass('primary')
      expect(screen.queryByText(en('models.engineProblem.title'))).not.toBeInTheDocument()
      const hint = reinstall.closest('.engine-problem-hint') as HTMLElement
      const installBanner = screen.getByText(en('models.engine.title')).closest('.banner') as HTMLElement
      await user.click(reinstall)
      await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: en('models.engineProblem.voiceReinstall') }))
      expect(downloadEngine).toHaveBeenCalledWith({ families: ['whisper_cpp'], reinstall: true })
      expect(await within(hint).findByText(en('models.engine.progress', { pct: 50 }))).toBeInTheDocument()
      // The install banner does not claim that job, and waits for it: one engine job at a time.
      expect(within(installBanner).queryByText(en('models.engine.progress', { pct: 50 }))).not.toBeInTheDocument()
      expect(within(installBanner).getByRole('button', { name: en('models.engine.install') })).toBeDisabled()
    })
  })
})

// ---- 6: HomeScreen ---------------------------------------------------------------------------

describe('HomeScreen — engine problem and demo runtime (#530)', () => {
  function renderHome(opts: {
    problems?: EngineProblem[]
    runtime: Partial<RuntimeStatus>
    onNavigate?: (t: string) => void
  }): void {
    stubHomeApi({
      getAppStatus: vi.fn(async () => appStatus({ activeModelId: 'qwen3-chat', engineProblems: opts.problems })),
      getRuntimeStatus: vi.fn(async () => ({ ...STOPPED_RUNTIME, ...opts.runtime }))
    })
    render(<HomeScreen onNavigate={opts.onNavigate ?? vi.fn()} />)
  }

  const RUNNING = { running: true, modelId: 'qwen3-chat', port: 1, healthy: true, message: 'Running' }

  it('an engine problem: the row says it, the badge says it, and the loud primary leads to AI Model', async () => {
    const onNavigate = vi.fn()
    // While the chat engine can't run, the demo runtime answers (rung 4): the engine row must win over the demo row.
    renderHome({ problems: [LIBGOMP], runtime: { ...RUNNING, backend: 'mock' }, onNavigate })
    expect(await screen.findByText(en('home.model.engineCannotRun'))).toBeInTheDocument()
    expect(screen.getByText(en('home.model.badgeEngine'))).toBeInTheDocument()
    expect(screen.queryByText(en('home.model.demo', { model: 'qwen3-chat' }))).not.toBeInTheDocument()
    // The headline does not claim "ready" either.
    expect(screen.queryByText(en('home.headline.ready'))).not.toBeInTheDocument()
    // Two "Go to AI Model" buttons: the row's small one, and the hero primary.
    const buttons = screen.getAllByRole('button', { name: en('home.model.open') })
    const primary = buttons.filter((b) => b.classList.contains('primary'))
    expect(primary).toHaveLength(1)
    await userEvent.click(primary[0])
    expect(onNavigate).toHaveBeenCalledWith('models')
    // Chatting stays reachable, as a secondary.
    const chat = screen.getByRole('button', { name: en('home.actions.startChat') })
    expect(chat).not.toHaveClass('primary')
  })

  it('a voice-only problem does not touch the chat model row', async () => {
    renderHome({ problems: [WHISPER], runtime: RUNNING })
    expect(await screen.findByText(en('home.model.running', { model: 'qwen3-chat' }))).toBeInTheDocument()
    expect(screen.queryByText(en('home.model.engineCannotRun'))).not.toBeInTheDocument()
  })

  it('a running MOCK runtime with no engine problem says demo mode with the model id', async () => {
    renderHome({ runtime: { ...RUNNING, backend: 'mock' } })
    expect(await screen.findByText(en('home.model.demo', { model: 'qwen3-chat' }))).toBeInTheDocument()
    expect(screen.getByText(en('home.model.badgeDemo'))).toBeInTheDocument()
    expect(screen.queryByText(en('home.model.engineCannotRun'))).not.toBeInTheDocument()
    expect(screen.queryByText(en('home.model.running', { model: 'qwen3-chat' }))).not.toBeInTheDocument()
  })

  it('an engine problem beside a REAL runtime (a cpu/ build answering) does not claim simulated replies', async () => {
    // Review fix: a Windows Kit's cpu/ build can run beside a damaged main folder — chat works.
    renderHome({ problems: [LIBGOMP], runtime: { ...RUNNING, backend: 'cpu' } })
    expect(await screen.findByText(en('home.model.running', { model: 'qwen3-chat' }))).toBeInTheDocument()
    expect(screen.queryByText(en('home.model.engineCannotRun'))).not.toBeInTheDocument()
  })
})

// ---- 7: the App notice -----------------------------------------------------------------------

describe('App — runtime notice target (#530)', () => {
  beforeEach(() => {
    __resetModelsScreenMemoryForTests()
  })

  function renderApp(opts: { problems?: () => EngineProblem[]; appStatusGate?: Promise<void> } = {}): {
    fire: (message: string, target?: 'models') => void
    push: () => void
  } {
    let subscriber: ((message: string, target?: 'models') => void) | null = null
    // Several components subscribe (App, Home, …): keep them all, as the real preload does.
    const engineSubscribers = new Set<() => void>()
    const status = (): AppStatus => ({ ...appStatus({ machineRamGb: 16 }), engineProblems: opts.problems?.() ?? [] })
    const shell = appShellStubs({
      ...modelsScreenStubs(),
      onRuntimeNotice: vi.fn((cb: (message: string, target?: 'models') => void) => {
        subscriber = cb
        return () => {
          subscriber = null
        }
      }),
      onEngineProblemsChanged: vi.fn((cb: () => void) => {
        engineSubscribers.add(cb)
        return () => {
          engineSubscribers.delete(cb)
        }
      }),
      // A gate holds every status read (all its readers) until the test releases it; without one, today's timing.
      getAppStatus: opts.appStatusGate
        ? vi.fn(async () => {
            await opts.appStatusGate
            return status()
          })
        : vi.fn(async () => status()),
      getDriveStatus: vi.fn(async () => driveStatus()),
      getRuntimeInstall: vi.fn(async () => null),
      getLogTail: vi.fn(async () => []),
      // The 'Details' row navigates on to Settings → Diagnostics, which reads the snapshot.
      getPerformance: vi.fn(async () => performanceSnapshot())
    })
    stubApi(shell)
    render(<App />)
    return { fire: (message, target) => subscriber?.(message, target), push: () => engineSubscribers.forEach((cb) => cb()) }
  }

  it("a 'models' notice's button reads 'Go to AI Model' and navigates there", async () => {
    const user = userEvent.setup()
    const app = renderApp()
    const nav = await screen.findByRole('navigation')
    await waitFor(() => expect(window.api.onRuntimeNotice).toHaveBeenCalled())
    const message = 'The AI engine can not run here (test notice).'
    act(() => app.fire(message, 'models'))
    const text = await screen.findByText(message)
    const banner = text.closest('.banner') as HTMLElement
    expect(within(banner).queryByRole('button', { name: en('app.noticeDetails') })).not.toBeInTheDocument()
    const go = within(banner).getByRole('button', { name: en('app.noticeGoToModels') })
    expect(within(nav).getByRole('button', { name: 'AI Model' })).not.toHaveAttribute('aria-current')
    await user.click(go)
    await waitFor(() => expect(within(nav).getByRole('button', { name: 'AI Model' })).toHaveAttribute('aria-current', 'page'))
  })

  it.each([
    { what: 'the AI Model notice leaves', target: 'models' as const, stays: false },
    { what: 'a notice without a target stays', target: undefined, stays: true }
  ])('once Check again healed the chat engine (verdict true → false), $what', async ({ target, stays }) => {
    // Both rows run one sequence: the `leaves` row is the timing control that App's own re-read has
    // landed by the final assertion, so the `stays` row cannot pass because App had not read yet.
    let problems: EngineProblem[] = [LIBGOMP]
    const app = renderApp({ problems: () => problems })
    // The verdict was read: Home's row says so (App's own read was issued first, at mount).
    expect(await screen.findByText(en('home.model.engineCannotRun'))).toBeInTheDocument()
    const message = 'A runtime notice (test).'
    act(() => app.fire(message, target))
    expect(await screen.findByText(message)).toBeInTheDocument()
    problems = []
    await act(async () => app.push()) // every reader re-reads; async act drains the renders and effects (React 18.3)
    expect(screen.queryByText(en('home.model.engineCannotRun'))).not.toBeInTheDocument() // the heal landed
    expect(screen.queryByText(message) !== null).toBe(stays)
  })

  it('an engine notice that arrives before any verdict was read is not cleared by that first read', async () => {
    // Every status read waits until the notice is up: the first verdict read lands AFTER it, finding nothing —
    // null → false is no true → false transition (§11.17 decision 4).
    const firstRead = deferred<void>()
    const app = renderApp({ problems: () => [], appStatusGate: firstRead.promise })
    await screen.findByRole('navigation')
    await waitFor(() => expect(window.api.onRuntimeNotice).toHaveBeenCalled())
    const message = 'The AI engine can not run here (early notice).'
    act(() => app.fire(message, 'models'))
    expect(await screen.findByText(message)).toBeInTheDocument()
    expect(window.api.getAppStatus).toHaveBeenCalled() // in flight, not landed
    await act(async () => firstRead.resolve()) // the read lands; act drains the render, the effect and any setNotice
    expect(screen.getByText(message)).toBeInTheDocument()
  })

  it('a notice without a target keeps the "Details" button (Diagnostics)', async () => {
    const user = userEvent.setup()
    const app = renderApp()
    const nav = await screen.findByRole('navigation')
    await waitFor(() => expect(window.api.onRuntimeNotice).toHaveBeenCalled())
    const message = 'Switched to compatibility mode (test notice).'
    act(() => app.fire(message))
    const banner = (await screen.findByText(message)).closest('.banner') as HTMLElement
    expect(within(banner).queryByRole('button', { name: en('app.noticeGoToModels') })).not.toBeInTheDocument()
    await user.click(within(banner).getByRole('button', { name: en('app.noticeDetails') }))
    // Diagnostics lives on a Settings tab: the rail's Settings item lights up…
    await waitFor(() => expect(within(nav).getByRole('button', { name: 'Settings' })).toHaveAttribute('aria-current', 'page'))
    // …on its Diagnostics tab, not General.
    expect(await screen.findByText(en('diag.localOnly'))).toBeInTheDocument()
  })
})

// ---- 8: Diagnostics --------------------------------------------------------------------------

describe('Settings → Diagnostics — engine problem line (#530)', () => {
  let lastCopied: string | null = null

  function stubDiagnostics(problems: EngineProblem[]): void {
    lastCopied = null
    stubApi(diagnosticsEngineStubs({
      getAppStatus: vi.fn(async () => appStatus({ appVersion: '0.1.20', engineProblems: problems })),
      getDriveStatus: vi.fn(async () => driveStatus()),
      getRuntimeStatus: vi.fn(async () => STOPPED_RUNTIME),
      getRuntimeInstall: vi.fn(async () => null),
      getSettings: vi.fn(async () => DEFAULT_SETTINGS),
      getPerformance: vi.fn(async () => performanceSnapshot()),
      getLogTail: vi.fn(async () => []),
      copyToClipboard: vi.fn(async (text: string) => {
        lastCopied = text
        return true
      })
    }))
  }

  const renderDiagnostics = (): void => {
    render(
      <ToastProvider>
        <SettingsScreen tab="diagnostics" />
      </ToastProvider>
    )
  }

  const line = (): string =>
    en('diag.engine.cannotRun', { reason: en('diag.engine.reason.libraryMissing') }) + ' (libgomp.so.1, exit code 127)'

  it('shows the label as a dt and the reason + technical detail as its dd, and copies the same line', async () => {
    const user = userEvent.setup()
    stubDiagnostics([LIBGOMP])
    renderDiagnostics()
    const dd = await screen.findByText(line())
    expect(dd.tagName).toBe('DD')
    const dt = screen.getByText(en('diag.app.engine'))
    expect(dt.tagName).toBe('DT')
    expect(dt.nextElementSibling).toBe(dd)
    await user.click(screen.getAllByRole('button', { name: en('diag.copy') })[0])
    await waitFor(() => expect(lastCopied).not.toBeNull())
    expect(lastCopied).toContain(`${en('diag.app.engine')}: ${line()}`)
  })

  it('damaged files reported right after a fresh install say so — support reads it off the report (#532)', async () => {
    stubDiagnostics([{ family: 'llama_cpp', reason: 'files-damaged', os: 'win', exit: 'exit code 0xC0000135', afterInstall: true }])
    renderDiagnostics()
    expect(
      await screen.findByText(
        en('diag.engine.cannotRun', { reason: en('diag.engine.reason.filesDamagedAfterInstall') }) + ' (exit code 0xC0000135)'
      )
    ).toBeInTheDocument()
  })

  it('a voice-engine problem is labelled "Voice engine"', async () => {
    stubDiagnostics([WHISPER])
    renderDiagnostics()
    expect(await screen.findByText(en('diag.app.voiceEngine'))).toBeInTheDocument()
    expect(screen.queryByText(en('diag.app.engine'))).not.toBeInTheDocument()
  })

  it('shows no engine line when there is no problem', async () => {
    stubDiagnostics([])
    renderDiagnostics()
    // The app read has landed — the version row and the engine rows come from the same `app` state.
    expect(await screen.findByText('HilbertRaum 0.1.20')).toBeInTheDocument()
    expect(screen.queryByText(en('diag.app.engine'))).not.toBeInTheDocument()
  })
})

// ---- 9: Performance --------------------------------------------------------------------------

describe('PerformanceScreen — graphics tile under an engine problem (#530)', () => {
  function stubPerformance(problems: EngineProblem[]): void {
    const snap: PerformanceSnapshot = {
      ...performanceSnapshot(),
      current: laptopResult({ recommendedModelId: null }),
      currentMachine: true,
      currentGpu: null,
      graphicsDevice: null
    }
    stubApi({
      getPerformance: vi.fn(async () => snap),
      listModels: vi.fn(async () => []),
      getSettings: vi.fn(async () => DEFAULT_SETTINGS),
      getRuntimeStatus: vi.fn(async () => STOPPED_RUNTIME),
      getAppStatus: vi.fn(async () => appStatus({ engineProblems: problems })),
      onBenchmarkProgress: vi.fn(() => () => {}),
      onPerformanceChanged: vi.fn(() => () => {}),
      onEngineProblemsChanged: vi.fn(() => () => {})
    })
  }
  const renderPerf = (): void => {
    render(
      <ToastProvider>
        <PerformanceScreen onNavigate={vi.fn()} />
      </ToastProvider>
    )
  }

  it('says the engine could not check the card, with an "Unknown" pill, instead of "no usable card"', async () => {
    stubPerformance([LIBGOMP])
    renderPerf()
    expect(await screen.findByText(en('perf.tile.graphics.engine'))).toBeInTheDocument()
    expect(screen.getByText(en('perf.rating.unknown'))).toBeInTheDocument()
    expect(screen.queryByText(en('perf.tile.graphics.none'))).not.toBeInTheDocument()
  })

  it('without a problem the same snapshot still reads "no usable graphics card"', async () => {
    stubPerformance([])
    renderPerf()
    expect(await screen.findByText(en('perf.tile.graphics.none'))).toBeInTheDocument()
    expect(screen.queryByText(en('perf.tile.graphics.engine'))).not.toBeInTheDocument()
  })

  it('a voice-only problem does not change the graphics tile', async () => {
    stubPerformance([WHISPER])
    renderPerf()
    expect(await screen.findByText(en('perf.tile.graphics.none'))).toBeInTheDocument()
  })
})

// ---- 10: the engineCannotRun error code (Images) ---------------------------------------------

describe('engineCannotRun error code copy (#530)', () => {
  it('AnswerThread renders images.err.engineCannotRun', () => {
    const turn: ImageTurn = { id: 't1', question: 'What?', answer: '', state: 'failed', error: 'engineCannotRun' }
    render(<AnswerThread turns={[turn]} onCopy={() => {}} onTryAgain={() => {}} onStop={() => {}} busy={false} />)
    expect(screen.getByText(en('images.err.engineCannotRun'))).toBeInTheDocument()
    expect(screen.queryByText(en('images.err.runtimeFailed'))).not.toBeInTheDocument()
  })
})