Skip to content

AI, fully local on your computer.

45.8 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

// The graphics figures of the Performance screen come from ONE eligible source (PR #303 audit
// M8 / N1 / DR1 / DR2 / DR5, owner decisions G3 / G4):
//  - the persisted probe is STAMPED with the machine it ran on, and a probe stamped with
//    another machine supplies nothing; an unstamped legacy probe stays eligible (G3; the rule's
//    own cases live in gpu-rules.test.ts);
//  - of the eligible probe, ONE device is selected — the BUDGET device for the next start
//    (`nextStartMemory`: the largest usable card; PR #308 audit decision 9, unified with this
//    audit's M8.2 at the merge of the two) — and its name and memory travel together into the
//    benchmark result, the fold-in, `currentGpu` and the VRAM budget — on a hybrid
//    [iGPU, dGPU] box that is the dGPU, never devices[0]; an integrated-only box has NO device
//    for the next start (null everywhere, the RAM pick);
//  - the probe write: every path persists THIS session's stamped answer — a resolved list
//    (empty included), no binary and a rejecting probe alike (PR #308 audit decision 6: a
//    stale same-machine card must not survive a failed refresh; an empty stamped result
//    re-stamps no old device); a probe that outlives a lock or its workspace session writes
//    nothing — and "Try GPU again" pushes as soon as it clears the flags, before the probe's
//    own write pushes again (A-D1);
//  - the rows say where a model runs under the CURRENT configuration (DR1), the free/working
//    figures are attributed to the selected device (DR2), and the "everything at once" total
//    is class-aware (DR5);
//  - the hardware-profile bump follows ALL devices, as before (G4).

vi.mock('electron', () => ({
  ipcMain: {
    handle: () => undefined,
    removeHandler: () => undefined
  },
  app: { getVersion: () => '0.0.0-test' }
}))

// 32 GB: a BALANCED machine, one step up with a useful card (the profile rows below expect literals).
vi.mock('node:os', async (importOriginal) => ({
  ...(await importOriginal<typeof import('node:os')>()),
  totalmem: () => 32 * 1024 ** 3
}))

import {
  buildPerformanceSnapshot,
  probeAndPersistGpu,
  runAndPersistBenchmark,
  tryGpuAgain
} from '../../src/main/ipc/registerBenchmarkIpc'
import { setPerformanceChangedSink } from '../../src/main/ipc/performance-notify'
import type { AppContext } from '../../src/main/services/context'
import type { Db } from '../../src/main/services/db'
import { log } from '../../src/main/services/logging'
import { resetPerformanceForTests } from '../../src/main/services/performance'
import { resetEffectiveReadForTests } from '../../src/main/services/read-speed'
import { ModelOccupancy } from '../../src/main/services/runtime/occupancy'
import {
  clearModelLoadLatches,
  clearSpeculativeSuppression,
  isSpeculativeSuppressed,
  latchModelLoad,
  modelLoadLatchReason,
  suppressSpeculative
} from '../../src/main/services/runtime/factory'
import { recordModelPlacement, resetModelPlacementForTests } from '../../src/main/services/runtime/placement'
import { getSettings, updateSettings } from '../../src/main/services/settings'
import type {
  AppSettings,
  BenchmarkResult,
  GpuDevice,
  GpuProbeResult,
  ModelPlacement,
  PerformanceSnapshot,
  ResidentModelRow,
  RuntimeStatus,
  TranslationDeviceStatus
} from '../../src/shared/types'
import { modelPlacement } from '../helpers/benchmark-records'
import { deferred } from '../helpers/deferred'
import {
  CARDS,
  CATALOG_MANIFESTS,
  closePerformanceFixture,
  ctxWith,
  fakeGpuProbe,
  freshRoot,
  hereKey,
  hereResult,
  performanceChangedSpy,
  pinPlatform,
  result,
  seededDb,
  withCatalogFiles,
  withLlamaBinary,
  type CatalogRole
} from '../helpers/performance-fixture'
import { runtimeStatus } from '../helpers/status'
import { workspaceStandIn } from '../helpers/workspace-stand-in'

// #656: pinned, not inherited from the host. The memory class reads process.platform /
// process.arch, and every probe here is a Vulkan Windows/Linux machine: on an Apple Silicon host
// the class is `unified` and its device the LARGEST one listed, so a hybrid fixture would name
// its iGPU there. The placeholder binary below is named for the same pinned platform. Apple
// Silicon's own branch is pinned in performance.test.ts (`nextStartMemory`); see also #332.
pinPlatform('win32', 'x64')

beforeEach(() => {
  resetPerformanceForTests()
  resetEffectiveReadForTests()
  resetModelPlacementForTests()
  setPerformanceChangedSink(null)
})

// TH2: every root/DB in this file (including via the `cardMachine`/`withLog` helpers below)
// comes from the fixture's `freshRoot`/`seededDb` — safe to add the shared teardown.
afterEach(async () => {
  vi.restoreAllMocks()
  await closePerformanceFixture()
})

const IRIS: GpuDevice = { id: 'Vulkan0', name: 'Intel(R) Iris(R) Xe Graphics', totalMb: 16_384, freeMb: 15_000 }
const RTX: GpuDevice = { id: 'Vulkan1', name: 'NVIDIA GeForce RTX 3090', totalMb: 24_576, freeMb: 22_000 }
// A real hybrid laptop (2026-09-07): the iGPU listed first, the "6 GB" card at 5,994 MiB on Vulkan.
// That was under the old 6,144 gate; since #321 lowered it to 5,120 the card IS the budget device.
const RADEON_IGPU: GpuDevice = { id: 'Vulkan0', name: 'AMD Radeon(TM) Graphics', totalMb: 8886, freeMb: 8441 }
const RTX3060L = CARDS.RTX_3060_LAPTOP
const PROBED_AT = '2026-09-05T00:00:00Z'
const FOREIGN_KEY = 'linux|x64|Some Other CPU|32|64'
const CHAT = 'qwen3.5-9b-ud-q4kxl'

/** A persisted probe: unstamped (legacy) when `stamp` is omitted, else stamped with it. */
function probe(devices: GpuDevice[], stamp?: string | null): GpuProbeResult {
  return stamp === undefined ? { devices, probedAt: PROBED_AT } : { devices, probedAt: PROBED_AT, machineKey: stamp }
}

