Skip to content

AI, fully local on your computer.

13.9 KB
Raw Blame
import { describe, it, expect, vi } from 'vitest'
import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { composeServices, composeTranslator } from '../../src/main/services/compose-services'
import { LlamaReranker } from '../../src/main/services/reranker/llama'
import { llamaServerBinaryName, llamaServerDir } from '../../src/main/services/runtime/sidecar'
import {
  createRerankerCallbacks,
  createPendingModelSwitchCounter,
  type RerankerCallbackDeps
} from '../../src/main/services/rag/device-posture'
import { resolveAskCandidateScope } from '../../src/main/ipc/registerRagIpc'
import type { Translator } from '../../src/main/services/translation'
import { DEFAULT_SETTINGS, type AppSettings } from '../../src/shared/types'
import type { AppContext } from '../../src/main/services/context'
import { CARDS, CATALOG_MANIFESTS } from '../helpers/gpu-fixtures'

// #795: `registerRagIpc` reaches `ipcMain` through `guarded-handle`. Unmocked, `electron` is the
// real npm package, whose first load downloads the Electron binary when none is installed (Electron
// >= 42): every CI leg fetched ~100 MB from GitHub here, and a 504 failed the file. Nothing in this
// file registers a handler.
vi.mock('electron', () => ({ ipcMain: { handle: () => undefined, removeHandler: () => undefined } }))

// Wave 8 ruling (b)(G)/NF-1 (step 4-8, the Wave 8 analysis's finding that a composition test
// through `compose-services.ts` -> `reranker/factory.ts` alone cannot see an omission at
// `main/index.ts` or at the ask site, the ask handler's `resolveAskCandidateScope` call in
// `registerRagIpc.ts`): this file targets the exported closure FACTORY and
// `composeServices`'s own signature directly, with type-level proof
// (`@ts-expect-error`, which fails `npm run typecheck` if a wire becomes optional again)
// alongside a functional check that the wired callbacks actually reach the sidecar.

describe('Wave 8 NF-1: the required-wiring type-level proof', () => {
  it('composeServices refuses a call missing ONLY rerankerDevicePosture', () => {
    const rootPath = mktemp()
    // @ts-expect-error — rerankerDevicePosture/rerankerRequestCeiling are REQUIRED on composeServices's
    // own signature (ComposeServicesArgs), even though the shared ComposeServicesDeps base (also used
    // by composeTranslator) keeps them optional. An omission here must be a compile error.
    composeServices({ rootPath, manifestsDir: null, bundledManifestsDir: null, rerankerRequestCeiling: () => 48, checkModel })
  })

  it('composeServices refuses a call missing ONLY rerankerRequestCeiling', () => {
    const rootPath = mktemp()
    // @ts-expect-error — rerankerRequestCeiling alone omitted.
    composeServices({ rootPath, manifestsDir: null, bundledManifestsDir: null, rerankerDevicePosture: () => 'cpu' as const, checkModel })
  })

  it('composeServices refuses a call missing ONLY bundledManifestsDir (#842)', () => {
    const rootPath = mktemp()
    // @ts-expect-error — the engine pins' source is required too: left out, the voice engine would read
    // as "no build for this system" with no compile error.
    composeServices({
      rootPath,
      manifestsDir: null,
      rerankerDevicePosture: () => 'cpu' as const,
      rerankerRequestCeiling: () => 48,
      checkModel
    })
  })

  // #913 review S3: the start check is required on composeServices's own signature, and on composeTranslator's
  // (the issue-#40 refresh in main/index.ts), so a composition root that leaves it out does not compile.
  it('composeServices and composeTranslator refuse a call missing ONLY checkModel (#913)', () => {
    const rootPath = mktemp()
    composeServices({
      rootPath,
      manifestsDir: null,
      bundledManifestsDir: null,
      rerankerDevicePosture: () => 'cpu' as const,
      rerankerRequestCeiling: () => 48,
      checkModel
    }) // the complete call compiles
    // @ts-expect-error — checkModel alone omitted: every non-chat role would start unchecked.
    composeServices({ rootPath, manifestsDir: null, bundledManifestsDir: null, rerankerDevicePosture: () => 'cpu' as const, rerankerRequestCeiling: () => 48 })
    // @ts-expect-error — the same for the translator a download re-composes.
    composeTranslator({ rootPath, manifestsDir: null })
  })

  it('createRerankerCallbacks refuses a call missing any of its four required dependencies', () => {
    const base: RerankerCallbackDeps = {
      runtimeManager: { activeModelId: () => null, active: () => null, status: () => ({ startingModelId: null }) as any },
      pendingModelSwitches: createPendingModelSwitchCounter(),
      getTranslator: () => null,
      getSettings: () => null,
      manifestsDir: null
    }
    // Sanity: the fully-specified shape compiles and runs.
    const cb = createRerankerCallbacks(base)
    expect(cb.devicePosture()).toBe('cpu')
    expect(typeof cb.requestCeiling()).toBe('number')

    // @ts-expect-error — runtimeManager omitted.
    createRerankerCallbacks({ ...base, runtimeManager: undefined })
    // @ts-expect-error — pendingModelSwitches omitted.
    createRerankerCallbacks({ ...base, pendingModelSwitches: undefined })
    // @ts-expect-error — getTranslator omitted.
    createRerankerCallbacks({ ...base, getTranslator: undefined })
    // @ts-expect-error — getSettings omitted.
    createRerankerCallbacks({ ...base, getSettings: undefined })
  })

  it('AppContext refuses a literal missing pendingModelSwitches (#477: required, no silent fallback)', () => {
    const base = {
      paths: { workspacePath: '/w' },
      isDev: true,
      manifestsDir: null,
      pendingModelSwitches: createPendingModelSwitchCounter()
    } as unknown as AppContext
    const acceptsContext = (_ctx: AppContext): void => {}

    // Sanity: the fully-specified shape compiles.
    acceptsContext(base)

    // @ts-expect-error — pendingModelSwitches omitted; #477 removed the `?` on AppContext's own
    // field (was optional, with a silent `ctx.pendingModelSwitches ?? createPendingModelSwitchCounter()`
    // fallback at the ask site) — an omission here must now be a compile error.
    acceptsContext({ ...base, pendingModelSwitches: undefined })
  })

  it("resolveAskCandidateScope (the ask handler's call in registerRagIpc.ts) refuses a call omitting occupancy", () => {
    // The type-level proof: `@ts-expect-error` fails `npm run typecheck` if `occupancy` becomes
    // optional again. Wrapped in `expect(...).toThrow()` because TS only strips types -- the
    // call itself still runs (and crashes on the missing 4th argument), which the runtime
    // assertion below turns into a clean, honest test outcome rather than an uncaught error.
    expect(() => {
      // @ts-expect-error — the 4th `occupancy` parameter is required (Wave 8 ruling (a)/NF-1):
      // an optional parameter here would silently readmit "trust the setting" behaviour.
      resolveAskCandidateScope({} as unknown as AppSettings, true, null)
    }).toThrow()
  })
})

