Skip to content

AI, fully local on your computer.

21.3 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import { EventEmitter } from 'node:events'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'

// #530 "Check again" (`recheckEngines` / `rearmLlamaConsumers`) over a minimal fake AppContext.
// Electron is mocked only because the re-check's import graph reaches the model IPC registrar.
vi.mock('electron', () => ({
  ipcMain: { handle: () => undefined, removeHandler: () => undefined },
  app: { getVersion: () => '0.0.0-test' },
  BrowserWindow: { getAllWindows: () => [], getFocusedWindow: () => null }
}))

import type { AppContext } from '../../src/main/services/context'
import type { EngineProblem } from '../../src/shared/types'
import { openDatabase, type Db } from '../../src/main/services/db'
import { rearmLlamaConsumers, rearmWhenChatEngineHeals, recheckEngines } from '../../src/main/ipc/engine-recheck'
import {
  clearEngineProblemFor,
  engineProblemFor,
  reportEngineProblem,
  resetEngineProblemsForTest
} from '../../src/main/services/runtime/engine-load'
import { clearModelLoadLatches, latchModelLoad, modelLoadLatchReason } from '../../src/main/services/runtime/factory'
import {
  LlamaServer,
  llamaOsDir,
  llamaServerBinaryName,
  type ChildProcessLike,
  type SpawnFn
} from '../../src/main/services/runtime/sidecar'
import { whisperCliBinaryName } from '../../src/main/services/transcriber/cli'
import { getSettings, seedSettings, updateSettings } from '../../src/main/services/settings'
import { workspaceStandIn } from '../helpers/workspace-stand-in'
import { hangBudgetMs } from '../helpers/hang-budget'

const LLAMA_PROBLEM: EngineProblem = {
  family: 'llama_cpp',
  reason: 'library-missing',
  os: 'linux',
  name: 'libgomp.so.1',
  exit: 'exit code 127'
}
const WHISPER_PROBLEM: EngineProblem = { ...LLAMA_PROBLEM, family: 'whisper_cpp' }
// The programs the verdicts were reported against (any path: the re-check resolves the drive's own).
const REFUSED_LLAMA = '/drive/runtime/llama.cpp/linux/llama-server'
const REFUSED_WHISPER = '/drive/runtime/whisper.cpp/linux/whisper-cli'

const dirs: string[] = []
const dbs: Db[] = []

const cpuNetBin = (root: string): string => join(root, 'runtime', 'llama.cpp', llamaOsDir(), 'cpu', llamaServerBinaryName())

/** `cpuNet` (#678): the chat engine's `cpu/` safety net too, as on a prepared Kit. */
function driveRoot(opts: { llama?: boolean; whisper?: boolean; cpuNet?: boolean } = {}): string {
  const root = mkdtempSync(join(tmpdir(), 'hilbertraum-recheck-'))
  dirs.push(root)
  const put = (family: string, bin: string): void => {
    const dir = join(root, 'runtime', family, llamaOsDir())
    mkdirSync(dir, { recursive: true })
    writeFileSync(join(dir, bin), '')
  }
  if (opts.llama !== false) put('llama.cpp', llamaServerBinaryName())
  if (opts.cpuNet) {
    mkdirSync(join(root, 'runtime', 'llama.cpp', llamaOsDir(), 'cpu'), { recursive: true })
    writeFileSync(cpuNetBin(root), '')
  }
  if (opts.whisper) put('whisper.cpp', whisperCliBinaryName())
  return root
}

interface Fakes {
  ctx: AppContext
  probe: Mock & { invalidate: Mock }
  embedderReset: Mock
  rerankerReset: Mock
  visionReset: Mock
  refreshTranslatorSlot: Mock
  restartChat: Mock
}

/** `probeBehavior` runs inside the fake device probe (e.g. re-report the problem). `db` null = locked workspace. */
function makeCtx(root: string, probeBehavior: () => void, db: Db | null = null): Fakes {
  const probe = Object.assign(
    vi.fn(async () => {
      probeBehavior()
      return []
    }),
    { invalidate: vi.fn() }
  )
  const embedderReset = vi.fn()
  const rerankerReset = vi.fn()
  const visionReset = vi.fn()
  const refreshTranslatorSlot = vi.fn()
  const ctx = {
    paths: { rootPath: root },
    isDev: false,
    probeGpu: probe,
    embedder: { resetStartFailure: embedderReset },
    reranker: { resetStartFailure: rerankerReset },
    vision: { resetStartFailure: visionReset },
    refreshTranslatorSlot,
    runtime: { status: () => ({ backend: 'mock', modelId: 'm', running: true, healthy: true, port: null, message: '' }) },
    // Locked: probeAndPersistGpu and healEngineLoadState are admission-gated and skip entirely.
    workspace: workspaceStandIn({ unlocked: db != null }),
    db
  } as unknown as AppContext
  const restartChat = vi.fn(async () => undefined)
  // As `main/index.ts` wires it (#654); `resetEngineProblemsForTest` drops the subscription.
  rearmWhenChatEngineHeals(ctx, { restartChat })
  return { ctx, probe, embedderReset, rerankerReset, visionReset, refreshTranslatorSlot, restartChat }
}