/** A result of THIS machine persisted before `gpuVramMb` existed, naming whatever `gpu` says. */
function legacyResult(gpu: string | null = null): BenchmarkResult {
  const r = hereResult({ gpu })
  delete r.gpuVramMb
  return r
}

describe('one eligible source: the selected device (M8.2)', () => {
  it('a hybrid [iGPU, dGPU] probe: currentGpu, the VRAM budget, the class and the fold-in all describe the dGPU', () => {
    const root = freshRoot()
    const db = seededDb(root)
    // An "already-mixed" older row: the old devices[0] rule recorded the iGPU's name.
    updateSettings(db, { lastBenchmark: legacyResult(IRIS.name), gpuProbe: probe([IRIS, RTX]) })

    const snap = buildPerformanceSnapshot(ctxWith(root, db))

    expect(snap.currentGpu).toEqual({ name: RTX.name, totalMb: RTX.totalMb, useful: true })
    // With a usable card the display device IS the budget device.
    expect(snap.graphicsDevice).toEqual({ name: RTX.name, totalMb: RTX.totalMb, useful: true })
    expect(snap.placement.vramMb).toBe(RTX.totalMb)
    expect(snap.placement.memoryClass).toBe('discrete')
    // The fold-in replaces NAME and memory together: never the old iGPU name with the dGPU's figure.
    expect(snap.current?.gpu).toBe(RTX.name)
    expect(snap.current?.gpuVramMb).toBe(RTX.totalMb)
  })

  it('an integrated-only probe: no budget device — currentGpu is null, no VRAM budget, nothing folded in (M8.1 / PR #308 decision 9)', () => {
    const root = freshRoot()
    const db = seededDb(root)
    updateSettings(db, { lastBenchmark: legacyResult(), gpuProbe: probe([IRIS]) })

    const snap = buildPerformanceSnapshot(ctxWith(root, db))

    // The #303 P5 rule named the iGPU with `useful: false`; merged with #308, the snapshot's
    // `currentGpu` names the BUDGET device only, and an integrated device is not one for any
    // consumer — the ★ is the RAM pick, nothing is folded in. The tile still NAMES the iGPU
    // through `graphicsDevice` (rated "Integrated, shared memory", owner decision 2026-09-07).
    expect(snap.currentGpu).toBeNull()
    expect(snap.graphicsDevice).toEqual({ name: IRIS.name, totalMb: IRIS.totalMb, useful: false })
    expect(snap.placement.vramMb).toBeNull()
    expect(snap.placement.memoryClass).toBe('cpu')
    expect(snap.current?.gpu).toBeNull()
    expect(snap.current?.gpuVramMb).toBeUndefined()
  })

  it('a hybrid [iGPU, 6 GB dGPU] probe: the CARD is the budget device since #321 — every consumer describes it, never the iGPU', () => {
    for (const devices of [[RADEON_IGPU, RTX3060L], [RTX3060L, RADEON_IGPU]]) {
      const root = freshRoot()
      const db = seededDb(root)
      updateSettings(db, { lastBenchmark: legacyResult(), gpuProbe: probe(devices) })

      const snap = buildPerformanceSnapshot(ctxWith(root, db))

      // 5,994 ≥ the 5,120 gate: discrete, and every figure is the CARD's — not the shared-memory
      // iGPU's, whichever order the driver listed them in. Before #321 this machine had no budget
      // device at all and fell back to the RAM pick.
      expect(snap.currentGpu).toEqual({ name: RTX3060L.name, totalMb: 5994, useful: true })
      expect(snap.placement.vramMb).toBe(5994)
      expect(snap.placement.memoryClass).toBe('discrete')
      expect(snap.current?.gpu).toBe(RTX3060L.name)
      expect(snap.current?.gpuVramMb).toBe(5994)
      // The tile names the same device, now rated usable.
      expect(snap.graphicsDevice).toEqual({ name: RTX3060L.name, totalMb: 5994, useful: true })
    }
  })

  it('a hybrid [iGPU, SUB-gate dGPU] probe: still no budget device, and the tile still names THE card (owner decision 2026-09-07)', () => {
    const gtx1650 = { id: 'Vulkan1', name: 'NVIDIA GeForce GTX 1650', totalMb: 4096, freeMb: 3900 }
    const root = freshRoot()
    const db = seededDb(root)
    updateSettings(db, { lastBenchmark: legacyResult(), gpuProbe: probe([RADEON_IGPU, gtx1650]) })

    const snap = buildPerformanceSnapshot(ctxWith(root, db))

    // 4,096 MiB is under the gate even at 5,120: no budget device for ANY consumer…
    expect(snap.currentGpu).toBeNull()
    expect(snap.placement.vramMb).toBeNull()
    expect(snap.placement.memoryClass).toBe('cpu')
    expect(snap.current?.gpu).toBeNull()
    expect(snap.current?.gpuVramMb).toBeUndefined()
    // …and the graphics tile still names it with its OWN memory — never the iGPU listed first,
    // never "no usable graphics card". Whether it is used is the rating's (and the budget's) job.
    expect(snap.graphicsDevice).toEqual({ name: gtx1650.name, totalMb: 4096, useful: false })
  })

  it('with the GPU switched off or auto-disabled the tile names no device either, so its "acceleration is off" copy stands', () => {
    for (const flags of [{ gpuMode: 'off' as const }, { gpuAutoDisabled: true }]) {
      const root = freshRoot()
      const db = seededDb(root)
      updateSettings(db, { lastBenchmark: legacyResult(), gpuProbe: probe([RADEON_IGPU, RTX3060L]), ...flags })

      const snap = buildPerformanceSnapshot(ctxWith(root, db))

      expect(snap.currentGpu).toBeNull()
      expect(snap.graphicsDevice).toBeNull()
    }
  })

  it('a result that already carries a figure is left alone; a foreign result is never folded', () => {
    const root = freshRoot()
    const db = seededDb(root)
    updateSettings(db, { lastBenchmark: hereResult({ gpu: 'NVIDIA GeForce GTX 1650', gpuVramMb: 4096 }), gpuProbe: probe([RTX]) })
    expect(buildPerformanceSnapshot(ctxWith(root, db)).current).toMatchObject({ gpu: 'NVIDIA GeForce GTX 1650', gpuVramMb: 4096 })

    const foreign = result()
    delete (foreign as Partial<BenchmarkResult>).gpuVramMb
    updateSettings(db, { lastBenchmark: foreign })
    const snap = buildPerformanceSnapshot(ctxWith(root, db))
    expect(snap.currentMachine).toBe(false)
    expect(snap.current?.gpuVramMb).toBeUndefined()
    expect(snap.current?.gpu).toBe(foreign.gpu)
    // The probe is still this machine's: the tile may show it beside the foreign result's own copy.
    expect(snap.currentGpu).toEqual({ name: RTX.name, totalMb: RTX.totalMb, useful: true })
  })

  it('the benchmark records the selected device as one pair; the profile bump follows ALL devices (G4)', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)

    const hybrid = await runAndPersistBenchmark(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => [IRIS, RTX]) }))
    expect(hybrid.gpu).toBe(RTX.name)
    expect(hybrid.gpuVramMb).toBe(RTX.totalMb)
    expect(hybrid.profile).toBe('PRO')
    // The probe write is stamped with this machine.
    expect(getSettings(db).gpuProbe).toMatchObject({ devices: [IRIS, RTX], machineKey: hereKey() })

    const igpu = await runAndPersistBenchmark(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => [IRIS]) }))
    // No budget device: the record names no card (the next start runs from RAM) and it bumps nothing.
    expect(igpu.gpu).toBeNull()
    expect(igpu.gpuVramMb).toBeNull()
    expect(igpu.profile).toBe('BALANCED')

    const none = await runAndPersistBenchmark(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => []) }))
    expect(none.gpu).toBeNull()
    expect(none.gpuVramMb).toBeNull()
  })
})

