Skip to content

AI, fully local on your computer.

16.0 KB
Raw Blame
import type { Db } from './db'
import type { ResolvedPaths } from './workspace'
import type { WorkspaceController } from './workspace-vault'
import type { RuntimeManager } from './runtime'
import type { Embedder } from './embeddings'
import type { Reranker } from './reranker'
import type { Transcriber } from './transcriber'
import type { OcrEngine } from './ocr'
import type { Translator } from './translation'
import type { CachedGpuProbe } from './runtime/gpu'
import type { AuditRecorder } from './audit'
import type { DocTaskManager } from './doctasks'
import type { ZimService } from './zim'
import type { SkillRegistry } from './skills/registry'
import type { SkillRunController } from './skills/run-controller'
import type { VisionService } from './vision'
import type { TrustedSenders } from '../ipc/guarded-handle'
import type { TranslateJobService } from './translation/jobs'
import type { LocalApiServer } from './local-api/server'
import type { PlaintextOpsRegistry } from './ingestion/plaintext-ops'
import type { PendingModelSwitchCounter } from './rag/device-posture'
import type { TranscriberMissing } from '../../shared/types'
import type { ModelStartCheck } from './models'

// Shared application context assembled at startup and passed to IPC handlers.
export interface AppContext {
  paths: ResolvedPaths
  /**
   * WebContents ids allowed to invoke `ipcMain.handle` channels (#252): the main window's,
   * added in `createWindow`. Every registrar registers through `guardedHandleFor(ctx)`;
   * the fake test harness passes its permissive set (never used in production).
   */
  trustedSenders: TrustedSenders
  /**
   * The live workspace database. Backed by a getter over `workspace`: in
   * `plaintext_dev` mode it is open from startup; in `encrypted` mode it throws until
   * the vault is unlocked. Handlers read it at call time, so it tracks unlock/lock.
   */
  db: Db
  /** Owns the workspace lock/unlock lifecycle. */
  workspace: WorkspaceController
  runtime: RuntimeManager
  /** Embedder used for document ingestion + retrieval. */
  embedder: Embedder
  /**
   * Retrieval reranker: a third loopback sidecar, selected only when the
   * binary + the reranker GGUF exist. Null/absent = retrieval keeps today's ordering
   * (graceful-fallback rule — there is deliberately no mock reranker).
   */
  reranker?: Reranker | null
  /**
   * Audio transcriber: the whisper.cpp CLI behind the `Transcriber`
   * interface, selected only when the binary + the GGML weights exist. Null/absent =
   * audio imports fail per-file with friendly copy (graceful-fallback rule — there is
   * deliberately no mock transcriber). MUTABLE (#497): a null slot is RE-ASSIGNED by
   * `refreshTranscriberSlot` when a mid-session speech-model download or whisper.cpp engine
   * install makes the role available — consumers read it off ctx per call, never capture it.
   */
  transcriber?: Transcriber | null
  /**
   * Why `transcriber` is null (#527): the missing engine, the missing speech model, both, or an
   * engine with no build for this system. Set together with the slot — at startup and by every
   * `refreshTranscriberSlot` — so it always describes the same drive state; null while a
   * transcriber is selected. `getAppStatus` and the audio-import deps read it per call.
   */
  transcriberMissing?: TranscriberMissing | null
  /**
   * Local OCR engine: tesseract.js over the drive's vendored language
   * files, selected only when those exist. Null/absent = photo imports fail per-file
   * with friendly copy and detected scans show no "Make searchable" offer
   * (graceful-fallback rule — there is deliberately no mock OCR engine). MUTABLE (#410): the
   * in-app OCR installer runs `refreshOcrSlot`, which fills a null slot (or re-probes an engine
   * that could not start) — consumers read it off ctx per call, never capture it.
   */
  ocrEngine?: OcrEngine | null
  /**
   * TranslateGemma translation sidecar (TG wave, plan §2 D1): a SEPARATE lazy llama-server serving
   * the raw `/completion` endpoint (no `--jinja` — the #20305 regression). Selected only when the
   * binary + GGUF are present; null/absent = translation refuses with a friendly install path
   * (TG-3, O2 — deliberately no mock translator). Held for the session: `stop()` on quit,
   * `suspend()` on lock (it lazily restarts on the next translate), plus its own idle teardown.
   * MUTABLE (issue #40): starts as the startup composition's selection and is RE-ASSIGNED by
   * `onModelInstalled` when a mid-session download makes the role available — consumers must read
   * it off ctx per call (`ctx.translator`), never capture the value at wiring time.
   */
  translator?: Translator | null
  /**
   * Directory holding model-manifests, or null if it could not be located. The model list reads
   * it; a launcher start points it at the drive's copy (`HILBERTRAUM_MANIFESTS_DIR`).
   */
  manifestsDir: string | null
  /**
   * The app's OWN `model-manifests/` (`resolveBundledManifestsDir`: packaged, exactly
   * `resources/model-manifests`; dev, the checkout's), never `HILBERTRAUM_MANIFESTS_DIR`. The AI-engine
   * pins come from here, never from `manifestsDir` (#842: on a launcher start that is the drive's
   * copy, so a new app on a drive whose manifests were not refreshed compared the engine with the
   * drive's old pin and never offered its update). Also the OCR installer's second source list, per
   * file (#410, #841). Required, so no context can leave it out by accident; null reads as "no engine sources".
   */
  bundledManifestsDir: string | null
  /**
   * Session-cached GPU probe: `--list-devices` on a drive-local binary,
   * shared between the start ladder, Diagnostics, and the benchmark so they never
   * disagree within a session. `invalidate()` is wired to "Try GPU again" so an
   * explicit retry re-probes. Optional — absent in most test contexts.
   */
  probeGpu?: CachedGpuProbe
  /**
   * True for a dev build (`!app.isPackaged`). Treated as "developer" alongside the
   * user-toggleable `developerMode` setting (which defaults OFF on shipped builds).
   */
  isDev: boolean
  /**
   * Audit-log recorder: fire-and-forget, NEVER throws — an audit failure
   * (incl. a locked workspace) must never break the operation it records. Optional so
   * partial test contexts stay valid; call sites use `ctx.audit?.(…)`.
   */
  audit?: AuditRecorder
  /**
   * Document task engine: summary/translation/compare jobs, strictly
   * one-at-a-time. Optional so partial test contexts stay valid; the chat/RAG
   * handlers guard with `ctx.docTasks?.hasActiveTask()`.
   */
  docTasks?: DocTaskManager
  /**
   * Registry of the operations that materialise decrypted document content (preview, re-index,
   * import prepare, dictation, export) — the lock/quit teardowns abort it, await its settle and
   * shred whatever is still registered before the vault re-encrypts (#237). Optional so partial
   * test contexts stay valid; absent ⇒ nothing is registered and the teardowns skip the step.
   */
  plaintextOps?: PlaintextOpsRegistry
  /**
   * In-flight skill-run probe (GAP-5, full-audit 2026-07-11): true while the SkillRunController —
   * module-local to registerSkillsIpc, which assigns this at registration time — has a
   * non-terminal run on the document. The docs IPC delete/re-index guards consult it exactly like
   * `docTasks?.isDocumentBusy`: a delete or chunk rebuild under a suspended extraction would
   * interleave with the run (and, with FK enforcement off, orphan its bank/invoice rows).
   * Optional so partial test contexts stay valid.
   */
  skillRunActive?: (documentId: string) => boolean
  /**
   * #606: the skill-run lane's teardown handle, assigned by registerSkillsIpc like
   * `skillRunActive`. Lock and quit cancel every run before they stop the sidecars and await the
   * runs' settle before the vault re-encrypts; a stop or switch of the chat model cancels the runs
   * streaming on it (`endWorkOnModelStop`). Optional so partial test contexts stay valid.
   */
  skillRuns?: Pick<SkillRunController, 'cancelAll' | 'cancelModelRuns' | 'awaitSettled'>
  /**
   * #606: abort the running benchmark's speed leg, assigned by registerBenchmarkIpc. Lock and quit
   * call it before they stop the chat model, so the leg ends as a cancel rather than on the killed
   * socket; nothing is persisted. A model stop or switch does not: the run keeps its system, drive
   * and graphics legs and says the speed leg was skipped (#393). Optional (partial test contexts).
   */
  cancelBenchmark?: () => void
  /**
   * #782: internet access was switched off (`on` false) or back on — a real flip of the setting
   * (`settings:update`). Off stops each manager's running job: a transfer at once, a job checking
   * what it already has before its next request; `onStopped` runs when (and if) a job stops for it.
   * On withdraws a stop that has not come due. Assigned by registerDownloadIpc (model downloads) and
   * registerEngineIpc (engine and OCR installs). Optional (partial test contexts).
   */
  downloadsNetworkSwitched?: (on: boolean, onStopped: () => void) => void
  installsNetworkSwitched?: (on: boolean, onStopped: () => void) => void
  /**
   * The one-line notice every window shows (`runtime:notice`); `target: 'models'` gives it a button
   * to the AI Model screen. Assigned in index.ts, the same sender the runtime factories get.
   * Optional (partial test contexts).
   */
  runtimeNotice?: (message: string, target?: 'models') => void
  /**
   * In-flight ingestion probe (BE-1, ocr-audit 2026-07-18): true while the docs IPC import
   * loop or a re-index — the module-local `processing` set in registerDocsIpc, which assigns
   * this at registration time — is actively driving the document's row. The doc-task
   * manager's admission guard consults it (`DocTaskDeps.isDocumentProcessing`), the mirror
   * of `requireNoActiveTask`: a task admitted mid-re-index would interleave two ingestions
   * of the same document. Optional so partial test contexts stay valid.
   */
  docIngestionActive?: (documentId: string) => boolean
  /**
   * #516: true while the docs IPC import loop or a re-index is driving ANY document (the same
   * module-local `processing` set, assigned at registration). An engine update's pause would cut
   * off its embedding (or, for audio, its transcription), so the update waits for it. Optional so
   * partial test contexts stay valid.
   */
  ingestionActive?: () => boolean
  /** #516: true while any knowledge-pack article save is in flight (registerZimIpc assigns it). */
  articleSavesActive?: () => boolean
  /**
   * In-flight knowledge-pack article save (#340 Tier-2): true while `packs:saveArticle` is
   * driving this document's row through the import path (registerZimIpc assigns it). The docs
   * IPC guards treat it exactly like their own `processing` set — a delete or re-index under
   * the import would race it. Optional so partial test contexts stay valid.
   */
  articleSaveActive?: (documentId: string) => boolean
  /**
   * Skill registry (skills plan §8): the uniform disk-reconcile + state cache over the plain
   * app-skills/ + user-skills/ folders. Optional so partial test contexts stay valid. `reconcile`
   * needs an unlocked DB, so the live wiring reconciles best-effort at startup (plaintext_dev) and
   * later phases re-run it post-unlock; tests drive `reconcileSkills`/the handle directly.
   */
  skills?: SkillRegistry
  /**
   * Knowledge packs (ZIM wave): the registry + kiwix-serve sidecar facade. Optional so
   * partial test contexts stay valid; absent ⇒ the feature reads "not installed" and the
   * ask path never builds a ZIM arm. Quit calls `stop()` with the other sidecars.
   */
  zim?: ZimService
  /**
   * Knowledge-pack operation registry (#301, finding H4) — a SECOND instance of the
   * `plaintextOps` contract, dedicated to the ZIM operations (an ask's arm, an article read,
   * a registration incl. the native picker wait, the reconciliation). Separate from
   * `plaintextOps` so the lock/quit ZIM settle is its own bounded step and the paths it
   * tracks are only `zim-transient/` files, never a document transient. Optional so partial
   * test contexts stay valid; absent ⇒ the service's operations are local no-ops.
   */
  zimOps?: PlaintextOpsRegistry
  /**
   * Image-understanding (vision) sidecar orchestrator: a SEPARATE lazy llama-server with the
   * mmproj projector (image-understanding plan §10). Optional so partial test contexts stay
   * valid. Owns its own idle teardown; the lock/quit handlers also call `stop()` so its
   * in-memory image/prompt context never outlives a lock and no child orphans on quit.
   */
  vision?: VisionService
  /**
   * Translate-view job orchestrator (TG-4, plan §2 D6): the Translate screen's live TEXT
   * translation, streamed on the SHARED `translator` sidecar (a per-job service, NOT a second
   * model). Optional so partial test contexts stay valid. Owns only transient job state; the
   * lock/quit handlers call `stop()` so an in-flight job is aborted before the sidecar is
   * suspended (its next window would otherwise lazily respawn the just-killed server).
   */
  translateJobs?: TranslateJobService
  /**
   * The opt-in OpenAI-compatible loopback endpoint (local-api wave). Optional so partial
   * test contexts stay valid. Exists only while the workspace is unlocked AND
   * policy ∧ setting permit (D3/D7): started from the post-unlock seams via
   * `maybeStartLocalApi`, stopped in `runLockTeardown`/`performShutdown` (it holds no
   * child process — the listener dies with the app — but stop() aborts external streams
   * and closes sockets deterministically).
   */
  localApi?: LocalApiServer
  /**
   * Fired by the in-app download manager when a model download completes (issue #40, all files in
   * place). The live wiring (main/index.ts) re-runs the availability selectors that composed to
   * null at startup — the translation sidecar (#40) and the transcriber (#497; its engine-install
   * twin is `EngineDownloadManager.onInstalled` for `whisper_cpp`) — so a downloaded model
   * activates without an app restart. The reranker still needs a restart (unaudited); the
   * embedder is captured at wiring time (`getIngestionDeps` in main/index.ts) and stays
   * startup-frozen by design. The OCR engine is refreshed by its own installer, not by this hook
   * (#410 — `refreshOcrSlot`). Optional so partial test contexts stay valid; must never throw
   * (the manager guards regardless).
   */
  onModelInstalled?: (modelId: string) => void
  /**
   * Re-compose the translator slot when it is empty or holds a latched failed start — the
   * BE-7 rule (`shouldReplaceTranslator`), never a live sidecar. Shared by `onModelInstalled` and
   * the #530 engine re-arm (a chat-engine install, a successful "Check again"). Optional so partial
   * test contexts stay valid; never throws.
   */
  refreshTranslatorSlot?: () => void
  /**
   * #913: the start check every non-chat role runs before it spawns its model (`checkModelBeforeStart` over this
   * workspace's hash store, with the policy-aware leniency). Built in `main/index.ts` by `createModelStartCheck`;
   * held here so the mid-session re-compositions (`refreshTranscriberSlot` from both install hooks) give a refreshed
   * service the same check. Required (#913 review S3): a context built without it does not compile.
   */
  checkModel: ModelStartCheck
  /**
   * Wave 8 ruling (a): the per-call counter of `startModelRuntime` calls presently awaiting the
   * reranker's single-flight suspend after committing to a REAL model switch — shared between
   * `registerModelIpc.ts` (which increments/decrements it) and the reranker's posture/scope
   * resolution (which reads only its count, via `snapshotRerankerOccupancy`). One instance per
   * app session, created in `main/index.ts` and wired here. Required (#477): an optional field
   * with a silent zero-fallback at every read site made it possible to construct a context that
   * looks valid but never counts a pending switch, widening the GPU-contention window the
   * counter exists to close; a missing wiring is now a compile error, not a silently-inert
   * fallback.
   */
  pendingModelSwitches: PendingModelSwitchCounter
}