Skip to content

AI, fully local on your computer.

19.5 KB
Raw Blame
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mkdtempSync, readdirSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'

// F16 / TEST-N8 generalized (audit-postmerge-2026-06-29).
//
// The prior TEST-N8 (chat-ipc.test.ts) enumerated only registerChatIpc + the two benchmark
// handlers; both now have their MODULES entry here. The audit found four more DB-touching handler GROUPS with no explicit
// requireUnlocked() preamble — rag (rag:ask), audit, core settings, and model — which were
// fail-closed (the `ctx.db` getter throws when locked) but surfaced the RAW unlocalized
// "Workspace is locked — unlock it first." instead of the friendly localized copy, and were
// not covered by an enumerating test (so a future unguarded handler would slip the net).
//
// This is the GENERALIZED structural test: it drives each DB-touching register*Ipc module
// in two postures (`POSTURES`): a LOCKED ctx, and an open workspace mid-lock (`isUnlocked()`
// still true, the AUD-02 `isLocking()` latch set). In each it asserts EVERY non-exempt handler
// refuses with the friendly copy ("Workspace is locked." — note the PERIOD; the raw
// vault-getter string has " — unlock it first."). It also asserts the read-only / in-memory
// channels (getLogTail, getRuntimeStatus) STILL resolve when locked (pre-unlock diagnostics +
// runtime status must work at the gate).
//
// Modules with their own dedicated locked-vault rejection tests (translate, dictation) and the
// pre-unlock modules are listed in COVERED_ELSEWHERE below, each with its
// reason. Together with this file every DB-touching IPC module is enumerated.
//
// NOTE: this also SUBSUMES Phase-5 item T3 (rag:ask lock-rejection) — registerRagIpc is
// driven here against a locked ctx, so T3 needs no separate test.

const ipcState = vi.hoisted(() => ({ handlers: new Map<string, unknown>(), dialogOpens: 0 }))
vi.mock('electron', () => ({
  ipcMain: {
    handle: (channel: string, fn: unknown) => ipcState.handlers.set(channel, fn),
    removeHandler: (channel: string) => ipcState.handlers.delete(channel)
  },
  // registerCoreIpc imports `app`/`clipboard`; only referenced inside handlers we don't drive.
  app: { getVersion: () => '0.0.0-test' },
  clipboard: { writeText: () => {}, readText: () => '', clear: () => {} },
  // A picker or a save dialog that skips its lock gate, or runs it only after the dialog, reaches the OS
  // dialog: count it, and answer it (cancelled) so an ungated one reports "resolved instead of rejecting" (#681).
  BrowserWindow: { getFocusedWindow: () => null },
  dialog: {
    showOpenDialog: async () => {
      ipcState.dialogOpens += 1
      return { canceled: true, filePaths: [] }
    },
    showSaveDialog: async () => {
      ipcState.dialogOpens += 1
      return { canceled: true }
    }
  }
}))

import { registerCoreIpc } from '../../src/main/ipc/registerCoreIpc'
import { registerModelIpc } from '../../src/main/ipc/registerModelIpc'
import { registerAuditIpc } from '../../src/main/ipc/registerAuditIpc'
import { registerChatIpc } from '../../src/main/ipc/registerChatIpc'
import { registerRagIpc } from '../../src/main/ipc/registerRagIpc'
import { registerBenchmarkIpc } from '../../src/main/ipc/registerBenchmarkIpc'
import { registerCollectionsIpc } from '../../src/main/ipc/registerCollectionsIpc'
import { registerZimIpc } from '../../src/main/ipc/registerZimIpc'
import { registerEvidenceReviewsIpc } from '../../src/main/ipc/registerEvidenceReviewsIpc'
import { registerLocalApiIpc } from '../../src/main/ipc/registerLocalApiIpc'
import { registerSkillsIpc } from '../../src/main/ipc/registerSkillsIpc'
import { registerImagesIpc } from '../../src/main/ipc/registerImagesIpc'
import { registerDocsIpc } from '../../src/main/ipc/registerDocsIpc'
import { registerDocTasksIpc } from '../../src/main/ipc/registerDocTasksIpc'
import { VisionService } from '../../src/main/services/vision'
import { IPC } from '../../src/shared/ipc'
import { t } from '../../src/shared/i18n'
import { initLogging } from '../../src/main/services/logging'
import type { AppContext } from '../../src/main/services/context'
import type { WorkspaceAdmission } from '../../src/main/services/workspace-vault'
import { ANY_SENDER, invoke, type IpcHandlers } from '../helpers/ipc'
import { workspaceStandIn } from '../helpers/workspace-stand-in'