describe('probe identity (M8.3, G3)', () => {
  it('a probe stamped with ANOTHER machine supplies nothing: no fold-in, no currentGpu, no class beyond cpu, no budget', () => {
    const root = freshRoot()
    const db = seededDb(root)
    updateSettings(db, { lastBenchmark: legacyResult(), gpuProbe: probe([RTX], FOREIGN_KEY) })

    const snap = buildPerformanceSnapshot(ctxWith(root, db))

    expect(snap.currentGpu).toBeNull()
    expect(snap.current?.gpuVramMb).toBeUndefined()
    expect(snap.current?.gpu).toBeNull()
    expect(snap.placement.vramMb).toBeNull()
    expect(snap.placement.memoryClass).toBe('cpu')
    expect(snap.graphicsDevice).toBeNull() // the tile never names another machine's card (#327 class)
    // The raw settings still hold the devices — nothing was deleted, they are just not this machine's.
    expect(getSettings(db).gpuProbe).toEqual(probe([RTX], FOREIGN_KEY))
  })
})

describe('the probe write (probeAndPersistGpu, through "Try GPU again")', () => {
  /** What a push saw (A-D1): the flags as written by then, the probe as it stood. */
  const flagsAndProbe = (db: Db) => () => {
    const s = getSettings(db)
    return { gpuAutoDisabled: s.gpuAutoDisabled, gpuLastError: s.gpuLastError, gpuProbe: s.gpuProbe }
  }

  it('no binary for this OS: the probe never runs, yet an EMPTY probe stamped with THIS machine replaces the old one — the flag clear pushes first, the write pushes again (A-D1)', async () => {
    // The #303 P5 rule wrote nothing here so old devices were never re-stamped as local; merged
    // with #308 (decision 6, findings R3/R5) every path persists this session's answer: the empty
    // stamped result re-stamps no old device, and a stale SAME-machine card no longer survives a
    // refresh that could not see it (picker-seams.test.ts pins that case). "Try GPU again" pushes
    // as soon as it clears the flags (#303 P10, A-D1), so the sequence is TWO pushes: the first
    // sees the cleared flags and the untouched foreign probe, the second the empty stamped probe.
    const root = freshRoot()
    const db = seededDb(root)
    const foreign = probe([RTX], FOREIGN_KEY)
    updateSettings(db, { gpuProbe: foreign, gpuAutoDisabled: true, gpuLastError: 'Vulkan device lost' })
    const probeGpu = fakeGpuProbe([IRIS])
    const spy = performanceChangedSpy(flagsAndProbe(db))

    await tryGpuAgain(ctxWith(root, db, { probeGpu }))

    expect(probeGpu).not.toHaveBeenCalled()
    const written = getSettings(db).gpuProbe!
    expect(written.devices).toEqual([])
    expect(written.machineKey).toBe(hereKey())
    expect(Number.isNaN(new Date(written.probedAt).getTime())).toBe(false)
    expect(spy.mock.results.map((r) => r.value)).toEqual([
      { gpuAutoDisabled: false, gpuLastError: null, gpuProbe: foreign },
      { gpuAutoDisabled: false, gpuLastError: null, gpuProbe: written }
    ])
  })

  it('a rejecting probe: the same EMPTY stamped probe replaces the old devices (the old ones are never re-stamped as local) — the flag clear pushes first, the write pushes again (A-D1)', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const foreign = probe([RTX], FOREIGN_KEY)
    updateSettings(db, { gpuProbe: foreign, gpuAutoDisabled: true, gpuLastError: 'Vulkan device lost' })
    const spy = performanceChangedSpy(flagsAndProbe(db))

    await tryGpuAgain(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => { throw new Error('driver wedged') }) }))

    const written = getSettings(db).gpuProbe!
    expect(written.devices).toEqual([])
    expect(written.machineKey).toBe(hereKey())
    expect(spy.mock.results.map((r) => r.value)).toEqual([
      { gpuAutoDisabled: false, gpuLastError: null, gpuProbe: foreign },
      { gpuAutoDisabled: false, gpuLastError: null, gpuProbe: written }
    ])
  })

  it('an EMPTY result replaces the old devices with the current, stamped, empty probe — and pushes', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    updateSettings(db, { gpuProbe: probe([RTX], FOREIGN_KEY) })
    const spy = performanceChangedSpy(() => getSettings(db).gpuProbe)

    await tryGpuAgain(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => []) }))

    const written = getSettings(db).gpuProbe!
    expect(written.devices).toEqual([])
    expect(written.machineKey).toBe(hereKey())
    expect(Number.isNaN(new Date(written.probedAt).getTime())).toBe(false)
    // Pushed after the flag clear (the old probe still in place) and again after the write (A-D1).
    expect(spy.mock.results.map((r) => r.value)).toEqual([probe([RTX], FOREIGN_KEY), written])
  })

  // A-D1 through the SNAPSHOT the screen reads, not just the settings: the flag-clear push already
  // shows this machine's card re-armed (chat row 'gpu'); the probe write's push then shows it
  // gone, because a probe that cannot run persists the empty stamped answer (decision 6). Moved
  // here from performance-notify.test.ts (#656), where it read the class from the host.
  it.each<[label: string, binary: boolean, probeImpl: () => Promise<GpuDevice[]>]>([
    ['no binary for this OS (the probe is never called)', false, async () => [RTX]],
    [
      'a rejecting probe',
      true,
      async () => {
        throw new Error('driver wedged')
      }
    ]
  ])('"Try GPU again": the first push re-arms this machine’s card on the screen even when the probe cannot run — %s (A-D1)', async (_label, binary, probeImpl) => {
    const root = freshRoot()
    const db = seededDb(root)
    const before = probe([RTX], hereKey())
    updateSettings(db, { gpuProbe: before, gpuAutoDisabled: true, gpuLastError: 'Vulkan device lost' })
    if (binary) withLlamaBinary(root)
    const ctx = ctxWith(root, db, { probeGpu: fakeGpuProbe(probeImpl) })
    const chatDevice = (): string => buildPerformanceSnapshot(ctx).placement.models.find((r) => r.role === 'chat')!.device
    expect(chatDevice()).toBe('cpu') // the auto-disable forces the processor before the button
    const spy = performanceChangedSpy(() => ({ gpuAutoDisabled: getSettings(db).gpuAutoDisabled, chat: chatDevice() }))

    await tryGpuAgain(ctx)

    expect(spy.mock.results.map((r) => r.value)).toEqual([
      { gpuAutoDisabled: false, chat: 'gpu' },
      { gpuAutoDisabled: false, chat: 'cpu' }
    ])
    expect(getSettings(db).gpuProbe).toMatchObject({ devices: [], machineKey: hereKey() })
  })

  it('a probe-only refresh drops the cached answer first, then writes the devices stamped with this machine and pushes', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const spy = performanceChangedSpy()
    const probeGpu = fakeGpuProbe([IRIS, RTX])

    const settings = await tryGpuAgain(ctxWith(root, db, { probeGpu }))

    // "Try GPU again" is never answered from the session cache: invalidate() precedes the re-probe.
    expect(probeGpu.invalidate).toHaveBeenCalledTimes(1)
    expect(probeGpu.invalidate.mock.invocationCallOrder[0]).toBeLessThan(probeGpu.calls.mock.invocationCallOrder[0])
    expect(settings.gpuProbe).toMatchObject({ devices: [IRIS, RTX], machineKey: hereKey() })
    expect(spy).toHaveBeenCalledTimes(2) // the flag clear, then the write (A-D1)
  })

  it('a probe that resolves after the workspace locked writes nothing', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const before = probe([RTX], FOREIGN_KEY)
    updateSettings(db, { gpuProbe: before })
    let unlocked = true
    const pending = deferred<GpuDevice[]>()
    const ctx = ctxWith(root, db, {
      workspace: workspaceStandIn({ unlocked: () => unlocked }),
      probeGpu: fakeGpuProbe(() => pending.promise)
    })
    const spy = performanceChangedSpy()

    const run = tryGpuAgain(ctx)
    unlocked = false // "Lock now" completes while the driver is still enumerating
    pending.resolve([IRIS, RTX])
    await run

    expect(getSettings(db).gpuProbe).toEqual(before)
    expect(spy).toHaveBeenCalledTimes(1) // the flag clear, before the lock (A-D1); the late result adds nothing
  })

  it('a probe that outlives its workspace session (a lock AND a re-unlock) writes nothing', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const before = probe([RTX], FOREIGN_KEY)
    updateSettings(db, { gpuProbe: before })
    let epoch = 3
    const pending = deferred<GpuDevice[]>()
    const ctx = ctxWith(root, db, {
      workspace: workspaceStandIn({ epoch: () => epoch }),
      probeGpu: fakeGpuProbe(() => pending.promise)
    })
    const spy = performanceChangedSpy()

    const run = tryGpuAgain(ctx)
    epoch += 1 // locked and unlocked again: both flags read exactly as before, the epoch does not
    pending.resolve([IRIS, RTX])
    await run

    expect(getSettings(db).gpuProbe).toEqual(before)
    expect(spy).toHaveBeenCalledTimes(1) // the flag clear only (A-D1); the stale result adds nothing

    // The control: the same session, the same probe → written.
    const again = deferred<GpuDevice[]>()
    ctx.probeGpu = fakeGpuProbe(() => again.promise)
    const run2 = tryGpuAgain(ctx)
    again.resolve([IRIS, RTX])
    await run2
    expect(getSettings(db).gpuProbe).toMatchObject({ devices: [IRIS, RTX], machineKey: hereKey() })
    expect(spy).toHaveBeenCalledTimes(3) // + the flag clear and the write
  })

  // #380 — the ONE exception to decision 6. A probe that hits its 10 s kill-timeout resolves
  // `null`: not an answer but the absence of one. Persisting the empty stamped probe there is
  // exactly the #330 failure — the driver was busy with the weight upload, and a card machine
  // was recorded (tile "None"), classed from RAM and labelled "cpu" for the rest of the session.
  it('a TIMED-OUT probe on a machine with a stamped card: nothing is written, the stored probe stands', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const before = probe([RTX], hereKey())
    updateSettings(db, { gpuProbe: before, gpuAutoDisabled: true, gpuLastError: 'Vulkan device lost' })
    const spy = performanceChangedSpy(flagsAndProbe(db))

    await tryGpuAgain(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => null) }))

    expect(getSettings(db).gpuProbe).toEqual(before)
    // ONE push: the flag clear (A-D1). An unknown probe writes nothing, so it pushes nothing.
    expect(spy.mock.results.map((r) => r.value)).toEqual([
      { gpuAutoDisabled: false, gpuLastError: null, gpuProbe: before }
    ])
  })

  it('a benchmark whose probe timed out reports THIS machine’s card and leaves the probe untouched', async () => {
    // Decision 6 exists so the ★, the benchmark and the tile cannot disagree. With an unknown
    // probe they agree on the RECORD instead of on an empty answer nobody measured.
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const before = probe([RTX], hereKey())
    updateSettings(db, { gpuProbe: before })

    const result = await runAndPersistBenchmark(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => null) }))

    expect(result.gpu).toBe(RTX.name)
    expect(result.gpuVramMb).toBe(RTX.totalMb)
    expect(result.profile).toBe('PRO')
    expect(getSettings(db).gpuProbe).toEqual(before)
  })

  it('a TIMED-OUT probe over a FOREIGN-stamped record: still nothing written, and this machine still has no card', () => {
    // The stamp keeps doing its job: "unknown" never promotes another machine's devices to
    // local, it only declines to overwrite what is stored.
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const before = probe([RTX], FOREIGN_KEY)
    updateSettings(db, { gpuProbe: before, lastBenchmark: legacyResult() })

    return tryGpuAgain(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => null) })).then(() => {
      expect(getSettings(db).gpuProbe).toEqual(before)
      expect(buildPerformanceSnapshot(ctxWith(root, db)).currentGpu).toBeNull()
    })
  })

  it('a probe that gives NO answer after the workspace locked: no write, no push, an empty summary, and no false "probe failed" warning (#656)', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    const before = probe([RTX], hereKey())
    updateSettings(db, { gpuProbe: before })
    let unlocked = true
    const pending = deferred<GpuDevice[] | null>()
    const ctx = ctxWith(root, db, {
      workspace: workspaceStandIn({ unlocked: () => unlocked }),
      probeGpu: fakeGpuProbe(() => pending.promise)
    })
    // As in production, the database is out of reach once the lock completed.
    Object.defineProperty(ctx, 'db', {
      get: () => {
        if (!unlocked) throw new Error('Workspace is locked')
        return db
      }
    })
    const spy = performanceChangedSpy()
    const warn = vi.spyOn(log, 'warn')

    const run = probeAndPersistGpu(ctx)
    unlocked = false // "Lock now" completes while the driver is still enumerating…
    pending.resolve(null) // …and the probe then hits its kill-timeout (#380): unknown, not "no device"
    const summary = await run

    expect(summary).toMatchObject({ name: null, totalMb: null, useful: false })
    expect(spy).not.toHaveBeenCalled()
    // Nothing failed: the probe did not answer and the lock refused the read. Without the
    // admission check the settings read threw into the "GPU probe failed" path.
    expect(warn).not.toHaveBeenCalled()
    unlocked = true
    expect(getSettings(db).gpuProbe).toEqual(before)
  })
})