/** A fake child that emits `stderr` (when given) then closes with `code` on the next microtask. */
function closingSpawn(code: number, stderr = ''): SpawnFn {
  return () => {
    const child = new EventEmitter() as EventEmitter & ChildProcessLike
    const err = new EventEmitter()
    Object.assign(child, { pid: 5, killed: false, stderr: err, kill: () => true, unref: () => undefined })
    queueMicrotask(() => {
      if (stderr) err.emit('data', Buffer.from(stderr))
      child.emit('close', code, null)
    })
    return child
  }
}
const verified = async (): Promise<'ok'> => 'ok' // the real verifier's pass verdict
const LOADER_STDERR =
  '/media/x/runtime/whisper.cpp/linux/whisper-cli: error while loading shared libraries: libgomp.so.1: cannot open shared object file: No such file or directory\n'

beforeEach(() => {
  // A developer's dev-only override would redirect the resolvers away from the temp drive.
  vi.stubEnv('HILBERTRAUM_LLAMA_BIN', '')
  vi.stubEnv('HILBERTRAUM_WHISPER_BIN', '')
})
afterEach(() => {
  vi.unstubAllEnvs()
  resetEngineProblemsForTest()
  clearModelLoadLatches()
  for (const db of dbs.splice(0)) {
    try {
      db.close()
    } catch {
      /* already closed */
    }
  }
  for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true })
})

