AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { execFileSync } from 'node:child_process'
import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
// The Performance screen's push model (PR #303 audit remediation P3, owner decisions G2/G6;
// benchmark.md "Performance screen" → "Data path"):
// - the IPC controls: `benchmark:run` streams its steps to the requesting window only, and a
// destroyed one never blocks the run;
// - the ordering contract: the progress 'done' step precedes the persist and the occupancy
// release, and the terminal `performance:changed` follows BOTH (it is the idle signal);
// - the notifier itself: every send isolated (a destroyed window, a throwing recipient, a
// throwing sink) and never a participant in the mutation that triggered it;
// - every emit site: run start/end (a refused run emits nothing; the failed-run push is
// first-benchmark-scheduler's), accepted read-speed samples (including a ranked loser), the
// answer latch, a placement observation, the upgrade seed (after the empty-probe write; the
// restore's push is first-benchmark-scheduler's), chat-runtime transitions, resident-sidecar
// transitions, and the settings keys the snapshot reads. The GPU probe write and "Try GPU
// again"'s flag-clear push are owned by performance-gpu.test.ts "the probe write", which
// asserts each push's value (#656); the translation and vision runtimes' own flips by their
// suites, `initBackend`'s subscriptions by answer-speed-wiring.test.ts (#747);
// - the `performance_get` mark, through the script that reads it (#333).
const electronState = vi.hoisted(() => ({
handlers: new Map<string, (...args: any[]) => any>(),
windows: [] as Array<{
isDestroyed: () => boolean
webContents: { isDestroyed: () => boolean; send: (...args: unknown[]) => void }
}>
}))
vi.mock('electron', () => ({
ipcMain: {
handle: (key: string, fn: (...args: any[]) => any) => electronState.handlers.set(key, fn),
removeHandler: (key: string) => electronState.handlers.delete(key)
},
app: { getVersion: () => '0.0.0-test' },
clipboard: { writeText: () => undefined },
BrowserWindow: { getAllWindows: () => electronState.windows }
}))
import {
buildPerformanceSnapshot,
observeAnswerSpeed,
registerBenchmarkIpc,
runAndPersistBenchmark
} from '../../src/main/ipc/registerBenchmarkIpc'
import { persistEffectiveRead, registerModelIpc } from '../../src/main/ipc/registerModelIpc'
import { registerCoreIpc } from '../../src/main/ipc/registerCoreIpc'
import { notifyPerformanceChanged, setPerformanceChangedSink } from '../../src/main/ipc/performance-notify'
import { E5Embedder } from '../../src/main/services/embeddings/e5'
import { LlamaReranker } from '../../src/main/services/reranker/llama'
import { initPerf } from '../../src/main/services/perf'
import { latestAnswerSpeed } from '../../src/main/services/performance'
import { latestEffectiveRead, recordChecksumRead } from '../../src/main/services/read-speed'
import { RuntimeManager } from '../../src/main/services/runtime'
import type { ModelRuntime, RuntimeStartOptions } from '../../src/main/services/runtime'
import { recordModelPlacement } from '../../src/main/services/runtime/placement'
import { getSettings, updateSettings } from '../../src/main/services/settings'
import { VisionService, type VisionAnalyzer, type VisionStreamEmitter } from '../../src/main/services/vision'
import { EVENTS, IPC } from '../../src/shared/ipc'
import type { AppSettings, BenchmarkProgressStep, ImageAnalyzeRequest, PerformanceSnapshot, VisionStatus } from '../../src/shared/types'
import { modelPlacement } from '../helpers/benchmark-records'
import { fakeSpawn } from '../helpers/fake-sidecar'
import { invoke, makeEvent } from '../helpers/ipc'
import {
CARDS,
CATALOG_MANIFESTS,
closePerformanceFixture,
ctxWith,
firstBenchmarkNow,
freshRoot,
hereKey,
hereResult,
loadSample,
performanceChangedSpy,
pinPlatform,
seededDb,
writeChatManifest
} from '../helpers/performance-fixture'
import { hangBudgetMs } from '../helpers/hang-budget'
import { sha256, writeDriveFile } from '../helpers/manifest-fixtures'
import { createSettingsHashStore } from '../../src/main/services/models'
import { createModelStartCheck } from '../../src/main/services/model-start-check'
const here = () => {
const root = freshRoot()
const db = seededDb(root)
const ctx = ctxWith(root, db)
return { db, ctx }
}
beforeEach(() => {
electronState.handlers.clear()
electronState.windows.length = 0
})
// TH2: every root/DB here is minted through the fixture's `freshRoot`/`seededDb` (via this
// file's own `here()` helper), and the shared teardown resets the session latches and observers.
afterEach(closePerformanceFixture)
describe('IPC controls', () => {
it('benchmark:run streams its steps to the requesting window; performance:get then returns that result', async () => {
const { ctx } = here()
registerBenchmarkIpc(ctx)
const event = makeEvent()
const fresh = await electronState.handlers.get(IPC.runBenchmark)!(event)
expect(event.sender.send.mock.calls).toEqual(
(['system', 'drive', 'done'] as BenchmarkProgressStep[]).map((s) => [EVENTS.benchmarkProgress, s])
)
const snap = electronState.handlers.get(IPC.getPerformance)!(makeEvent())
expect(snap.current.ranAt).toBe(fresh.ranAt)
expect(snap.running).toBe(false)
})
it('a destroyed requesting window gets no steps; the run still completes and persists', async () => {
const { ctx, db } = here()
registerBenchmarkIpc(ctx)
const event = makeEvent()
event.sender.destroy()
const fresh = await electronState.handlers.get(IPC.runBenchmark)!(event)
expect(event.sender.send).not.toHaveBeenCalled()
expect(getSettings(db).lastBenchmark?.ranAt).toBe(fresh.ranAt)
})
it("'done' precedes the persist and the release; performance:changed follows both (the idle signal)", async () => {
const { ctx, db } = here()
const held = () => ctx.runtime.occupancy.held('benchmark')
const persisted = () => getSettings(db).lastBenchmark !== null
const spy = performanceChangedSpy(() => ({ held: held(), persisted: persisted() }))
const atDone: Array<{ held: boolean; persisted: boolean; pushes: number }> = []
await runAndPersistBenchmark(ctx, (step) => {
if (step === 'done') atDone.push({ held: held(), persisted: persisted(), pushes: spy.mock.calls.length })
})
// At 'done' the probes are complete but nothing is persisted, the span is still held, and
// only the run-start push and the GPU-probe write's push have gone out (a root without a
// binary persists an EMPTY probe, PR #308 decision 6, and every probe write pushes).
expect(atDone).toEqual([{ held: true, persisted: false, pushes: 2 }])
// The pushes bracket the run: start (span held, nothing persisted), the probe write (same
// state) and idle (both done).
expect(spy.mock.results.map((r) => r.value)).toEqual([
{ held: true, persisted: false },
{ held: true, persisted: false },
{ held: false, persisted: true }
])
expect(buildPerformanceSnapshot(ctx).running).toBe(false)
})
})
describe('the notifier', () => {
it('default broadcast: a destroyed window is skipped, a throwing one never blocks the next, the live one gets the event', () => {
const live = { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: vi.fn() } }
const gone = { isDestroyed: () => false, webContents: { isDestroyed: () => true, send: vi.fn() } }
const closed = { isDestroyed: () => true, webContents: { isDestroyed: () => false, send: vi.fn() } }
const broken = {
isDestroyed: () => false,
webContents: {
isDestroyed: () => false,
send: vi.fn(() => {
throw new Error('render frame gone')
})
}
}
electronState.windows.push(gone, closed, broken, live)
expect(() => notifyPerformanceChanged()).not.toThrow()
expect(live.webContents.send).toHaveBeenCalledWith(EVENTS.performanceChanged)
expect(broken.webContents.send).toHaveBeenCalledTimes(1)
expect(gone.webContents.send).not.toHaveBeenCalled()
expect(closed.webContents.send).not.toHaveBeenCalled()
})
it('a throwing sink never blocks the persist it follows', async () => {
const { ctx, db } = here()
setPerformanceChangedSink(() => {
throw new Error('sink exploded')
})
const fresh = await runAndPersistBenchmark(ctx)
expect(getSettings(db).lastBenchmark?.ranAt).toBe(fresh.ranAt)
expect(ctx.runtime.occupancy.held('benchmark')).toBe(false)
})
it('a refused second run pushes nothing and leaves the first span held', async () => {
const { ctx } = here()
const release = ctx.runtime.occupancy.begin('benchmark') // the "first run"
const spy = performanceChangedSpy()
try {
await expect(runAndPersistBenchmark(ctx)).rejects.toThrow()
expect(spy).not.toHaveBeenCalled()
expect(ctx.runtime.occupancy.held('benchmark')).toBe(true)
} finally {
release()
}
})
})
describe('read-speed samples', () => {
it('a model load then a checksum: both push; the checksum fills its own row while the ranked latch and the persisted sample stay the model load', () => {
const { ctx, db } = here()
const mine = hereResult()
updateSettings(db, { lastBenchmark: mine, benchmarkHistory: [mine] })
registerModelIpc(ctx)
const spy = performanceChangedSpy()
loadSample('load')
expect(spy).toHaveBeenCalledTimes(1)
recordChecksumRead(3_000_000_000, 30_000, 'check')
expect(spy).toHaveBeenCalledTimes(2)
expect(latestEffectiveRead()?.modelId).toBe('load')
const s = getSettings(db)
expect(s.lastBenchmark?.effectiveRead?.modelId).toBe('load')
expect(s.benchmarkHistory[0].effectiveRead?.modelId).toBe('load')
const observed = buildPerformanceSnapshot(ctx).observed
expect(observed.lastModelLoad?.modelId).toBe('load')
expect(observed.lastChecksum?.modelId).toBe('check')
})
it('a retry persist pushes only when it actually wrote', () => {
const { ctx, db } = here()
updateSettings(db, { lastBenchmark: hereResult() })
const spy = performanceChangedSpy()
persistEffectiveRead(ctx) // nothing latched yet
expect(spy).not.toHaveBeenCalled()
loadSample('load') // no observer registered: latched only
persistEffectiveRead(ctx) // the post-start/list/verify retry writes it
expect(spy).toHaveBeenCalledTimes(1)
expect(getSettings(db).lastBenchmark?.effectiveRead?.modelId).toBe('load')
persistEffectiveRead(ctx) // the memo hit: no write, no push
expect(spy).toHaveBeenCalledTimes(1)
})
})
describe('session latches', () => {
it('a finished answer latches with the running model and pushes', () => {
const { ctx } = here()
ctx.runtime.active = () => ({ modelId: 'chat-model' }) as ModelRuntime
const spy = performanceChangedSpy()
observeAnswerSpeed(ctx, { messageId: 'a', tokensPerSecond: 12.5, ttftMs: 800, tokens: 100 })
expect(latestAnswerSpeed()).toMatchObject({ tokensPerSecond: 12.5, ttftMs: 800, tokens: 100, modelId: 'chat-model' })
expect(spy).toHaveBeenCalledTimes(1)
})
it('a placement observation pushes after its persist — and still pushes when the persist is skipped (locked)', () => {
const { ctx, db } = here()
registerBenchmarkIpc(ctx)
const spy = performanceChangedSpy(() => getSettings(db).modelPlacements['m']?.contextTokens ?? null)
const placement = modelPlacement({ modelId: 'm', contextTokens: 4096, machineKey: null, at: '2026-09-05T00:00:00Z' })
recordModelPlacement(placement)
expect(spy.mock.results.map((r) => r.value)).toEqual([4096]) // persisted BEFORE the push
ctx.workspace.isUnlocked = () => false
recordModelPlacement({ ...placement, contextTokens: 8192 })
expect(spy).toHaveBeenCalledTimes(2)
expect(getSettings(db).modelPlacements['m'].contextTokens).toBe(4096) // not persisted while locked
})
})
describe('seed writes', () => {
it('the same-machine upgrade seed pushes once, after the empty-probe write', async () => {
const { ctx, db } = here()
updateSettings(db, { lastBenchmark: hereResult() })
const spy = performanceChangedSpy(() => getSettings(db).benchmarkHistory.length)
await expect(firstBenchmarkNow(ctx)).resolves.toBe('not-needed')
// [empty-probe write (history still empty), seed]
expect(spy.mock.results.map((r) => r.value)).toEqual([0, 1])
})
})
describe('the chat runtime', () => {
const opts: RuntimeStartOptions = { modelId: 'm', modelPath: '/w.gguf', contextTokens: 2048 }
const fake = (over: Partial<ModelRuntime> = {}): ModelRuntime => ({
modelId: 'm',
start: async () => {},
stop: async () => {},
health: async () => ({ healthy: true, message: '', port: 1 }),
chatStream: async function* () {},
...over
})
const summary = (mgr: RuntimeManager) => {
const s = mgr.status()
return { running: s.running, starting: s.startingModelId ?? null }
}
it('pushes on starting, ready and stopped, with status() already reflecting each', async () => {
const mgr = new RuntimeManager(() => fake())
const seen: Array<ReturnType<typeof summary>> = []
const off = mgr.onChange(() => seen.push(summary(mgr)))
await mgr.start(opts)
expect(seen).toEqual([
{ running: false, starting: 'm' }, // admitted
{ running: true, starting: null }, // committed (ready)
{ running: true, starting: null } // the start window closed
])
await mgr.stop()
expect(seen.at(-1)).toEqual({ running: false, starting: null })
off()
await mgr.start(opts)
expect(seen).toHaveLength(4)
})
it('a failed start pushes starting then stopped; a throwing listener never fails the start', async () => {
const failing = fake({
start: async () => {
throw new Error('health timeout')
}
})
const mgr = new RuntimeManager(() => failing)
const seen: Array<ReturnType<typeof summary>> = []
mgr.onChange(() => {
throw new Error('listener exploded')
})
mgr.onChange(() => seen.push(summary(mgr)))
await expect(mgr.start(opts)).rejects.toThrow(/health timeout/)
expect(seen).toEqual([
{ running: false, starting: 'm' },
{ running: false, starting: null }
])
const ok = new RuntimeManager(() => fake())
ok.onChange(() => {
throw new Error('listener exploded')
})
await expect(ok.start(opts)).resolves.toMatchObject({ running: true })
})
})
describe('resident sidecars', () => {
const fetchFor = (route: string, body: unknown): typeof fetch =>
(async (url: string | URL) => {
const u = String(url)
if (u.endsWith('/health')) return { ok: true, status: 200 } as Response
if (u.endsWith(route)) return { ok: true, status: 200, json: async () => body } as Response
throw new Error(`unexpected url ${u}`)
}) as typeof fetch
const base = { binPath: '/bin/llama-server', modelPath: '/models/x.gguf', findPort: async () => 52000, healthIntervalMs: 1 }
it('the embedder pushes when its sidecar lands and when it is suspended', async () => {
const embedder = new E5Embedder({
...base,
id: 'e5',
dimensions: 2,
spawn: fakeSpawn().spawn,
fetchImpl: fetchFor('/v1/embeddings', { data: [{ embedding: [3, 4], index: 0 }] })
})
const seen: boolean[] = []
embedder.onResidencyChange(() => seen.push(embedder.isLoaded()))
await embedder.embed(['hello'])
expect(seen).toEqual([true])
await embedder.suspend()
expect(seen).toEqual([true, false])
await embedder.stop() // nothing resident: no flip, no push
expect(seen).toEqual([true, false])
})
it('the reranker pushes the same way', async () => {
const reranker = new LlamaReranker({
...base,
id: 'rr',
spawn: fakeSpawn().spawn,
fetchImpl: fetchFor('/v1/rerank', { results: [{ index: 0, relevance_score: 0.9 }] })
})
const seen: boolean[] = []
reranker.onResidencyChange(() => seen.push(reranker.isLoaded()))
await reranker.rerank('q', ['doc'])
expect(seen).toEqual([true])
await reranker.stop()
expect(seen).toEqual([true, false])
})
it("the vision service forwards its runtime's flips", async () => {
const AVAILABLE: VisionStatus = { available: true, modelId: 'vlm', modelDisplayName: 'VLM' }
let fire: (() => void) | null = null
const analyzer: VisionAnalyzer = {
analyze: async () => 'a bar chart',
onResidencyChange: (cb) => {
fire = cb
return () => {
fire = null
}
}
}
const service = new VisionService({ getStatus: async () => AVAILABLE, createRuntime: () => analyzer, isWorkspaceLocking: () => false, checkModel: async () => 'ok' })
const pushes = vi.fn()
service.onResidencyChange(pushes)
const emit: VisionStreamEmitter = { token: vi.fn(), done: vi.fn(), error: vi.fn() }
const req: ImageAnalyzeRequest = {
imageBytes: new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2]),
mimeType: 'image/png',
question: 'what is in this image'
}
service.analyze(req, emit)
await vi.waitFor(() => expect(emit.done).toHaveBeenCalled(), { timeout: hangBudgetMs(5000) })
expect(fire).not.toBeNull()
fire!()
expect(pushes).toHaveBeenCalledTimes(1)
})
})
describe('settings keys the snapshot reads', () => {
it('selecting a model pushes (models:select)', async () => {
const { ctx } = here()
ctx.manifestsDir = CATALOG_MANIFESTS
registerModelIpc(ctx)
const spy = performanceChangedSpy()
await invoke(electronState.handlers, IPC.selectModel, 'qwen3.5-9b-ud-q4kxl')
expect(spy).toHaveBeenCalledTimes(1)
})
describe('through settings:update', () => {
pinPlatform('win32', 'x64') // the `gpuMode` row reads the class, which reads the platform
/** A card machine whose active model is outside the catalog, so its context is the settings default. */
function snapshotInputs() {
const { ctx, db } = here()
updateSettings(db, { activeModelId: 'some-model', gpuProbe: { devices: [CARDS.RTX_3090], probedAt: '2026-09-05T00:00:00Z', machineKey: hereKey() } })
registerCoreIpc(ctx)
return ctx
}
const context = (s: PerformanceSnapshot): unknown => s.placement.model?.contextTokens
// Each row reads the figure the key moves: a key that stops feeding the snapshot fails here, so
// this is no copy of PERFORMANCE_SETTINGS_KEYS. The active slots are main-owned since #868: they
// move through `models:select` / `runtime:use` (the row above), never through this channel.
it.each<[keyof AppSettings, Partial<AppSettings>, (s: PerformanceSnapshot) => unknown]>([
['contextTokens', { contextTokens: 2048 }, context],
['contextTokensOverride', { contextTokensOverride: 16_384 }, context],
['gpuMode', { gpuMode: 'off' }, (s) => s.placement.memoryClass]
])('%s moves the snapshot, and the patch pushes after the write', async (_key, patch, figure) => {
const ctx = snapshotInputs()
const before = figure(buildPerformanceSnapshot(ctx))
const spy = performanceChangedSpy(() => figure(buildPerformanceSnapshot(ctx)))
await invoke(electronState.handlers, IPC.updateSettings, patch)
expect(spy).toHaveBeenCalledTimes(1)
expect(spy.mock.results[0].value).not.toEqual(before)
})
it('a patch of anything else stays silent: the screen has no interest in the language', async () => {
snapshotInputs()
const spy = performanceChangedSpy()
await invoke(electronState.handlers, IPC.updateSettings, { uiLanguage: 'en' })
expect(spy).not.toHaveBeenCalled()
})
})
})
// #333: the figure `scripts/measure-manifest-read.mjs --log` reports is the time a renderer waits on
// `performance:get`, split by the `discover_manifests` line right before it. The script pairs the two
// on adjacency alone, so the row reads the log with the script.
describe('the performance_get mark', () => {
const dirs: string[] = []
afterEach(() => {
vi.unstubAllEnvs()
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
it('each read leaves its mark right behind its manifest scan, in the shape the --log script reads', async () => {
vi.stubEnv('HILBERTRAUM_PERF_LOG', '1')
const dir = mkdtempSync(join(tmpdir(), 'hilbertraum-perf-mark-'))
dirs.push(dir)
initPerf(dir)
const { ctx } = here()
ctx.manifestsDir = CATALOG_MANIFESTS
registerBenchmarkIpc(ctx)
await invoke(electronState.handlers, IPC.getPerformance)
await invoke(electronState.handlers, IPC.getPerformance)
const script = join(__dirname, '..', '..', '..', '..', 'scripts', 'measure-manifest-read.mjs')
const report = execFileSync(process.execPath, ['--no-warnings', script, '--log', join(dir, 'perf.log')], { encoding: 'utf8' })
expect(report).toContain('2 performance_get · 0 scans by other callers')
expect(report).toContain('of which: manifest scan')
})
})
// #959: a file check that changes a verdict pushes the Performance refresh, once per pass. The files here
// are tiny (under the 64 MiB the read-speed observer needs for a sample), so the observer's own push stays silent
// and every push counted below comes from the verdict diff.
describe('a file check that changes a verdict (#959)', () => {
const GOOD = 'the bytes the manifest expects'
const BAD = GOOD.toUpperCase() // same length: a "put back from a backup" file keeps its size
/** A chat model whose manifest hash is of GOOD; its weight holds `content` (BAD: a check finds it damaged). */
function chatModel(root: string, id: string, content: string): string {
writeChatManifest(join(root, 'model-manifests'), {
id,
display_name: id,
size_on_disk_gb: 1,
recommended_min_ram_gb: 1,
recommended_ram_gb: 1,
local_path: `models/chat/${id}.gguf`,
sha256: sha256(GOOD)
})
writeDriveFile(root, `models/chat/${id}.gguf`, content)
return join(root, 'models', 'chat', `${id}.gguf`)
}
function withModels(models: Record<string, string>) {
const { ctx, db } = here()
const root = ctx.paths.rootPath
const files = Object.fromEntries(Object.entries(models).map(([id, content]) => [id, chatModel(root, id, content)]))
ctx.manifestsDir = join(root, 'model-manifests')
;(ctx.runtime as unknown as { activeModelId: () => string | null }).activeModelId = () => null
registerModelIpc(ctx)
return { ctx, db, files }
}
const listModels = (lazy?: boolean, runId?: string, event = makeEvent()) =>
electronState.handlers.get(IPC.listModels)!(event, lazy, runId)
const verifyModel = (id: string) => electronState.handlers.get(IPC.verifyModel)!(makeEvent(), id)
it('a full pass that finds a file damaged pushes once; the next pass, which only reads the cache, pushes nothing', async () => {
withModels({ 'chat-a': BAD, 'chat-b': GOOD })
const spy = performanceChangedSpy()
await listModels()
expect(spy).toHaveBeenCalledTimes(1)
await listModels()
expect(spy).toHaveBeenCalledTimes(1)
})
it('a full pass over intact files pushes nothing', async () => {
withModels({ 'chat-a': GOOD, 'chat-b': GOOD })
const spy = performanceChangedSpy()
await listModels()
expect(spy).not.toHaveBeenCalled()
})
it('a lazy pass pushes when it hashes the active model and finds it damaged, and not again', async () => {
const { db } = withModels({ 'chat-a': BAD, 'chat-b': BAD })
updateSettings(db, { activeModelId: 'chat-a' })
const spy = performanceChangedSpy()
await listModels(true)
expect(spy).toHaveBeenCalledTimes(1)
await listModels(true)
expect(spy).toHaveBeenCalledTimes(1)
})
it('a pass cancelled after it found one file damaged still pushes once', async () => {
withModels({ 'chat-a': BAD, 'chat-b': GOOD })
const spy = performanceChangedSpy()
const event = makeEvent()
// The second hashing model's first progress event is the moment chat-a is done: cancel there.
event.sender.send.mockImplementation((_channel: string, p: { modelId?: string; runId?: string }) => {
if (p?.modelId === 'chat-b') void electronState.handlers.get(IPC.cancelModelVerify)!(makeEvent(), p.runId)
})
await listModels(false, 'run-1', event)
expect(spy).toHaveBeenCalledTimes(1)
})
it('Verify checksum pushes when it finds a damaged file, again when a put-back file makes it intact, and not when nothing changes', async () => {
const { ctx, db, files } = withModels({ 'chat-a': BAD })
const spy = performanceChangedSpy()
await verifyModel('chat-a') // nothing known -> damaged
expect(spy).toHaveBeenCalledTimes(1)
await verifyModel('chat-a') // still damaged: the same verdict
expect(spy).toHaveBeenCalledTimes(1)
// The good file is put back (a restore from a backup) and the cache still holds the old mismatch for its
// size and mtime: the stale entry that only a forced re-hash clears.
writeFileSync(files['chat-a'], GOOD)
const st = statSync(files['chat-a'])
createSettingsHashStore(() => db, ctx.paths.rootPath).set(files['chat-a'], {
size: st.size,
mtimeMs: st.mtimeMs,
actual: sha256(BAD)
})
await verifyModel('chat-a') // damaged -> intact, which only a capture BEFORE the invalidate can see
expect(spy).toHaveBeenCalledTimes(2)
await verifyModel('chat-a') // intact again
expect(spy).toHaveBeenCalledTimes(2)
})
describe('the start check of the search and voice models', () => {
function startCheck(models: Record<string, string>) {
const { ctx, db } = withModels(models)
const onVerdictChanged = vi.fn()
const check = createModelStartCheck({
manifestsDir: ctx.manifestsDir,
paths: ctx.paths,
isDev: true,
getSettings: () => getSettings(db),
getDb: () => db,
onVerdictChanged
})
return { check, onVerdictChanged }
}
it('calls onVerdictChanged once when a hashing check finds a file damaged, and not for the same check again', async () => {
const { check, onVerdictChanged } = startCheck({ 'chat-a': BAD })
await expect(check('chat-a', { hash: true })).resolves.toBe('damaged')
expect(onVerdictChanged).toHaveBeenCalledTimes(1)
await expect(check('chat-a', { hash: true })).resolves.toBe('damaged')
expect(onVerdictChanged).toHaveBeenCalledTimes(1)
})
it('stays silent when the check finds the file intact', async () => {
const { check, onVerdictChanged } = startCheck({ 'chat-ok': GOOD })
await expect(check('chat-ok', { hash: true })).resolves.toBe('ok')
expect(onVerdictChanged).not.toHaveBeenCalled()
})
})
})