/**
 * A card machine with the 9B active and running, the translation sidecar live with 20/49 layers, and the real catalog.
 * The drive holds the 9B and every role's catalog model (presence-only stand-ins, #914), so every row counts in the
 * totals; `missing` leaves a role's files off the drive.
 */
function cardMachine(over: {
  settings?: Partial<AppSettings>
  translation?: TranslationDeviceStatus | null
  status?: RuntimeStatus
  placement?: Partial<ModelPlacement>
  /** #476: a fake `Reranker` — absent (the default) reports 'cpu', same as no reranker composed. */
  reranker?: { devicePosture?: () => 'gpu' | 'cpu'; isLoaded?: () => boolean }
  /** #914: roles whose catalog model is not on this drive. */
  missing?: readonly CatalogRole[]
} = {}): { placement: PerformanceSnapshot['placement']; db: Db; ctx: AppContext } {
  // Each machine starts from a clean session latch: a placement recorded for an earlier
  // machine in the same test must not count as this one's observation.
  resetModelPlacementForTests()
  const root = freshRoot()
  const roles: readonly CatalogRole[] = ['translation', 'vision', 'reranker', 'embeddings', 'transcriber']
  withCatalogFiles(root, { chat: CHAT, roles: roles.filter((role) => !over.missing?.includes(role)) })
  const db = seededDb(root)
  updateSettings(db, { lastBenchmark: hereResult(), activeModelId: CHAT, gpuProbe: probe([RTX], hereKey()), ...over.settings })
  const ctx = ctxWith(root, db, {
    reranker: over.reranker,
    manifestsDir: CATALOG_MANIFESTS,
    runtime: {
      occupancy: new ModelOccupancy(),
      active: () => ({ modelId: CHAT }),
      status: () => over.status ?? runtimeStatus({ modelId: CHAT, backend: 'gpu' })
    },
    translator: {
      deviceStatus: () =>
        over.translation === undefined ? { device: 'auto', gpuLayers: 20, totalLayers: 49, live: true } : over.translation
    }
  })
  if (over.placement) {
    // The launch context the snapshot resolves for the active model: a placement must carry it
    // to count as observed (the measured-evidence rule).
    const contextTokens = buildPerformanceSnapshot(ctx).placement.model?.contextTokens ?? 0
    recordModelPlacement(modelPlacement({ modelId: CHAT, contextTokens, machineKey: hereKey(), ...over.placement }))
  }
  return { placement: buildPerformanceSnapshot(ctx).placement, db, ctx }
}