describe('recheckEngines — the chat engine (#530)', () => {
  // The chat engine is re-checked with an explicit `--version` spawn (review fix): the GPU probe
  // answers [] for a binary it could not even run, which would have read as "loads".
  const LLAMA_LOADER_STDERR =
    '/media/x/runtime/llama.cpp/linux/llama-server: error while loading shared libraries: libgomp.so.1: cannot open shared object file: No such file or directory\n'

  it('a program the OS still refuses keeps the verdict and re-arms nothing', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    latchModelLoad('m', 'unknown model architecture')
    const f = makeCtx(driveRoot(), () => undefined)
    const result = await recheckEngines(f.ctx, {
      restartChat: f.restartChat,
      spawn: closingSpawn(127, LLAMA_LOADER_STDERR),
      verify: verified,
      platform: 'linux'
    })
    expect(result.problems).toEqual([LLAMA_PROBLEM])
    expect(f.embedderReset).not.toHaveBeenCalled()
    expect(f.rerankerReset).not.toHaveBeenCalled()
    expect(f.visionReset).not.toHaveBeenCalled()
    expect(f.refreshTranslatorSlot).not.toHaveBeenCalled()
    expect(f.restartChat).not.toHaveBeenCalled()
    expect(modelLoadLatchReason('m')).not.toBeNull()
  })

  it('a program the OS now starts loses the verdict and every consumer is re-armed', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    latchModelLoad('m', 'unknown model architecture')
    const f = makeCtx(driveRoot(), () => undefined)
    const spawn = vi.fn(closingSpawn(0))
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat, spawn, verify: verified })
    // #656: `--version` exits at once. Started with no arguments, b11146 runs a router-mode server
    // on 127.0.0.1:8080 until killed, so the check would hold a port for its whole 10 s bound.
    expect(spawn.mock.calls.map(([bin, args]) => [bin.endsWith(llamaServerBinaryName()), args])).toEqual([[true, ['--version']]])
    expect(result.problems).toEqual([])
    expect(engineProblemFor('llama_cpp')).toBeNull()
    expect(f.embedderReset).toHaveBeenCalledTimes(1)
    expect(f.rerankerReset).toHaveBeenCalledTimes(1)
    expect(f.visionReset).toHaveBeenCalledTimes(1)
    expect(f.refreshTranslatorSlot).toHaveBeenCalledTimes(1)
    expect(f.restartChat).toHaveBeenCalledTimes(1)
    expect(modelLoadLatchReason('m')).toBeNull()
  })

  // #1012 code review round 6: a changed engine file is the engine's own files damaged — the check never
  // runs the program, and the verdict becomes the one the "Install again" offer reads.
  it('a binary whose files do not match their marker is never run — the verdict becomes damaged files, never "runs again"', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot(), () => undefined)
    const spawn = vi.fn(closingSpawn(0))
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat, spawn, verify: async () => 'mismatch' })
    expect(spawn).not.toHaveBeenCalled()
    expect(result.problems).toEqual([expect.objectContaining({ family: 'llama_cpp', reason: 'files-damaged' })])
    expect(f.restartChat).not.toHaveBeenCalled()
  })

  it('a Windows spawn refusal (EPERM — policy / security software) is still a refusal', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot(), () => undefined)
    const spawn: SpawnFn = () => {
      throw Object.assign(new Error('spawn EPERM'), { code: 'EPERM' })
    }
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat, spawn, verify: verified, platform: 'win32' })
    expect(result.problems).toEqual([{ family: 'llama_cpp', reason: 'blocked', os: 'win', exit: 'spawn error EPERM' }])
    expect(f.restartChat).not.toHaveBeenCalled()
  })

  it('two clicks share one pass (single flight): one spawn, one restart', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot(), () => undefined)
    const spawn = vi.fn(closingSpawn(0))
    const deps = { restartChat: f.restartChat, spawn, verify: verified }
    const [a, b] = await Promise.all([recheckEngines(f.ctx, deps), recheckEngines(f.ctx, deps)])
    expect(a).toBe(b)
    expect(spawn).toHaveBeenCalledTimes(1)
    expect(f.restartChat).toHaveBeenCalledTimes(1)
  })

  it('with an unlocked workspace the heal runs too: the loader-caused flag clears, the probe is refreshed (#530)', async () => {
    const db = openDatabase(join(mkdtempSync(join(tmpdir(), 'hilbertraum-recheck-db-')), 'test.sqlite'))
    seedSettings(db)
    dbs.push(db)
    updateSettings(db, {
      gpuAutoDisabled: true,
      gpuLastError:
        '2026-09-30T10:00:00.000Z — llama-server exited before becoming healthy (code 127) — last output: /m/llama-server: error while loading shared libraries: libgomp.so.1: cannot open shared object file: No such file or directory'
    })
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot(), () => undefined, db)
    await recheckEngines(f.ctx, { restartChat: f.restartChat, spawn: closingSpawn(0), verify: verified, platform: 'linux' })
    const s = getSettings(db)
    expect(s.gpuAutoDisabled).toBe(false)
    expect(s.gpuLastError).toBeNull()
    expect(f.probe.invalidate).toHaveBeenCalledTimes(1)
    expect(f.probe).toHaveBeenCalledTimes(1)
    expect(f.restartChat).toHaveBeenCalledTimes(1)
  })

  it('an absent chat-engine binary clears the verdict (the missing-engine banner takes over)', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot({ llama: false }), () => undefined)
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat })
    expect(result.problems).toEqual([])
    expect(f.probe).not.toHaveBeenCalled()
    // Gone is not healed: nothing is re-armed and no restart is attempted on a missing engine.
    expect(f.embedderReset).not.toHaveBeenCalled()
    expect(f.restartChat).not.toHaveBeenCalled()
  })

  it('does nothing when no engine has a verdict', async () => {
    const f = makeCtx(driveRoot(), () => undefined)
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat })
    expect(result).toEqual({ problems: [] })
    expect(f.probe).not.toHaveBeenCalled()
    expect(f.restartChat).not.toHaveBeenCalled()
  })

  // #678: on a Kit, rungs 1–2 can fail for a reason that is not the loader's (a damaged weight file)
  // and rung 3 then reports the cpu/ net alone. The main build loads fine; checking it said "runs
  // again" and the next walk to rung 3 brought the verdict back. The cpu/ net is what is checked.
  it.each<[string, boolean]>([
    ['still refused keeps the verdict', false],
    ['now starting heals it', true]
  ])('a verdict only the cpu/ net reported is checked on the cpu/ net: %s (#678)', async (_label, cpuLoads) => {
    const root = driveRoot({ cpuNet: true })
    const CPU_DAMAGED: EngineProblem = { family: 'llama_cpp', reason: 'files-damaged', os: 'linux', name: 'libllama.so', exit: 'exit code 127' }
    reportEngineProblem(CPU_DAMAGED, cpuNetBin(root))
    const f = makeCtx(root, () => undefined)
    // The main build always loads; the cpu/ net is refused for a missing library of its own.
    const refusal = `${cpuNetBin(root)}: error while loading shared libraries: libllama.so: cannot open shared object file: No such file or directory\n`
    const spawn = vi.fn<SpawnFn>((bin, args, o) =>
      (bin === cpuNetBin(root) && !cpuLoads ? closingSpawn(127, refusal) : closingSpawn(0))(bin, args, o)
    )
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat, spawn, verify: verified, platform: 'linux' })
    expect(spawn.mock.calls.map(([bin]) => bin)).toEqual([cpuNetBin(root)])
    expect(result.problems).toEqual(cpuLoads ? [] : [CPU_DAMAGED])
    expect(f.restartChat).toHaveBeenCalledTimes(cpuLoads ? 1 : 0)
  })
})