const handlers = ipcState.handlers as unknown as IpcHandlers

/** A LOCKED ctx with just enough shape for each module to REGISTER and for the documented
 *  read-only/in-memory channels to run. Every DB-touching handler must refuse at its
 *  requireUnlocked() preamble (the first statement) before any of this matters. `workspace` is the
 *  posture the guards read (see `POSTURES`). */
function lockedCtx(tmp: string, workspace: WorkspaceAdmission = workspaceStandIn({ unlocked: false })): AppContext {
  return {
    trustedSenders: ANY_SENDER,
    workspace,
    paths: { workspacePath: tmp, rootPath: tmp, configPath: join(tmp, 'config.json') },
    runtime: {
      status: () => ({ running: false, modelId: null, backend: null }),
      active: () => null,
      activeModelId: () => null
    },
    manifestsDir: null,
    isDev: false
  } as unknown as AppContext
}

// Per-module exemptions: the channels that LEGITIMATELY work while locked (read-only,
// in-memory, or workspace-agnostic). Everything else must refuse.
const MODULES: Array<{
  name: string
  register: (ctx: AppContext) => void
  exempt: Set<string>
  /** The module's own locked sentence, where it has one. The shared "Workspace is locked." prefix alone cannot tell
   *  chat's copy from the benchmark's: chat throwing `main.benchmark.locked` stayed green. */
  lockedCopy?: string
}> = [
  {
    name: 'registerCoreIpc',
    register: registerCoreIpc,
    // Status/policy/preflight are workspace-aware (safe-default while locked); the diagnostics
    // log channels are intentionally pre-unlock; clipboard is in-memory. settings:get/update gated.
    exempt: new Set<string>([
      IPC.getAppStatus,
      IPC.getDriveStatus,
      IPC.runPreflight,
      IPC.getPolicy,
      IPC.getLogTail,
      IPC.exportLog,
      IPC.writeClipboard
    ])
  },
  {
    name: 'registerModelIpc',
    register: registerModelIpc,
    // stopRuntime + the two read-only runtime channels touch the in-memory runtime / disk
    // marker, never ctx.db, and must work at the gate. #420's cancelVerify joins them for the
    // same reason as stopRuntime: it only STOPS work already running (an AbortController in a
    // module-scoped map), touches no ctx.db, and a workspace that locked mid-pass must still be
    // able to end that pass.
    exempt: new Set<string>([
      IPC.stopRuntime,
      IPC.getRuntimeStatus,
      IPC.getRuntimeInstall,
      IPC.cancelModelVerify
    ])
  },
  { name: 'registerAuditIpc', register: registerAuditIpc, exempt: new Set<string>() },
  // Chat: 16 of its 19 channels open with requireUnlocked() — conversations, messages, search, the send and the three
  // save-dialog exports (chat-ipc's TEST-N8 lived in chat-ipc.test.ts until the chat + RAG campaign). Exempt, each read
  // from its handler: chat:stop only aborts an in-memory controller; chat:activeStream and
  // chat:activeStreamConversations read the in-memory stream registry, so a screen remounted after a lock still settles.
  {
    name: 'registerChatIpc',
    register: registerChatIpc,
    exempt: new Set<string>([IPC.stopGeneration, IPC.getActiveStream, IPC.listActiveStreamConversations]),
    lockedCopy: t('en', 'main.chat.locked')
  },
  { name: 'registerRagIpc', register: registerRagIpc, exempt: new Set<string>() },
  {
    name: 'registerBenchmarkIpc',
    register: registerBenchmarkIpc,
    exempt: new Set<string>(),
    lockedCopy: t('en', 'main.benchmark.locked')
  },
  { name: 'registerCollectionsIpc', register: registerCollectionsIpc, exempt: new Set<string>() },
  // Knowledge packs (ZIM wave): every registration/read/mutation channel is DB-backed; only the
  // tools-installed + refreshing status probe is workspace-agnostic (in-memory service state).
  // `packs:refresh` (#301 P3b, finding L7) schedules a DB-touching reconciliation and is
  // therefore NOT exempt — `requireUnlocked()` is its first statement like every other handler
  // here, so it is covered automatically by the loop below.
  {
    name: 'registerZimIpc',
    register: registerZimIpc,
    exempt: new Set<string>([IPC.getKnowledgePackStatus])
  },
  // EP-1 Phase 1: every evidence-review handler is DB-backed — none are exempt.
  {
    name: 'registerEvidenceReviewsIpc',
    register: registerEvidenceReviewsIpc,
    exempt: new Set<string>(),
    // #839 F5: every evidence channel, not only the one the IPC suite drives, says the module's own sentence.
    lockedCopy: t('en', 'main.evidenceReviews.locked')
  },
  // local-api wave P4: all three channels read or write the access-key table in the
  // workspace DB (mint / copy / rotate) — none may answer a locked vault.
  { name: 'registerLocalApiIpc', register: registerLocalApiIpc, exempt: new Set<string>() },
  // Skills: all 18 channels open with requireUnlocked(); none are exempt.
  { name: 'registerSkillsIpc', register: registerSkillsIpc, exempt: new Set<string>() },
  // Images: every handler opens with requireUnlocked() — chooseImage too (#119: ungated it would
  // pop the OS dialog and bank D2 picker tokens while locked). Only images:getStatus answers
  // locked: status is workspace-agnostic by design (PROD-2 — vision weights are not encrypted;
  // registerImagesIpc.ts "getStatus is WORKSPACE-AGNOSTIC"). The service is never reached: every
  // refusal comes first.
  {
    name: 'registerImagesIpc',
    register: (ctx) =>
      registerImagesIpc(
        ctx,
        new VisionService({
          isWorkspaceLocking: () => false,
          checkModel: async () => 'ok',
          getStatus: async () => ({ available: false, reason: 'no-model' }),
          createRuntime: () => {
            throw new Error('a locked workspace builds no vision runtime')
          }
        })
      ),
    exempt: new Set<string>([IPC.imageGetStatus])
  },
  // Documents: every DB-touching handler opens with requireUnlocked() — 15 channels, among them the old
  // docs-ipc "M6" subset, the L-3 preflight gate, the #90 original export and, since #681, docs:pick (the last
  // picker that opened the OS dialog and minted a D1 token while locked: SEC-3 (Info) in architecture.md's
  // follow-up-audit ledger; images gated since #119, skills since #240). Exempt, each read from its handler:
  //  - docs:getImportJob / docs:getActiveImportJob — in-memory import aggregates; a poll must still settle after a
  //    mid-job lock (docs-ipc T-4 drives getImportJob while locked).
  //  - docs:getReindexAllJob — the in-memory bulk re-index aggregate (the remount recovery read).
  //  - docs:cancelReindexAll — only STOPS work already running (aborts the loop at its next boundary) and touches no
  //    ctx.db, the #420 cancelVerify rationale above.
  {
    name: 'registerDocsIpc',
    register: registerDocsIpc,
    exempt: new Set<string>([
      IPC.getImportJob,
      IPC.getActiveImportJob,
      IPC.getReindexAllJob,
      IPC.cancelReindexAll
    ])
  },
  // Doc tasks: doctasks:start and the two read-only analysis channels (analysis:coverage, analysis:listAll) open with
  // requireUnlocked(). The four lane channels only read or abort the manager's in-memory queue and never touch
  // ctx.db: doctasks:get / doctasks:getActive / doctasks:listActive (a renderer poll that outlives a lock settles on
  // the manager's own terminal state) and doctasks:cancel (only stops work; the lock path flushes the lane itself).
  {
    name: 'registerDocTasksIpc',
    register: registerDocTasksIpc,
    exempt: new Set<string>([IPC.getDocTask, IPC.getActiveDocTask, IPC.listActiveDocTasks, IPC.cancelDocTask])
  }
]