const rowOf = (p: PerformanceSnapshot['placement'], role: ResidentModelRow['role']) =>
  p.models.find((r) => r.role === role)!

describe('capability is not execution (DR1)', () => {
  it('GPU on: chat and translation say gpu; bothOnCard needs chat resident on the GPU with layers and the translation live with layers', () => {
    const on = cardMachine({ placement: {} })
    expect(rowOf(on.placement, 'chat').device).toBe('gpu')
    // A live sidecar on the card carries its observed split.
    expect(rowOf(on.placement, 'translation')).toMatchObject({ device: 'gpu', gpuLayers: 20, totalLayers: 49 })
    expect(on.placement.totals.bothOnCard).toBe(true)
    // The estimate/measurement for the card, not the processor.
    expect(on.placement.verdict.kind).toBe('gpu')

    // A live translation sidecar at 0 offloaded layers is not on the card.
    expect(cardMachine({ placement: {}, translation: { device: 'auto', gpuLayers: 0, totalLayers: 49, live: true } }).placement.totals.bothOnCard).toBe(false)
    // A chat start observed at 0 layers, or with no reported split, is not on the card either.
    expect(cardMachine({ placement: { gpuLayers: 0 } }).placement.totals.bothOnCard).toBe(false)
    expect(cardMachine({ placement: { gpuLayers: null, totalLayers: null } }).placement.totals.bothOnCard).toBe(false)
    // No observation under a GPU-eligible configuration counts as on the card.
    expect(cardMachine().placement.totals.bothOnCard).toBe(true)
    // The chat model not resident: not both.
    expect(cardMachine({ status: { running: false, modelId: null, port: null, healthy: false, message: 'Stopped' } }).placement.totals.bothOnCard).toBe(false)
  })

  // #476: the Performance card summary line omitted a GPU-resident reranker — neither the
  // reranker row's own device nor `bothOnCard` (the contention warning) ever counted it.
  it('#476: a GPU-resident reranker is a THIRD source of bothOnCard, alongside chat/translation', () => {
    const withReranker = cardMachine({
      reranker: { devicePosture: () => 'gpu', isLoaded: () => true }
    })
    expect(rowOf(withReranker.placement, 'reranker').device).toBe('gpu')
    // Chat + translation ALREADY both on the card (the fixture's default) + a resident reranker:
    // still true (more than two on the card is still contention), never a miscount.
    expect(withReranker.placement.totals.bothOnCard).toBe(true)

    // Isolate the reranker's OWN contribution: chat/translation both OFF the card, reranker
    // alone resident on GPU — one source is not contention.
    const rerankerAlone = cardMachine({
      translation: null,
      status: { running: false, modelId: null, port: null, healthy: false, message: 'Stopped' },
      reranker: { devicePosture: () => 'gpu', isLoaded: () => true }
    })
    expect(rowOf(rerankerAlone.placement, 'reranker').device).toBe('gpu')
    expect(rerankerAlone.placement.totals.bothOnCard).toBe(false)

    // A reranker posture of 'gpu' that is NOT actually loaded (a cold start would take the GPU,
    // but nothing is resident there yet) does not count as "on the card" either.
    const rerankerColdOnly = cardMachine({
      translation: null,
      status: { running: false, modelId: null, port: null, healthy: false, message: 'Stopped' },
      reranker: { devicePosture: () => 'gpu', isLoaded: () => false }
    })
    expect(rerankerColdOnly.placement.totals.bothOnCard).toBe(false)

    // No reranker composed at all: the row still reports 'cpu' (the isLoaded?-pattern default),
    // byte-identical to before #476.
    const noReranker = cardMachine({})
    expect(rowOf(noReranker.placement, 'reranker').device).toBe('cpu')
    expect(noReranker.placement.totals.bothOnCard).toBe(true) // unchanged: chat + translation alone
  })

  // #495 follow-up: the reachable case the fix targets — a GPU
  // machine with no translation model installed (or its posture fallen back), chat AND the
  // reranker actually resident on the card. `bothOnCard` (the three-way contention flag) must
  // still be true, but `chatAndTranslationOnCard` — the ONE pair `perf.models.cardBoth`'s copy
  // is about — must be false, so the renderer never names a translation model that isn't there.
  it('#495 follow-up: chat on card + reranker on card + translation NOT on card -> bothOnCard true, chatAndTranslationOnCard false', () => {
    const chatAndReranker = cardMachine({
      translation: null,
      reranker: { devicePosture: () => 'gpu', isLoaded: () => true }
    })
    expect(rowOf(chatAndReranker.placement, 'chat').device).toBe('gpu')
    expect(rowOf(chatAndReranker.placement, 'reranker').device).toBe('gpu')
    expect(chatAndReranker.placement.totals.bothOnCard).toBe(true)
    expect(chatAndReranker.placement.totals.chatAndTranslationOnCard).toBe(false)

    // Sanity: the ordinary chat+translation-only fixture (no reranker override) still sets BOTH
    // flags true — the new field is a narrowing, not a behaviour change, when translation really
    // is on the card.
    expect(cardMachine({ placement: {} }).placement.totals.chatAndTranslationOnCard).toBe(true)
  })

  it.each([
    ["gpuMode 'off'", { gpuMode: 'off' as const }],
    ['gpuAutoDisabled', { gpuAutoDisabled: true }]
  ])("%s: both rows say cpu, the verdict is the processor estimate against RAM, bothOnCard is false — and the class is the NEXT start's, cpu", (_name, settings) => {
    const off = cardMachine({ settings })
    expect(rowOf(off.placement, 'chat').device).toBe('cpu')
    expect(rowOf(off.placement, 'translation').device).toBe('cpu')
    expect(off.placement.totals.bothOnCard).toBe(false)
    expect(off.placement.verdict.kind).not.toBe('gpu')
    expect(off.placement.verdict.estimated).toBe(true)
    expect(off.placement.verdict.budgetMb).toBe(off.placement.ramMb)
    // The #303 P5 rule kept the HARDWARE class here; merged with #308 (decision 6) the snapshot's
    // class and card describe the next start, which the switched-off card takes no part in —
    // the same answer `pickerMemoryFor` gives the Models ★ (the profile bump still follows the
    // hardware, `gpuUsefulForProfile`).
    expect(off.placement.memoryClass).toBe('cpu')
    expect(off.placement.vramMb).toBeNull()
  })

  // #671: the offload line is no evidence of a card. A forced `--device none` start and a GPU-posture
  // start with no usable device both print `offloaded 49/49 layers to GPU`, every buffer on the
  // processor: the row says processor, shows no "on the card" split, and counts in the RAM total.
  it.each([
    ['forced to --device none', { device: 'cpu', gpuLayers: 49, totalLayers: 49, live: true }],
    ['whose GPU-posture start put no buffer on a graphics device', { device: 'auto', gpuLayers: 49, totalLayers: 49, gpuBuffers: false, live: true }]
  ] as const)('a translation sidecar %s says cpu while chat keeps the card', (_name, translation) => {
    const tr = cardMachine({ placement: {}, translation })
    expect(rowOf(tr.placement, 'chat').device).toBe('gpu')
    expect(rowOf(tr.placement, 'translation')).toMatchObject({ device: 'cpu', gpuLayers: null, totalLayers: null })
    expect(tr.placement.totals.bothOnCard).toBe(false)
    const without = cardMachine({ placement: {}, translation: null })
    const sizeMb = (rowOf(tr.placement, 'translation').sizeOnDiskGb ?? 0) * 1024
    expect(Math.abs((tr.placement.totals.ramAllMb ?? 0) - (without.placement.totals.ramAllMb ?? 0) - sizeMb)).toBeLessThanOrEqual(1)
  })

  it('a matching start OBSERVED on the CPU backend puts the chat row on the processor and judges it against RAM', () => {
    const observedCpu = cardMachine({ placement: { backend: 'cpu', gpuLayers: null, totalLayers: null, gpuModelMb: null, gpuKvMb: null, cpuModelMb: 5900, cpuKvMb: 640 } })
    expect(rowOf(observedCpu.placement, 'chat').device).toBe('cpu')
    expect(rowOf(observedCpu.placement, 'translation').device).toBe('gpu')
    expect(observedCpu.placement.totals.bothOnCard).toBe(false)
    expect(observedCpu.placement.verdict).toMatchObject({ kind: 'cpu', estimated: false, budgetMb: observedCpu.placement.ramMb })
  })

  it('no usable card, GPU on: both rows say cpu and nothing counts as on the card', () => {
    // An integrated-only probe under 'auto' is a cpu CLASS without a forced configuration (`cpuForced`
    // false) — the rows still stay off the card (DR1).
    const none = cardMachine({ settings: { gpuProbe: probe([IRIS], hereKey()) } })
    expect(none.placement.memoryClass).toBe('cpu')
    expect(rowOf(none.placement, 'chat').device).toBe('cpu')
    // #671: a row that says processor claims no layers on the card, whatever the sidecar printed
    // (here a live 20/49 start, which on such a PC can only be the integrated GPU's).
    expect(rowOf(none.placement, 'translation')).toMatchObject({ device: 'cpu', gpuLayers: null, totalLayers: null })
    expect(none.placement.totals.bothOnCard).toBe(false)
  })
})