describe('recheckEngines — the voice engine (#530)', () => {
  it('a voice engine the OS now starts loses its verdict; the chat consumers are not re-armed', async () => {
    reportEngineProblem(WHISPER_PROBLEM, REFUSED_WHISPER)
    const f = makeCtx(driveRoot({ whisper: true }), () => undefined)
    const spawn = vi.fn(closingSpawn(0))
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat, spawn, verify: verified, platform: 'linux' })
    // #656: the voice engine is started with `--help`, which prints its usage and exits.
    expect(spawn.mock.calls.map(([bin, args]) => [bin.endsWith(whisperCliBinaryName()), args])).toEqual([[true, ['--help']]])
    expect(result.problems).toEqual([])
    expect(f.embedderReset).not.toHaveBeenCalled()
    expect(f.restartChat).not.toHaveBeenCalled()
  })

  it('a voice engine the OS still refuses keeps its verdict', async () => {
    reportEngineProblem(WHISPER_PROBLEM, REFUSED_WHISPER)
    const f = makeCtx(driveRoot({ whisper: true }), () => undefined)
    const result = await recheckEngines(f.ctx, {
      restartChat: f.restartChat,
      spawn: closingSpawn(127, LOADER_STDERR),
      verify: verified,
      platform: 'linux'
    })
    expect(result.problems).toEqual([WHISPER_PROBLEM])
    expect(engineProblemFor('whisper_cpp')).toEqual(WHISPER_PROBLEM)
  })

  it('an absent voice binary clears the verdict', async () => {
    reportEngineProblem(WHISPER_PROBLEM, REFUSED_WHISPER)
    const f = makeCtx(driveRoot(), () => undefined)
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat, verify: verified })
    expect(result.problems).toEqual([])
  })
})