// DX-4 (full-audit-2026-06-29 follow-up, Phase 7): the locked-vault posture of every register*Ipc
// module not driven HERE (in MODULES) is verified by a DEDICATED test, OR the module is
// intentionally PRE-UNLOCK (it runs at the setup gate, before a workspace exists, so it has no
// requireUnlocked preamble by design). Each entry names WHY, so this set can never silently absorb
// a genuinely-unguarded module. The enumeration meta-assertion below proves
// union(MODULES, COVERED_ELSEWHERE) == every register*Ipc discovered by glob — so a NEW module that
// is added uncovered reds this file (the exact drift it exists to catch).
const COVERED_ELSEWHERE: Record<string, string> = {
  registerTranslateIpc:
    'translate-ipc.test.ts (locked-vault rejection of translateStart — a start lazily respawns the suspended sidecar; cancel/getActive are safe non-DB reads, intentionally ungated)',
  registerWorkspaceIpc:
    'workspace-ipc.test.ts — IS the lock/unlock/create gate; unlock + getStatus MUST work pre-unlock (no requireUnlocked by design). The password change answers a result, not a throw: its refusal during a lock teardown (the AUD-02 latch) is lock-admission-race.test.ts "refuses changeWorkspacePassword while the lock teardown is parked"',
  registerStartFailureIpc:
    'backend-start-failure.test.ts (#1024) — pre-unlock by design: the state of a run whose back-end start threw. It takes no AppContext (there is none), answers getWorkspaceState with a constant and the log tail + clipboard pair of Diagnostics’ Copy; the rows pin that exact channel set',
  registerDictationIpc:
    'dictation-ipc.test.ts (locked-vault and mid-lock (AUD-02 latch) rejection, #860 L6; S3 full-audit-2026-06-30 — writes a transient plaintext WAV into the documents dir, so it is lock-gated, not pre-unlock)',
  registerDownloadIpc:
    'pre-unlock by design — model downloads run at the setup gate; its only ctx.db read is guarded behind ctx.workspace.isUnlocked()',
  registerEngineIpc:
    'pre-unlock by design — engine-binary downloads run at the setup gate; every ctx.db read is guarded (gates()\'s allowNetwork read behind ctx.workspace.isUnlocked(), the #339 pack reconcile behind workspaceAdmitsWork). Its ocr:* channels (#410): ocr:install is refused while locked through that gates() read — ocr-install.test.ts "OCR install via IPC (#410) › refuses while the workspace is locked, before any fetch"; ocr:status / ocr:getJob / ocr:cancel read only the drive and the in-memory job'
}