// #746: the class never read the flags on a Mac, and the rest of the snapshot took the class for
// "the next start uses the GPU", while the ladder skips rung 1 on any platform under those flags.
// Pinned, not run on a Mac: the real-hardware check is #332's.
describe('Apple Silicon: the GPU flags (#746)', () => {
  pinPlatform('darwin', 'arm64')
  const M2: GpuDevice = { id: 'Metal0', name: 'Apple M2 Pro', totalMb: 21_845, freeMb: 20_000 }
  const onMetal = (flags: Partial<AppSettings> = {}) =>
    cardMachine({ placement: {}, settings: { gpuProbe: probe([M2], hereKey()), ...flags } })

  it('GPU on: a start measured on Metal counts, and the row and the device say so', () => {
    const { placement: p, ctx } = onMetal()
    expect(p.memoryClass).toBe('unified')
    expect(p.observed?.backend).toBe('gpu')
    expect(p.observedMismatch).toBeNull()
    expect(p.verdict).toMatchObject({ kind: 'gpu', estimated: false })
    expect(rowOf(p, 'chat').device).toBe('gpu')
    expect(p.vramMb).toBe(M2.totalMb)
    expect(buildPerformanceSnapshot(ctx).currentGpu?.name).toBe(M2.name)
  })

  it.each([
    ["gpuMode 'off'", { gpuMode: 'off' as const }],
    ['gpuAutoDisabled', { gpuAutoDisabled: true }]
  ])('%s: the stored Metal record stops counting, the rows and the verdict go to the processor, and the pool stays unified', (_name, flags) => {
    const { placement: p, ctx } = onMetal(flags)
    // The memory is one pool either way: the tile keeps saying so.
    expect(p.memoryClass).toBe('unified')
    expect(p.observed).toBeNull()
    expect(p.observedMismatch?.backend).toBe('gpu')
    expect(rowOf(p, 'chat').device).toBe('cpu')
    expect(rowOf(p, 'translation')).toMatchObject({ device: 'cpu', gpuLayers: null, totalLayers: null })
    expect(p.verdict).toMatchObject({ kind: 'cpu', estimated: true, budgetMb: p.ramMb })
    // Nothing names a device the start will not use: Diagnostics reads `currentGpu` as "available".
    const snap = buildPerformanceSnapshot(ctx)
    expect(p.vramMb).toBeNull()
    expect(snap.currentGpu).toBeNull()
    expect(snap.graphicsDevice).toBeNull()
  })
})