/** A start check that passes everything: these rows are about the reranker wires, not the check. */
const checkModel = async (): Promise<'ok'> => 'ok'

function mktemp(): string {
  return mkdtempSync(join(tmpdir(), 'hilbertraum-reranker-callbacks-composition-'))
}

/** A minimal VALID reranker manifest (compose-services-discovery.test.ts's `roleManifest` shape). */
const RERANKER_MANIFEST = {
  id: 'rerank-test',
  display_name: 'rerank-test (test)',
  family: 'test-family',
  role: 'reranker',
  format: 'gguf',
  runtime: 'llama_cpp',
  license: 'apache-2.0',
  size_on_disk_gb: 0.1,
  recommended_min_ram_gb: 1,
  recommended_ram_gb: 2,
  recommended_context_tokens: 4096,
  local_path: 'models/reranker/rerank-test.gguf',
  sha256: 'REPLACE_WITH_REAL_HASH',
  recommended_profiles: [],
  license_review: { status: 'approved', reviewed_by: 'test', reviewed_at: '2026-07-10', notes: '' }
}

describe('Wave 8: the wired callbacks actually reach the sidecar (functional, not just type-level)', () => {
  it('composeServices threads BOTH reranker callbacks into the LlamaReranker it selects from a provisioned drive', async () => {
    const root = mkdtempSync(join(tmpdir(), 'hilbertraum-reranker-wiring-'))
    const manifestsDir = join(root, 'model-manifests')
    mkdirSync(manifestsDir, { recursive: true })
    writeFileSync(join(manifestsDir, 'rerank-test.yaml'), JSON.stringify(RERANKER_MANIFEST)) // JSON is YAML
    mkdirSync(join(root, 'models', 'reranker'), { recursive: true })
    writeFileSync(join(root, 'models', 'reranker', 'rerank-test.gguf'), '') // existence only
    mkdirSync(llamaServerDir(root), { recursive: true })
    writeFileSync(join(llamaServerDir(root), llamaServerBinaryName()), '') // never spawned below
    let posture: 'gpu' | 'cpu' = 'gpu'
    let postureCalls = 0
    const { reranker } = composeServices({
      rootPath: root,
      manifestsDir,
      bundledManifestsDir: null,
      rerankerDevicePosture: () => {
        postureCalls++
        return posture
      },
      rerankerRequestCeiling: () => 1,
      checkModel: async () => 'ok'
    })
    expect(reranker).toBeInstanceOf(LlamaReranker)
    expect(reranker?.id).toBe('rerank-test') // the manifest id
    expect(postureCalls).toBe(0) // composing reads nothing — lazy
    expect(reranker?.devicePosture?.()).toBe('gpu') // the injected posture, not the absent-callback 'cpu'
    posture = 'cpu'
    // G throws before any start, so the placeholder binary is never spawned.
    await expect(reranker!.rerank('q', ['a', 'b'])).rejects.toThrow(/refused/i) // 2 > the ceiling of 1
  })
})