// AUD-02: the two postures a content guard must refuse. Locked: the DB is closed. Mid-lock: "Lock now" keeps the DB OPEN
// for its whole multi-second teardown, so `isUnlocked()` is still true and only the latch (`isLocking()`, read through
// `workspaceAdmitsWork`) says no. A guard regressed to a bare `isUnlocked()` admits the call there; the handler then
// runs on into a ctx with no `db` and fails some other way, or resolves, and the row reds. This pass proves each
// module's FIRST guard; that the real controller arms the latch before the teardown's first await is
// lock-admission-race.test.ts's, over a parked real lock.
// Built per row (the stand-in is stateful: a handler that called `shutdown()` on a refusal path would otherwise turn the
// mid-lock posture into a locked one for every later module).
const POSTURES: ReadonlyArray<readonly [string, () => WorkspaceAdmission]> = [
  ['when locked', () => workspaceStandIn({ unlocked: false })],
  ['while a lock is under way (AUD-02 latch)', () => workspaceStandIn({ locking: true })]
]

describe('IPC lock-guard coverage across modules (F16 / TEST-N8 generalized)', () => {
  let tmp: string

  beforeEach(() => {
    tmp = mkdtempSync(join(tmpdir(), 'hilbertraum-lockcov-'))
    ipcState.handlers.clear()
  })

  for (const [posture, makeWorkspace] of POSTURES) {
    for (const mod of MODULES) {
      it(`${mod.name}: every DB-touching handler refuses with the friendly copy ${posture}`, async () => {
        ipcState.handlers.clear()
        ipcState.dialogOpens = 0
        mod.register(lockedCtx(tmp, makeWorkspace()))
        const channels = [...handlers.keys()]
        expect(channels.length).toBeGreaterThan(0) // the module registered something
        let checked = 0
        for (const ch of channels) {
          if (mod.exempt.has(ch)) continue
          // Throwaway args — requireUnlocked() is the FIRST statement of every DB-touching
          // handler, so the refusal is arg-shape-independent.
          await expect(invoke(handlers, ch, 'x', 'y', 'z')).rejects.toThrow(mod.lockedCopy ?? /Workspace is locked\./)
          // …and never the raw vault-getter string ("Workspace is locked — unlock it first.").
          await expect(invoke(handlers, ch, 'x', 'y', 'z')).rejects.not.toThrow(/unlock it first/i)
          checked++
        }
        // Guard against an exempt set that accidentally swallows the whole surface.
        expect(checked).toBeGreaterThan(0)
        // No picker opened the OS dialog while locked: a gate that runs only after the dialog still
        // refuses above, but the dialog was already on screen (#681).
        expect(ipcState.dialogOpens).toBe(0)
      })
    }
  }

  it('read-only / in-memory channels still resolve when locked (getLogTail, getRuntimeStatus, the chat stream registry)', async () => {
    ipcState.handlers.clear()
    initLogging(tmp) // deterministic buffering state (no key attached → pre-unlock diagnostics)
    registerCoreIpc(lockedCtx(tmp))
    registerModelIpc(lockedCtx(tmp))
    registerChatIpc(lockedCtx(tmp))

    const tail = await invoke(handlers, IPC.getLogTail)
    expect(Array.isArray(tail.result)).toBe(true)

    const status = await invoke(handlers, IPC.getRuntimeStatus)
    expect(status.result).toMatchObject({ running: false })

    // The chat stream registry: Stop, the remount read and the in-flight list touch no ctx.db.
    await expect(invoke(handlers, IPC.stopGeneration, 'no-such-conv')).resolves.toBeDefined()
    expect((await invoke(handlers, IPC.getActiveStream, 'no-such-conv')).result).toBeNull()
    expect((await invoke(handlers, IPC.listActiveStreamConversations)).result).toEqual([])
  })

  // DX-4: close the enumeration loop. Glob EVERY `register*Ipc` export from the source tree and
  // assert each is accounted for — either driven HERE (MODULES) or in COVERED_ELSEWHERE with a
  // reason. A new register*Ipc module added uncovered lands in `unaccounted` and reds this; a
  // module renamed/removed without updating the lists lands in `stale`. Discovery reads the source
  // files (regex on the `export function register*Ipc` declaration) rather than importing them, so
  // it needs no module side effects and matches what an author greps.
  it('every register*Ipc module is enumerated here or in COVERED_ELSEWHERE (DX-4 drift guard)', () => {
    const ipcDir = join(__dirname, '../../src/main/ipc')
    const discovered = new Set<string>()
    for (const file of readdirSync(ipcDir)) {
      if (!file.startsWith('register') || !file.endsWith('Ipc.ts')) continue
      const src = readFileSync(join(ipcDir, file), 'utf8')
      for (const m of src.matchAll(/export function (register\w*Ipc)\b/g)) discovered.add(m[1])
    }
    // Sanity: the glob actually found the modules (a broken path would vacuously pass).
    expect(discovered.size).toBeGreaterThanOrEqual(MODULES.length)

    const accounted = new Set<string>([
      ...MODULES.map((m) => m.name),
      ...Object.keys(COVERED_ELSEWHERE)
    ])
    const unaccounted = [...discovered].filter((n) => !accounted.has(n)).sort()
    const stale = [...accounted].filter((n) => !discovered.has(n)).sort()
    // A new module appears in `unaccounted` (add it to MODULES or COVERED_ELSEWHERE with a reason);
    // a removed/renamed module appears in `stale` (drop it from the lists).
    expect({ unaccounted, stale }).toEqual({ unaccounted: [], stale: [] })
  })
})