describe('free/compute attribution to the selected device (DR2)', () => {
  const irisRow = { label: 'Vulkan0', name: IRIS.name, totalMb: 16_384, freeMb: 15_000, computeMb: 300 }
  const rtxRow = { label: 'Vulkan1', name: RTX.name, totalMb: 24_576, freeMb: 2703, computeMb: 2860 }

  /** An active model outside the catalog (context = the settings default) with a latched partial start. */
  function withLog(devices: ModelPlacement['devices'], probed: GpuDevice[]): PerformanceSnapshot['placement'] {
    const root = freshRoot()
    const db = seededDb(root)
    updateSettings(db, { lastBenchmark: hereResult(), activeModelId: 'some-model', gpuProbe: probe(probed, hereKey()) })
    const contextTokens = getSettings(db).contextTokens
    recordModelPlacement(
      modelPlacement({
        modelId: 'some-model', contextTokens, gpuLayers: 62, totalLayers: 66,
        gpuModelMb: 17_600, cpuModelMb: 1750, gpuKvMb: 512,
        // The legacy summary fields say what the FIRST row and the SUM would: the iGPU's free memory.
        gpuFreeAtStartMb: 15_000, gpuComputeMb: 3160, devices,
        machineKey: hereKey()
      })
    )
    return buildPerformanceSnapshot(ctxWith(root, db)).placement
  }

  it('a hybrid log: the figures are the selected dGPU’s, by name — never the first row’s', () => {
    const p = withLog([irisRow, rtxRow], [IRIS, RTX])
    expect(p.observed).not.toBeNull()
    expect(p.verdict).toMatchObject({ kind: 'partial', freeAtStartMb: 2703, workingMb: 2860, spillMb: 1750, budgetMb: RTX.totalMb })
  })
})