// #654: the refused chat engine runs again without "Check again" — the user installed the missing
// library and started the model. Before, the healthy start dropped the verdict (banner gone) while the
// embedder's latch kept failing every import with "The AI engine can't run on this computer".
describe('rearmWhenChatEngineHeals — a healthy start of the refused engine (#654)', () => {
  /** A child that runs until killed; the kill ends it like a real process. */
  const runningSpawn: SpawnFn = () => {
    const child = new EventEmitter() as EventEmitter & ChildProcessLike
    Object.assign(child, {
      pid: 6,
      killed: false,
      stdout: new EventEmitter(),
      stderr: new EventEmitter(),
      kill: () => {
        queueMicrotask(() => {
          child.emit('exit', 0, null)
          child.emit('close', 0, null)
        })
        return true
      }
    })
    return child
  }

  it('re-arms every consumer the refusal latched and brings a demo-mode model back on the engine', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    latchModelLoad('m', 'unknown model architecture')
    const f = makeCtx(driveRoot(), () => undefined)
    const server = new LlamaServer({
      binPath: REFUSED_LLAMA,
      modelPath: '/m.gguf',
      contextTokens: 2048,
      spawn: runningSpawn,
      fetchImpl: (async () => ({ ok: true, status: 200 }) as Response) as typeof fetch,
      findPort: async () => 50910,
      healthIntervalMs: 1
    })
    await server.start()
    try {
      expect(engineProblemFor('llama_cpp')).toBeNull()
      expect(f.embedderReset).toHaveBeenCalledTimes(1)
      expect(f.rerankerReset).toHaveBeenCalledTimes(1)
      expect(f.visionReset).toHaveBeenCalledTimes(1)
      expect(f.refreshTranslatorSlot).toHaveBeenCalledTimes(1)
      expect(modelLoadLatchReason('m')).toBeNull()
      // The healthy start may be the embedder's while the chat model answers in demo mode (owner call).
      await vi.waitFor(() => expect(f.restartChat).toHaveBeenCalledTimes(1), { timeout: hangBudgetMs(5000) })
    } finally {
      await server.stop()
    }
  })

  // The refused probes persisted nothing: the ladder the restart walks must read this computer's answer (#380).
  it('with an unlocked workspace the probe is re-run and persisted before the restart', async () => {
    const db = openDatabase(join(mkdtempSync(join(tmpdir(), 'hilbertraum-recheck-db-')), 'test.sqlite'))
    seedSettings(db)
    dbs.push(db)
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot(), () => undefined, db)
    clearEngineProblemFor('llama_cpp', REFUSED_LLAMA) // a reporting program started healthy
    await vi.waitFor(() => expect(f.restartChat).toHaveBeenCalledTimes(1), { timeout: hangBudgetMs(5000) })
    expect(f.probe.invalidate).toHaveBeenCalledTimes(1)
    expect(f.probe).toHaveBeenCalledTimes(1)
    expect(f.probe.mock.invocationCallOrder[0]).toBeLessThan(f.restartChat.mock.invocationCallOrder[0])
  })

  // The usual trigger: the chat model's own healthy start. Nothing to restart, and a probe now would run
  // beside its weight upload (#473).
  it('the chat model starting re-arms the consumers but neither probes nor restarts', async () => {
    const db = openDatabase(join(mkdtempSync(join(tmpdir(), 'hilbertraum-recheck-db-')), 'test.sqlite'))
    seedSettings(db)
    dbs.push(db)
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot(), () => undefined, db)
    Object.assign(f.ctx.runtime, {
      status: () => ({ backend: 'mock', modelId: 'm', running: true, healthy: true, port: null, message: '', startingModelId: 'm' })
    })
    clearEngineProblemFor('llama_cpp', REFUSED_LLAMA)
    expect(f.embedderReset).toHaveBeenCalledTimes(1)
    expect(f.probe.invalidate).not.toHaveBeenCalled() // a re-probe drops the cache synchronously
    // One macrotask: a chained probe or restart would have been called by now.
    await new Promise((r) => setImmediate(r))
    expect(f.probe).not.toHaveBeenCalled()
    expect(f.restartChat).not.toHaveBeenCalled()
  })

  // A healthy start that lands while "Check again" checks (an import, say) heals it; Check again then
  // finds nothing left to heal instead of re-arming, re-probing and restarting a second time.
  it('a healthy start during Check again is healed once', async () => {
    reportEngineProblem(LLAMA_PROBLEM, REFUSED_LLAMA)
    const f = makeCtx(driveRoot(), () => undefined)
    const healthyStartDuringCheck: SpawnFn = (...args) => {
      clearEngineProblemFor('llama_cpp', REFUSED_LLAMA)
      return closingSpawn(0)(...args)
    }
    const result = await recheckEngines(f.ctx, { restartChat: f.restartChat, spawn: healthyStartDuringCheck, verify: verified })
    expect(result.problems).toEqual([])
    await vi.waitFor(() => expect(f.restartChat).toHaveBeenCalledTimes(1), { timeout: hangBudgetMs(5000) })
    expect(f.embedderReset).toHaveBeenCalledTimes(1)
  })

  it('a voice engine that runs again re-arms and restarts nothing of the chat engine', () => {
    reportEngineProblem(WHISPER_PROBLEM, REFUSED_WHISPER)
    const f = makeCtx(driveRoot(), () => undefined)
    clearEngineProblemFor('whisper_cpp', REFUSED_WHISPER) // what a clean whisper-cli run does
    expect(engineProblemFor('whisper_cpp')).toBeNull()
    expect(f.embedderReset).not.toHaveBeenCalled()
    expect(f.restartChat).not.toHaveBeenCalled()
  })
})

describe('rearmLlamaConsumers (#530)', () => {
  it('re-arms the model latches and every consumer, tolerating missing optional ones', () => {
    latchModelLoad('m', 'unknown model architecture')
    const f = makeCtx(driveRoot(), () => undefined)
    rearmLlamaConsumers(f.ctx)
    expect(modelLoadLatchReason('m')).toBeNull()
    expect(f.embedderReset).toHaveBeenCalledTimes(1)
    expect(f.rerankerReset).toHaveBeenCalledTimes(1)
    expect(f.visionReset).toHaveBeenCalledTimes(1)
    expect(f.refreshTranslatorSlot).toHaveBeenCalledTimes(1)

    const bare = { embedder: {}, reranker: undefined, vision: undefined } as unknown as AppContext
    expect(() => rearmLlamaConsumers(bare)).not.toThrow()
  })
})