// Wave 8 review-fix round (opus-review-8.md, finding C4): every OTHER call site of
// `snapshotRerankerOccupancy`/`createRerankerCallbacks` in the suite passes `getTranslator: () =>
// null`, so `translationOccupied: getTranslator()?.gpuOccupied?.() ?? false`
// (`rag/device-posture.ts:232`) was indistinguishable from the literal `false` under the whole
// suite — the wire itself was untested, only its two ENDPOINTS (`TranslationRuntime.gpuOccupied()`
// in `translation-runtime.test.ts`, and `resolveRerankerDevicePosture`'s own occupancy branch with
// a hand-built snapshot in `rerank-profile-wiring.test.ts`). These two
// tests drive the JOIN itself through the real, exported `createRerankerCallbacks` factory, with a
// NON-null `Translator`. Confirmed both tests are load-bearing by temporarily replacing
// `device-posture.ts:232`'s expression with the literal `false` in the worktree (`node -e` editing
// the file directly, never through a commit) and re-running this file: BOTH went red (2 failed / 6
// passed — every `gpuOccupied: () => true` assertion stayed 'gpu' instead of 'cpu'), then all 8
// passed again once `git checkout -- device-posture.ts` restored the join — confirmed clean via
// `git diff`/`git status` before moving on.

// The project's own measured GTX 1070 Ti fixture (same as `reranker-wave8.test.ts`'s S4/S5 scenarios):
// {totalMb: 8273, freeMb: 7504}. qwen3.5-4b-ud-q4kxl needs ~3837.4 MiB (remainder 3666.6 MiB >=
// the 2808.2 MiB floor) => posture 'gpu' with NO occupancy — the "otherwise resolves gpu" baseline
// C4 asks for.
const GTX_SETTINGS: AppSettings = {
  ...DEFAULT_SETTINGS,
  gpuMode: 'auto',
  gpuAutoDisabled: false,
  gpuProbe: { devices: [CARDS.GTX_1070_TI], probedAt: new Date().toISOString() }
}
const FOUR_B = 'qwen3.5-4b-ud-q4kxl'

const BARE_TRANSLATOR: Translator = {
  modelId: 'translategemma-x',
  contextWindow: () => 4096,
  translate: async () => '',
  stop: async () => undefined
}

function callbacksWith(getTranslator: () => Translator | null): ReturnType<typeof createRerankerCallbacks> {
  const deps: RerankerCallbackDeps = {
    runtimeManager: { activeModelId: () => FOUR_B, active: () => null, status: () => ({ startingModelId: null }) as any },
    pendingModelSwitches: createPendingModelSwitchCounter(),
    getTranslator,
    getSettings: () => GTX_SETTINGS,
    manifestsDir: CATALOG_MANIFESTS
  }
  return createRerankerCallbacks(deps)
}

describe('Wave 8 review-fix round (C4): Translator.gpuOccupied() -> posture, through the real join', () => {
  it('createRerankerCallbacks: a NON-null Translator.gpuOccupied() reaches the resolved posture (true -> cpu, false -> gpu, absent member -> gpu)', () => {
    // No translator at all: the committed 4B has provable headroom on the fixture -- 'gpu'.
    expect(callbacksWith(() => null).devicePosture()).toBe('gpu')

    // A Translator WITHOUT the optional member reads as NOT occupied -- same answer as null.
    expect(callbacksWith(() => BARE_TRANSLATOR).devicePosture()).toBe('gpu')

    // gpuOccupied() -> false: still 'gpu' (the snapshot that otherwise resolves 'gpu').
    const free: Translator = { ...BARE_TRANSLATOR, gpuOccupied: () => false }
    expect(callbacksWith(() => free).devicePosture()).toBe('gpu')

    // gpuOccupied() -> true: forces 'cpu' on that SAME otherwise-'gpu' snapshot.
    const busy: Translator = { ...BARE_TRANSLATOR, gpuOccupied: () => true }
    expect(callbacksWith(() => busy).devicePosture()).toBe('cpu')
  })

  it('createRerankerCallbacks follows a RE-COMPOSED translator instance through the SAME live getter, not a captured reference (the ruled re-composed-translator case)', () => {
    // Models `main/index.ts`'s `onModelInstalled` re-composition: `ctx.translator` is REASSIGNED
    // to a brand-new instance mid-session, never mutated in place. `getTranslator` below reads
    // `current` fresh on every call -- exactly the live-getter contract `RerankerCallbackDeps.
    // getTranslator`'s own doc comment requires, never a value captured at construction time.
    let current: Translator = { ...BARE_TRANSLATOR, gpuOccupied: () => false } // instance A -- not occupying
    const callbacks = callbacksWith(() => current)
    expect(callbacks.devicePosture()).toBe('gpu') // instance A: not occupying

    current = { ...BARE_TRANSLATOR, gpuOccupied: () => true } // instance B -- a re-composed, occupying instance
    expect(callbacks.devicePosture()).toBe('cpu') // the SAME callbacks object follows B, not a stale A
  })
})