describe('everything loaded at once (DR5)', () => {
  it('discrete: the processor rows plus the observed chat spill and the live translation spill', () => {
    const { placement: p } = cardMachine({ placement: { gpuLayers: 30, totalLayers: 41, cpuModelMb: 1900, cpuKvMb: 200 } })
    expect(p.memoryClass).toBe('discrete')
    expect(p.verdict).toMatchObject({ kind: 'partial', estimated: false, spillMb: 2100 })
    const tr = rowOf(p, 'translation')
    const pinned = p.models.filter((r) => r.device === 'cpu').reduce((a, r) => a + (r.sizeOnDiskGb ?? 0) * 1024, 0)
    const translationSpill = (tr.sizeOnDiskGb ?? 0) * 1024 * (1 - 20 / 49)
    expect(p.totals.ramAllMb).toBe(Math.round(pinned + 2100 + translationSpill))
    // Chat weights on the card are NOT counted against RAM.
    expect(p.totals.ramAllMb).toBeLessThan(Math.round(p.models.reduce((a, r) => a + (r.sizeOnDiskGb ?? 0) * 1024, 0)))

    // GPU off: every row is on the processor → the plain sum again.
    const off = cardMachine({ settings: { gpuMode: 'off' } }).placement
    expect(off.totals.ramAllMb).toBe(Math.round(off.models.reduce((a, r) => a + (r.sizeOnDiskGb ?? 0) * 1024, 0)))
  })

  // A lite drive on a card machine: only the chat model is on the drive and it runs on the card. The total is 0
  // (the honest number); null is reserved for nothing installed. The screen leaves the line out for 0.
  it('discrete: a drive holding only the chat model totals 0, not null', () => {
    const { placement: p } = cardMachine({ missing: ['translation', 'vision', 'reranker', 'embeddings', 'transcriber'], translation: null })
    expect(p.memoryClass).toBe('discrete')
    expect(p.models.filter((r) => r.onDrive).map((r) => r.role)).toEqual(['chat'])
    expect(rowOf(p, 'chat').device).toBe('gpu')
    expect(p.verdict.kind).toBe('gpu')
    expect(p.totals.ramAllMb).toBe(0)
  })

  // #914 (owner decision G-5 (c)): no TranslateGemma, no image model and no ranking model on the drive; the index
  // model and voice are there. The missing rows still name the catalog's models (what translation would take on the
  // card, before downloading it), marked not on this drive, and the total leaves them out. The images and ranking
  // models run on the processor here (pinned by design; no reranker posture composed), so on the drive they count in
  // full on a card machine too. Nothing composes a translator or reranker, as on a real drive without them. The
  // ranking and index rows differ on purpose: each row reads its own model's files (#914 review N-1).
  it('#914: models not on this drive keep their rows, marked so, and add nothing to the total', () => {
    const full = cardMachine({ translation: null }).placement
    const { placement: p } = cardMachine({ translation: null, missing: ['translation', 'vision', 'reranker'] })
    expect(p.memoryClass).toBe('discrete')
    expect(rowOf(p, 'translation')).toMatchObject({ modelId: 'translategemma-12b-it-q4', onDrive: false })
    expect(rowOf(p, 'vision')).toMatchObject({ modelId: 'qwen2.5-vl-3b-instruct-q4', onDrive: false, device: 'cpu' })
    expect(rowOf(p, 'reranker')).toMatchObject({ modelId: 'bge-reranker-v2-m3-f16', onDrive: false, device: 'cpu' })
    expect(p.models.filter((r) => !r.onDrive).map((r) => r.role)).toEqual(['translation', 'vision', 'reranker'])
    const pinnedMb = ((rowOf(full, 'vision').sizeOnDiskGb ?? 0) + (rowOf(full, 'reranker').sizeOnDiskGb ?? 0)) * 1024
    expect(rowOf(full, 'reranker').device).toBe('cpu')
    expect(pinnedMb).toBeGreaterThan(0)
    expect(Math.abs((full.totals.ramAllMb ?? 0) - (p.totals.ramAllMb ?? 0) - pinnedMb)).toBeLessThanOrEqual(1)
  })
})

describe('"Try GPU again" and the session latches (#182, #372)', () => {
  it('re-arms the #182 speculative latch but LEAVES the #372 unloadable-model latch alone', async () => {
    // "Try GPU again" is about the graphics card. A model no rung could load is not a card
    // problem, so this button is not its reset — verify / re-download / engine install are.
    const root = freshRoot()
    const db = seededDb(root)
    suppressSpeculative('m')
    latchModelLoad('m', 'unknown model architecture')
    try {
      await tryGpuAgain(ctxWith(root, db, { probeGpu: fakeGpuProbe(async () => [RTX]) }))
      expect(isSpeculativeSuppressed('m')).toBe(false)
      expect(modelLoadLatchReason('m')).toBe('unknown model architecture')
    } finally {
      // module state: never leak into a later case (the speculative one too, if tryGpuAgain threw)
      clearModelLoadLatches()
      clearSpeculativeSuppression()
    }
  })

  it('re-arms the speculative latch BEFORE it re-probes, so a start landing during the probe gets the fast path', async () => {
    const root = freshRoot()
    const db = seededDb(root)
    withLlamaBinary(root)
    suppressSpeculative('m')
    const atProbe: boolean[] = []
    try {
      await tryGpuAgain(ctxWith(root, db, {
        probeGpu: fakeGpuProbe(async () => {
          atProbe.push(isSpeculativeSuppressed('m'))
          return [RTX]
        })
      }))
      expect(atProbe).toEqual([false])
    } finally {
      clearSpeculativeSuppression()
    }
  })
})