Skip to content

AI, fully local on your computer.

39.9 KB
Raw Blame
// Central registry of IPC channel names so main + preload never drift.
export const IPC = {
  getAppStatus: 'app:getAppStatus',
  /**
   * One-way renderer timing mark for opt-in measurement runs (services/perf.ts). The
   * main-side listener enforces a hard event allowlist and is a no-op unless
   * HILBERTRAUM_PERF_LOG=1 is set in the environment.
   */
  perfMark: 'perf:mark',
  /**
   * #888: the window's one-way answer to `EVENTS.saveBeforeClose` — `{ requestId, unsaved }`, sent
   * by the preload itself once the renderer's save settles. An `ipcMain.on` listener per request
   * (`main/close-guard.ts`), not a `guardedHandle`: it checks the sender and the request id
   * itself, and it must answer while the workspace is locked too.
   */
  saveBeforeCloseDone: 'app:saveBeforeCloseDone',
  getDriveStatus: 'app:getDriveStatus',
  getSettings: 'settings:get',
  updateSettings: 'settings:update',
  // Privacy/offline policy
  getPolicy: 'policy:get',
  // Local API endpoint (opt-in loopback server). Everything else about it rides
  // `settings:update` (the toggles + port) and `app:getAppStatus` (live state); these
  // three exist because the access key must NEVER cross to the renderer in full.
  /** `{ serverAddress, maskedKey }` — what to paste into a client, key masked. */
  localApiConnectionInfo: 'localApi:getConnectionInfo',
  /** Copy the FULL key to the clipboard MAIN-side (the renderer never holds it). */
  localApiCopyKey: 'localApi:copyKey',
  /** Mint a new key + abort active/queued external streams; returns the new mask. */
  localApiRegenerateToken: 'localApi:regenerateToken',
  // Models + runtime
  listModels: 'models:list',
  selectModel: 'models:select',
  /**
   * Force a REAL re-hash of one model's weight file (drops the persisted checksum
   * cache entry first) — the Models screen's "Verify checksum" button. `listModels`
   * itself reads through the cache and never re-hashes an unchanged file.
   */
  verifyModel: 'models:verify',
  /**
   * Cancel one in-flight DISPLAY-side verification pass (#420) — the Models screen's "Check
   * all model files", a 25-minute operation on a slow drive that the user starts on purpose
   * and must be able to stop. Takes the run id the RENDERER minted and passed to
   * `listModels`, which is also the `runId` tagging that pass's `modelVerifyProgress`
   * events; resolves `true` if a pass was found and aborted, `false` if nothing was running
   * under that id (a no-op, never an error). Cancelling is not a failure: the pass returns a
   * complete model list in which what finished is verified from the cache and the rest is
   * simply unchecked. It can never reach the §7.4 start gate's own hash, the per-model
   * "Verify checksum" button or the ship-time gates — none of them pass a signal, and a hash
   * shared with an uncancellable caller (#106 single-flight) keeps running for that caller.
   * NOT gated on the unlocked workspace, for the same reason `stopRuntime` is not: it only
   * stops work that is already running and touches no database.
   */
  cancelModelVerify: 'models:cancelVerify',
  startRuntime: 'runtime:start',
  /**
   * The Models screen's one primary action per installed chat card (beta #27, D70): make a
   * model the active selection AND start its runtime, MAIN-side, so the install/RAM gates run
   * once and the audit trail is one event chain (`model_selected` then `runtime_started`). A
   * non-chat role is rejected before anything is persisted; a start failure leaves the fresh
   * selection standing (auto-start + a retry cover it — same posture as the old Select button).
   */
  useModel: 'runtime:use',
  stopRuntime: 'runtime:stop',
  /**
   * #599: start the running model again with its own start options — the AI Model card's "Restart"
   * for a model that stopped responding. Gated on the unlocked workspace like `startRuntime`.
   * Resolves the new status, or null when no model runs.
   */
  restartRuntime: 'runtime:restart',
  /** Read-only runtime health/state for Diagnostics (spec §7.11). */
  getRuntimeStatus: 'runtime:status',
  /** The drive's installed sidecar build (the .hilbertraum-runtime.json marker). */
  getRuntimeInstall: 'runtime:install',
  // Chat
  createConversation: 'chat:createConversation',
  listConversations: 'chat:listConversations',
  listMessages: 'chat:listMessages',
  sendChatMessage: 'chat:send',
  stopGeneration: 'chat:stop',
  /** Persist a conversation's sticky default skill (skills plan §10.1; null clears). */
  setConversationDefaultSkill: 'chat:setDefaultSkill',
  /** Deterministic skill suggestion for the composer picker (skills plan §10.2/S8; logs nothing). */
  suggestSkills: 'skills:suggest',
  /**
   * Snapshot of an in-flight generation for a conversation (accumulated answer +
   * reasoning), or null if none — lets a remounted Chat screen recover a reply that is
   * still streaming after the user navigated away and back.
   */
  getActiveStream: 'chat:activeStream',
  /**
   * The conversation ids that currently have a generation IN FLIGHT (in-memory only). A Chat
   * screen that mounts fresh (the user navigated away and back) has forgotten which conversation
   * it was streaming — this lets it re-select the still-generating one and re-attach via
   * getActiveStream, instead of showing an empty new chat while the reply streams invisibly.
   */
  listActiveStreamConversations: 'chat:activeStreamConversations',
  /** Delete a conversation (chat or document Q&A) and all of its messages. */
  deleteConversation: 'chat:deleteConversation',
  /** Replace a documents-conversation's "ask selected documents" scope. */
  updateConversationScope: 'chat:updateScope',
  /** Persist a conversation's composite source scope (`scope_v2_json`, plan D1). */
  setConversationScope: 'chat:setScope',
  /** Persist a conversation's creation-anchor project (`collection_id`, plan §13.4). */
  setConversationCollection: 'chat:setCollection',
  /** A conversation's temporary chat attachments (`conversation_documents`, plan C3/§16). */
  listAttachments: 'chat:listAttachments',
  /** Save a conversation transcript to a user-chosen file (spec §7.6). */
  exportConversation: 'chat:export',
  /** Save one message's attached RESULT TABLE as CSV to a user-chosen file (result-tables §4). */
  exportMessageTable: 'chat:exportMessageTable',
  /** #286: save ONE fenced code block of an assistant reply to a user-chosen file. The bytes are
   *  renderer-supplied (the parsed block content + fence info string), not DB-derived: main only
   *  validates the types, maps the info string through the fixed extension allowlist
   *  (`shared/code-block-export.ts`) and writes verbatim (no BOM) behind the native save dialog. */
  saveCodeBlock: 'chat:saveCodeBlock',
  /** Full-text search across conversations. Queries are content: never logged/audited. */
  searchConversations: 'chat:search',
  /**
   * Resting-state context-window usage for a conversation (context-compaction plan §5.1): the
   * assembled-prompt token ESTIMATE over the model's launched window. Read-only, no model call;
   * recomputed on conversation load + after each turn (live is not required). Returns null for an
   * unknown conversation.
   */
  getConversationContextUsage: 'chat:contextUsage',
  /**
   * The latest compaction checkpoint's summary + where its marker sits in the rendered transcript
   * (context-compaction plan §5.3, D-b): `{ summary, beforeMessageId }` — the id of the first
   * rendered turn the summary does NOT subsume (the marker renders before it), or null when no
   * checkpoint has been cut. Read-only; the summary is local context, never leaves the device.
   */
  getConversationSummary: 'chat:conversationSummary',
  /** Tail of the local log for Diagnostics (spec §7.11). Never uploaded. */
  getLogTail: 'logs:tail',
  /** Save the full local log to a user-chosen file (plaintext, a deliberate user action). */
  exportLog: 'logs:export',
  /** Write text to the OS clipboard from MAIN — the sandboxed preload has no `clipboard`. */
  writeClipboard: 'clipboard:write',
  // Documents
  pickDocuments: 'docs:pick',
  importDocuments: 'docs:import',
  /** What a picked selection contains (file/audio counts + audio bytes) — the
   *  renderer's size-aware audio import confirmation. Read-only. */
  importPreflight: 'docs:importPreflight',
  getImportJob: 'docs:getImportJob',
  /** The in-flight import job (or null) — parameterless so the Documents screen re-attaches its
   *  progress poll on mount without holding the job id across an unmount (DOC-1, #141). */
  getActiveImportJob: 'docs:getActiveImportJob',
  listDocuments: 'docs:list',
  /** Add documents to a collection (membership; idempotent). "Move" = add + remove. */
  addToCollection: 'docs:addToCollection',
  /** Remove documents from a collection (membership only; documents untouched). */
  removeFromCollection: 'docs:removeFromCollection',
  /** Set documents' retention lifecycle ('permanent'|'temporary'|'archived'). */
  setDocumentLifecycle: 'docs:setLifecycle',
  deleteDocument: 'docs:delete',
  reindexDocument: 'docs:reindex',
  /** Start a bulk re-index ("Re-index all" stale / "Retry all" failed). Main owns the job so its
   *  progress survives navigation; returns the initial ReindexJobStatus. Idempotent while running. */
  startReindexAll: 'docs:startReindexAll',
  /** Current bulk re-index job (or null) — parameterless so the renderer recovers the progress
   *  bar on mount without holding the job id across an unmount. */
  getReindexAllJob: 'docs:getReindexAllJob',
  /** Stop the in-flight bulk re-index. The current document finishes; the rest are skipped and the
   *  job ends with `cancelled: true`. No-op when nothing is running. */
  cancelReindexAll: 'docs:cancelReindexAll',
  /** Read-only in-app preview: re-extract the stored copy's text (FE-6: the BOUNDED first page). */
  previewDocument: 'docs:preview',
  /** FE-6: a subsequent bounded page of a document preview (offset/limit + cursor). */
  previewDocumentPage: 'docs:preview-page',
  /** Save a text document's stored content to a user-chosen file (the
   *  exportConversation pattern; enables exporting materialized translations). */
  exportDocument: 'docs:export',
  /** Save a document's stored ORIGINAL bytes — any format — to a user-chosen file (#90).
   *  Deliberately a NEW channel: `docs:export` stays text-only (the Translate screen
   *  shares its semantics); this is its binary sibling (atomic write, ids-only audit). */
  exportDocumentOriginal: 'docs:exportOriginal',
  /** Save a document's persisted summary (Markdown) to a user-chosen file
   *  (the exportDocument pattern: dialog + fs in MAIN). */
  exportSummary: 'docs:exportSummary',
  // Document tasks (async with polling, like imports/downloads)
  /** Start a document task (summary, translation; compare rides the same machine). */
  startDocTask: 'doctasks:start',
  /** Poll one task's state/progress. */
  getDocTask: 'doctasks:get',
  /** The currently RUNNING task's status (a copy), or null when idle — the #38 chain-adopt read. */
  getActiveDocTask: 'doctasks:getActive',
  /** Running + queued tasks in lane order (copies) — the file-translation reload-adoption read
   *  (#157 DT-5: a translation queued behind a foreign task must be adoptable too). */
  listActiveDocTasks: 'doctasks:listActive',
  /**
   * Cancel a task. With NO jobId, cancels the currently active one (the chat busy banner). With a
   * PRESENT jobId it is a TARGETED exact-id cancel, running OR queued (#157 DT-2). Stale-Stop-safe
   * (FA-3 / F-6): a settled task is terminal (no-op) and a newer task has a different id.
   */
  cancelDocTask: 'doctasks:cancel',
  /**
   * Read-only coverage + provenance of a document's current summary (whole-document-analysis
   * plan §5.1): how much of the document it covers (breadth) at what depth (tier), and the
   * source-chunk lineage behind a deep-index summary. No model call. Content stays in the DB.
   */
  documentCoverage: 'analysis:coverage',
  /**
   * Read-only "list every X" aggregation (whole-document-analysis plan §4.2/§5.1, Phase 3):
   * a pure GROUP BY over the precomputed `extraction_records` for one record type within a
   * scope — ZERO model calls. Returns the provenance-backed list + the honest coverage line
   * inputs (sections scanned/total/unparsed). Content stays in the DB (never logged/audited).
   */
  listAllExtractions: 'analysis:listAll',
  askDocuments: 'rag:ask',
  // Voice dictation (request/response; bytes in, text out, nothing stored)
  /** Transcribe recorded composer audio (16 kHz mono WAV bytes) into plain text. The
   *  recording is content: never logged, never audited, shredded after transcription. */
  transcribeDictation: 'dictation:transcribe',
  // In-app model downloader (async with polling, like imports)
  /** Start downloading one model's weights (gated: policy ∧ setting ∧ confirmation). */
  downloadModel: 'downloads:start',
  /** Poll one download job's progress/status. */
  getDownloadJob: 'downloads:get',
  /** Cancel an in-flight download (the `.part` file is kept for a future resume). */
  cancelDownload: 'downloads:cancel',
  /** #314: every download a reloaded renderer still has to show — the live job (if any) plus
   *  the undismissed unresolved results. Needs no job id, so it re-attaches after a reload. */
  listDownloadJobs: 'downloads:list',
  /** #314: the user dismissed a terminal result; `downloads:list` stops offering it. */
  dismissDownloadJob: 'downloads:dismiss',
  // In-app engine (llama.cpp sidecar) downloader — fetches the real runtime so models
  // stop falling back to the built-in demo runtime. Same gates as model downloads.
  /** Is the llama.cpp engine installed, and can it be fetched for this host? */
  getEngineStatus: 'engine:status',
  /**
   * #843: what a `downloadEngine` request would fetch (`EngineDownloadPreview`), for its confirmation
   * dialog. Takes the same optional payload; read-only (no network, no write).
   */
  getEnginePlan: 'engine:plan',
  /** Start fetching + extracting the host's llama-server build (gated: policy ∧ setting). */
  downloadEngine: 'engine:download',
  /** Poll the engine-download job's progress/status. */
  getEngineJob: 'engine:getJob',
  /** Cancel an in-flight engine download. */
  cancelEngineDownload: 'engine:cancel',
  /**
   * #530 "Check again": start each engine the OS refused once more; the ones it now accepts lose
   * their verdict and every latch the refusal left is re-armed. Resolves `EngineRecheckResult`.
   * Takes no payload. Spawns only drive-local programs — no network.
   */
  recheckEngine: 'engine:recheck',
  // In-app OCR language-file install (#410) — its own narrow installer, not an engine family.
  // Same gates as model/engine downloads. Never the `OCR_RASTER` channels (the rasterizer window).
  /** The dialog facts: pinned languages + sizes + installed, bytes to fetch, source host, licence. */
  getOcrInstallStatus: 'ocr:status',
  /** Start fetching the pinned OCR language files (no payload; gated: policy ∧ setting). */
  installOcr: 'ocr:install',
  /** Poll the OCR install job's progress/status/outcome. */
  getOcrInstallJob: 'ocr:getJob',
  /** Cancel an in-flight OCR install. */
  cancelOcrInstall: 'ocr:cancel',
  // Image understanding (vision) — image-understanding plan §9.1. A separate lazy
  // `llama-server --mmproj` sidecar answers a question about ONE image. Async-with-streaming
  // (the STREAM.img* channels below); `getStatus` is workspace-agnostic, the file/runtime
  // handlers requireUnlocked. No image/prompt/answer content is logged or audited.
  /** Is image understanding available (runtime + a verified vision model + projector)? */
  imageGetStatus: 'images:getStatus',
  /** Open the OS picker (png/jpg/jpeg/webp, plus "All files"); returns `{ token, name, sizeBytes }`
   *  or null. The absolute path stays in main; the token is one-time (D2). */
  imageChooseImage: 'images:chooseImage',
  /** Read a picked image's bytes by its picker token (main owns file I/O); re-validates
   *  extension + byte cap. */
  imageReadBytes: 'images:readBytes',
  /** Start a one-at-a-time analyze (validates extension/cap/question); a second one is busy. */
  imageAnalyze: 'images:analyze',
  /** Cancel an in-flight analyze (AbortController). */
  imageCancel: 'images:cancel',
  /** Poll one analyze job's state (unknown jobId ⇒ terminal failed). */
  imageGetJob: 'images:getJob',
  /** List saved image-analysis history entries (newest first; no image bytes). */
  imageListSessions: 'images:listSessions',
  /** Open one history entry: metadata + DECRYPTED image bytes + all turns. */
  imageGetSession: 'images:getSession',
  /** Delete one history entry: shred the stored image + cascade-remove its turns. */
  imageDeleteSession: 'images:deleteSession',
  /** Clear the WHOLE image history (#122): one transactional row sweep + post-commit shreds. */
  imageClearSessions: 'images:clearSessions',
  // Translate view (TG-4) — the Translate screen's live TEXT translation on the TranslateGemma
  // sidecar. Async-with-streaming (the STREAM.tr* channels below), keyed by jobId, mirroring the
  // image job contract. No source/translation CONTENT is logged or audited (ids/kinds only).
  /** Start a one-at-a-time text translation (validates langs + source≠target + a model present);
   *  a second one while one runs is busy, a document task holds the lane returns docTaskBusy. */
  translateStart: 'translate:start',
  /** Cancel an in-flight text translation (AbortController). */
  translateCancel: 'translate:cancel',
  /** The active view-translation job (accumulated text + progress) for remount recovery, or null. */
  translateGetActive: 'translate:getActive',
  // Benchmark
  runBenchmark: 'benchmark:run',
  /** The Performance screen's one read: last result, per-machine history, observed figures. */
  getPerformance: 'performance:get',
  /**
   * What the moved-drive check did for this unlock session (`MovedDriveNotice | null`) — Home's
   * one-shot read, re-read on `performance:changed`. Session state, not settings: after a restore
   * nothing in the store distinguishes "restored just now" from an ordinary same-machine launch.
   */
  getMovedDriveNotice: 'benchmark:moved-drive-notice',
  /**
   * "Try GPU again": clears `gpuAutoDisabled`/`gpuLastError`,
   * invalidates the session probe cache, re-probes + persists, returns fresh settings.
   */
  tryGpuAgain: 'gpu:try-again',
  // Non-technical first-run launch preflight
  runPreflight: 'preflight:run',
  // Audit log (the Diagnostics Activity panel; spec §7.11, local-only)
  /** Page through audit events, newest-first (`limit`, optional `beforeId` cursor). */
  getAuditEvents: 'audit:list',
  /** Save the activity log to a user-chosen file (the exportConversation pattern). */
  exportAuditLog: 'audit:export',
  // Knowledge packs (ZIM wave). Handlers in registerZimIpc.ts; all DB-backed and
  // requireUnlocked. Audit metadata is ids/counts only (pack titles/filenames are content).
  /** All registered packs — DATABASE-ONLY (#301 P3b, finding L7): no filesystem probe, no
   *  availability write. `reconcile()` (session start, and `packs:refresh`) is what discovers
   *  new drive files and heals availability — `KnowledgePack[]`. */
  listKnowledgePacks: 'packs:list',
  /** Open the native .zim picker AND register the chosen archives (dialog + registration in ONE
   *  main-side handler — no renderer-supplied path ever reaches registration). Returns the typed
   *  `KnowledgePackAddResult` DTO (#301 P5, finding L1): cancelled/success/partial/failure, the
   *  packs actually added, the failure count and a failure-reason CODE — never raw manager
   *  stderr or a path. */
  addKnowledgePacks: 'packs:add',
  /** Remove a registration (never touches the archive file). */
  removeKnowledgePack: 'packs:remove',
  /** Enable/disable a pack (a disabled pack stays registered but is never queried). */
  setKnowledgePackEnabled: 'packs:setEnabled',
  /** Whether kiwix-tools is installed, and whether a reconciliation is currently running
   *  (feature + refreshing-state for the UI) — `KnowledgePackStatus`. */
  getKnowledgePackStatus: 'packs:status',
  /** Kick off a background reconciliation pass (drive discovery + availability heal) at the
   *  user's request; schedules and returns `{ started: true }` at once — completion arrives via
   *  `EVENTS.knowledgePacksChanged` (#301 P3b, finding L7). The friendly locked copy when the
   *  workspace does not admit work. */
  refreshKnowledgePacks: 'packs:refresh',
  /** Read one article from a pack for the citation viewer — plain sectioned TEXT
   *  (`PackArticle`), resolved MAIN-side over the loopback sidecar; null when unavailable. */
  getPackArticle: 'packs:getArticle',
  /** Save one pack article as a REAL document in the corpus (#340 Tier-2, D-Z21): the text is
   *  re-read MAIN-side (only `packId` + `articlePath` cross the bridge) and run through the one
   *  import path; resolves `PackArticleSaveResult`. A second save of the same entry returns the
   *  existing document (`alreadySaved`). Locked ⇒ the friendly locked copy. */
  savePackArticle: 'packs:saveArticle',
  // Document organization — collections (projects + built-ins). Handlers in
  // registerCollectionsIpc.ts; membership/lifecycle live on the docs: namespace above.
  /** All collections (built-ins first, then projects by name). */
  listCollections: 'collections:list',
  /** Create a project. */
  createCollection: 'collections:create',
  /** Rename a collection (built-ins included, but the UI never offers it for built-ins). */
  renameCollection: 'collections:rename',
  /** Archive / unarchive a project (a scope-target change, not a global exclusion — C1). */
  setCollectionArchived: 'collections:setArchived',
  /** Delete a project: 'membershipOnly' (keep docs) or 'withDocuments' (delete project-only docs — C2). */
  deleteCollection: 'collections:delete',
  // Skills (instruction packages; skills plan §16). Handlers in registerSkillsIpc.ts; all
  // DB-backed handlers requireUnlocked and resolve validation MAIN-side. Audit metadata is
  // ids/counts only (§22-M1).
  /** All installed skills (app first, then by title) — `SkillInfo[]`. */
  listSkills: 'skills:list',
  /** One skill by install id — `SkillInfo | null`. */
  getSkill: 'skills:get',
  /** Open the OS picker for a `.skill.zip` file or a skill folder; returns the chosen path or null. */
  pickSkillPackage: 'skills:pick',
  /** Validate an import source FULLY in a transient dir, WITHOUT writing — `SkillPreview` (§9.2/OQ-2). */
  previewSkillPackage: 'skills:preview',
  /** Validate → unzip/copy into user-skills/<id>/ → install enabled-with-warning (DS7) — `SkillInfo`. */
  importSkill: 'skills:import',
  /** Export a skill as a `.skill.zip` via the save dialog (package tree only — §9.5). */
  exportSkill: 'skills:export',
  /** Delete a user skill: rm folder + row + clear refs in one txn (C3). App skills refuse. */
  deleteSkill: 'skills:delete',
  /** Enable a skill (one-active-per-id: disables same-id siblings — DS12). */
  enableSkill: 'skills:enable',
  /** Disable a skill (invisible to the picker, never injected). */
  disableSkill: 'skills:disable',
  /** Acknowledge a user skill's import warning (DS7 — clears the persistent warning state). */
  acknowledgeSkillWarning: 'skills:acknowledgeWarning',
  /**
   * Structural summary of the last disk reconcile's discovery errors — `SkillReconcileStatus`
   * (SKA-32, skills audit 2026-07-03, U7). Counts + fixed reason codes ONLY (never folder names or
   * package content — §22-M1); drives the Settings → Skills "N folders could not be read" notice.
   */
  skillReconcileStatus: 'skills:reconcileStatus',
  // Tier-2 app-orchestrated tool runs (skills plan §12.2/§16, S11b). Generic `skills:*` shape (NOT
  // bank-named) so S11c's tools slot in with no renderer/IPC change; bank specifics stay in the
  // `tool-runs.ts` dispatch + `run.ts` seam (§13). All requireUnlocked; the document scope is
  // resolved MAIN-side from the conversation (§22-C4) and NOTHING content-bearing is logged.
  /** Wired, runnable tools for the active skill in this conversation's scope (empty when none apply). */
  listRunnableTools: 'skills:listRunnableTools',
  /** Start a run from a user action; returns the initial state or a needs-confirmation/error signal. */
  startSkillRun: 'skills:startToolRun',
  /** Poll one run's ids/counts-only state/progress (the doc-task polling precedent). */
  getSkillRun: 'skills:getToolRun',
  /**
   * All runs the controller currently holds (running + terminal-but-unacknowledged), ids/counts only
   * (SKA-17, skills audit 2026-07-03, U6). Lets a freshly-reloaded renderer re-adopt in-flight runs
   * (its module-level store died with the reload; main kept them) — the `listActiveStreamConversations`
   * precedent, for skill runs. Content-free: each entry is a `SkillRunState` (state/progress/counts +
   * the content-free conversation/document ids), never the extracted rows. */
  listSkillRuns: 'skills:listToolRuns',
  /** Cancel a run by handle (aborts its `AbortSignal`); an empty handle is a no-op (SKA-25). */
  cancelSkillRun: 'skills:cancelToolRun',
  /** Drop a terminal run main-side once the renderer has shown its outcome (the acknowledge handshake). */
  clearSkillRun: 'skills:clearToolRun',
  // Evidence Pack / Review Mode (EP-1 plan §6.4, spec §19). Handlers in
  // registerEvidenceReviewsIpc.ts; ALL DB-backed → every one requireUnlocked. The renderer
  // sends ids + user-entered review text ONLY (spec §19 security rules) — snapshots, source
  // resolution and derived state are main-side. Audit metadata is ids/counts only.
  /** Create the draft review for one assistant message (idempotent: an existing review is
   *  returned, never duplicated). No model call, no network — persisted data only. */
  createEvidenceReview: 'evidence:create',
  /** The full review read-model (`EvidenceReviewDetail`), or null on an unknown id. */
  getEvidenceReview: 'evidence:get',
  /** EVERY review in one conversation as light `EvidenceReviewSummary[]` — the transcript's
   *  whole chip state in ONE round trip (AUD-12). Asking per message made opening a
   *  conversation cost one serial invoke (plus a full item load and a freshness recompute)
   *  per candidate answer, so the latency grew with the history length. Empty array for an
   *  unknown/malformed id, matching the other unknown-id results. */
  getEvidenceReviewSummariesForConversation: 'evidence:summariesForConversation',
  /** Patch head fields (title D-6 / reviewer label D-3 / general note); null on unknown id. */
  updateEvidenceReview: 'evidence:update',
  /** Patch one item's decision/note; null on unknown id. */
  updateEvidenceReviewItem: 'evidence:updateItem',
  /** Apply ONE conservative bulk decision action (`EvidenceReviewBulkAction`) to a whole
   *  review in a single transaction (AUD-13) → the refreshed `EvidenceReviewItem[]`, or
   *  null on an unknown id, an unrecognized action, and on a READY review (reopen first).
   *  A fan-out of per-item writes could crash half-applied; this cannot. The forbidden
   *  blanket "mark all supported" has no name in the union, so it cannot be requested. */
  applyEvidenceReviewBulkAction: 'evidence:bulkAction',
  /** Carve a reviewer selection from one block (UTF-16 offsets into its `textSnapshot`);
   *  null = refused (unknown block, out-of-range or surrogate-splitting offsets). */
  createEvidenceSelection: 'evidence:createSelection',
  /** Delete a reviewer SELECTION (block items are structural and refuse). */
  deleteEvidenceSelection: 'evidence:deleteSelection',
  /** Upsert one item→source link; null on unknown item/source key. */
  setEvidenceLink: 'evidence:setLink',
  /** Remove one item→source link. */
  removeEvidenceLink: 'evidence:removeLink',
  /** Mark ready (D-7 gated) — returns `{ review, gate }`; refuses (gate says why) while
   *  required items are undecided. Null on unknown id. */
  markEvidenceReviewReady: 'evidence:markReady',
  /** Reopen a ready review to draft (spec §18.4). Null on unknown id. */
  reopenEvidenceReview: 'evidence:reopen',
  /** Freshness check (spec §21.2, real since Phase 4): compare the review snapshot against
   *  the CURRENT workspace from STORED facts only — document existence by snapshotted id,
   *  stored `documents.sha256` vs snapshot hash (never re-hashed), answer text, coverage.
   *  → `EvidenceReviewFreshness | null` (null on unknown id). Unresolved identities stay
   *  'unverifiable' — never reported as changed. No model, no network, no file I/O. */
  refreshEvidenceReviewState: 'evidence:refreshState',
  /** Acknowledge the CURRENT drift of an outdated review (spec §15.5/§28.6): persists the
   *  drift fingerprint + stamp (additive nullable column; never touches status or
   *  completed_at — §18.4) and unlocks export. No-op on a non-outdated review. Returns the
   *  refreshed `EvidenceReviewFreshness | null`. */
  acknowledgeEvidenceReviewFreshness: 'evidence:acknowledgeFreshness',
  /** Source-in-context (D-5, spec §10.2.4): STORED extracted text around one snapshotted
   *  source's persisted excerpt. The renderer passes the review id + source KEY only —
   *  main resolves the snapshotted documentId (never a renderer-supplied id/path). Null on
   *  unknown review/key and on unresolved-identity sources. Reads the `chunks` table —
   *  never the source file. */
  getEvidenceSourceContext: 'evidence:sourceContext',
  /** How many reviews a conversation's messages carry — the D-2 delete-confirm warning
   *  count (spec §25.4). Added in Phase 2 (plan §7.6): the P0 service function existed
   *  without a channel; the renderer confirm needs the number. Count only — no content. */
  countEvidenceReviewsForConversation: 'evidence:countForConversation',
  /** Export the review as a self-contained HTML evidence pack (plan §8.3, spec §16/§17.2/
   *  §20): save dialog → deterministic render → ATOMIC write (tmp sibling → fsync →
   *  sha256 → rename) → `evidence_exports` row. Returns the export record, or null when
   *  the user cancelled / the id is unknown; a failure up to the rename leaves NO file and
   *  NO row (spec §28.9); a POST-rename record failure unlinks the file and rejects with
   *  honest localized copy (distinct message if even the unlink failed — the file then
   *  exists WITHOUT an export-history record). Registered in Phase 3 (per §8.3 as
   *  edited): Phase 1 deliberately shipped without it — a dead channel would have been a
   *  false promise. No model, no network. */
  exportEvidencePack: 'evidence:export',
  // Encrypted workspace lifecycle
  getWorkspaceState: 'workspace:getState',
  unlockWorkspace: 'workspace:unlock',
  createWorkspace: 'workspace:create',
  lockWorkspace: 'workspace:lock',
  /** Change the encrypted vault's password. Runs unlocked only. */
  changeWorkspacePassword: 'workspace:changePassword'
} as const

// Renderer-bound streaming event channels (main -> renderer).
// token/done/error are the LOCKED contract (one answer-token string per event;
// changes must be additive); `reasoning` is the ADDITIVE channel carrying the
// model's thinking deltas for Deep mode — answer tokens never travel on it and
// vice versa.
export const STREAM = {
  token: (requestId: string) => `chat:token:${requestId}`,
  done: (requestId: string) => `chat:done:${requestId}`,
  error: (requestId: string) => `chat:error:${requestId}`,
  reasoning: (requestId: string) => `chat:reasoning:${requestId}`,
  // ADDITIVE: a one-shot ephemeral notice fired before a document answer when retrieval
  // was auto-scoped to the file(s) the question named (never persisted — a live hint).
  scope: (requestId: string) => `chat:scope:${requestId}`,
  // ADDITIVE: a one-shot ephemeral notice fired the moment the context-compaction pre-pass
  // starts summarizing the older history for THIS turn (it adds latency before the first answer
  // token — context-compaction plan §5.2). Never persisted, not in `streamBuffers` (R14 — a
  // transient hint, fine to miss on remount); cleared in the renderer when answer tokens begin.
  compaction: (requestId: string) => `chat:compaction:${requestId}`,
  // ADDITIVE: the REAL assembled-prompt context usage for the in-flight turn (a ContextUsage
  // payload), fired once right after prompt assembly. A document answer injects the retrieved
  // excerpts / whole-document block into the prompt — content the renderer cannot see in the
  // persisted history, so its word-count estimate under-reads a doc turn by the entire document
  // ("meter says 7% while the window is full"). Ephemeral like `compaction` (R14): never
  // buffered, fine to miss on remount — the meter then falls back to the resting estimate.
  usage: (requestId: string) => `chat:usage:${requestId}`,
  // ADDITIVE (#290): ONE ephemeral `AnswerSpeed` payload per FINISHED chat answer — the runtime's
  // decode tokens/sec + token count (llama-server `timings`) and the user-felt time to first
  // token — fired right before `done`, keyed to the persisted message id. Never persisted, never
  // buffered (R14): a reload shows nothing on old messages, and the mock runtime (no timings)
  // never fires it. Plain chat answers only — not the hidden warm-up, document tasks, skill runs
  // or compaction. An aborted answer carries no timings and fires nothing.
  speed: (requestId: string) => `chat:speed:${requestId}`,
  // Image understanding (vision) per-job streaming (image-understanding plan §9.1). Mirrors the
  // chat token/done/error contract, keyed by analyze jobId: the vision sidecar emits SSE
  // byte-identical to chat (V1-confirmed), so `readChatSSE` forwards the deltas as imgToken.
  // imgDone carries the terminal ImageJob; imgError the failed ImageJob (a code, never content).
  imgToken: (jobId: string) => `images:token:${jobId}`,
  imgDone: (jobId: string) => `images:done:${jobId}`,
  imgError: (jobId: string) => `images:error:${jobId}`,
  // Translate view (TG-4) per-job streaming. Same token/done/error contract as chat/vision,
  // keyed by the translate jobId: trToken carries one translation-delta string; trDone the
  // terminal TranslateJob (with the COMPLETE `text`, so a mid-stream dropped token self-heals on
  // completion); trError the failed TranslateJob (a code, never source/translation content).
  trToken: (jobId: string) => `translate:token:${jobId}`,
  trDone: (jobId: string) => `translate:done:${jobId}`,
  trError: (jobId: string) => `translate:error:${jobId}`
} as const

/** Payload of the `scope` channel — the filenames retrieval was auto-restricted to. */
export interface ScopeNotice {
  titles: string[]
}

/**
 * Payload of the `compaction` channel (context-compaction plan §5.2). One-shot; `'start'` is the
 * only phase today (`'done'` is implicit when answer tokens begin), but the object shape leaves
 * room to grow without breaking the additive streaming contract.
 *
 * `kind` (U5 / audit §3.6) reuses this EPHEMERAL channel for a second kind of "working on it" notice:
 * `'analysis'` is fired when an exhaustive skill handler starts a potentially long, silent extraction
 * (the "one-blob answer reads as a hang" gap), so the renderer can show honest "reading the document…"
 * copy instead of the compaction "summarizing earlier messages…" line. Absent ⇒ `'compaction'` (the
 * original behaviour, byte-unchanged).
 */
export interface CompactionNotice {
  phase: 'start'
  kind?: 'compaction' | 'analysis'
}

/**
 * Payload of the `speed` channel (#290): how fast a FINISHED chat answer was generated. Session-
 * only — never persisted, never on the local API (`usage` there stays absent by decision,
 * local-api.md §6.5). Numbers only, never content.
 */
export interface AnswerSpeed {
  /** The persisted assistant message the figures belong to. */
  messageId: string
  /** Decode throughput from llama-server `timings.predicted_per_second` (tokens, not chunks). */
  tokensPerSecond: number
  /** User-felt wait from the send to the first answer token (prompt assembly, any compaction
   *  pre-pass and prefill included), in milliseconds. */
  ttftMs: number
  /** Generated tokens (`timings.predicted_n`). */
  tokens: number
}

/**
 * Channels between the main process and the HIDDEN OCR rasterizer window: the
 * window's whole job is rendering PDF pages to PNG bytes — the only step of
 * OCR that needs a canvas (recognition itself runs main-side). Pull-based: main
 * requests ONE page at a time, so a long scan never queues unbounded page images.
 * These channels are never exposed on the main window's bridge.
 */
export const OCR_RASTER = {
  /** main → ocr window: open this PDF — `{ pdf: Uint8Array }`. */
  open: 'ocr-raster:open',
  /** ocr window → main: the document opened — `{ pageCount }`. */
  opened: 'ocr-raster:opened',
  /** main → ocr window: render one page — `{ pageNumber }` (1-based). */
  render: 'ocr-raster:render',
  /** ocr window → main: one rendered page — `{ pageNumber, png: Uint8Array }`. */
  page: 'ocr-raster:page',
  /** ocr window → main: `{ message }` — the OCR task fails friendly. */
  error: 'ocr-raster:error'
} as const

// One-off main -> renderer notices (not tied to a request).
export const EVENTS = {
  /**
   * A friendly one-line runtime notice (the GPU crash auto-fallback's
   * "switched to compatibility mode" message — spec §11.4 tone, never alarming).
   */
  runtimeNotice: 'runtime:notice',
  /**
   * #888: the main window is about to close (an X, File → Exit, Cmd+Q, …) — save what is pending,
   * then answer on `IPC.saveBeforeCloseDone`. Payload: `requestId: number`, echoed in the answer.
   * Sent to the closing window only, at most once per close attempt (`main/close-guard.ts`).
   */
  saveBeforeClose: 'app:saveBeforeClose',
  /**
   * The step a running benchmark just finished (`BenchmarkProgressStep`), sent to the
   * renderer that started it so the Performance screen can show the steps as they land.
   */
  benchmarkProgress: 'benchmark:progress',
  /**
   * Payload-free invalidation for the Performance screen (PR #303 audit, G6): something the
   * `performance:get` snapshot reads has changed — re-read it. Broadcast to every live window,
   * only AFTER a mutation (a benchmark run starting or ending, an accepted read-speed sample,
   * the answer latch, a placement observation, a restore/backfill/probe write, a chat-runtime
   * transition, a resident sidecar loading or unloading, a settings key the snapshot reads) and
   * never from a getter, so a read can never trigger itself. The read stays gated (locked or
   * untrusted callers are still refused), the event carries nothing to gate.
   */
  performanceChanged: 'performance:changed',
  /**
   * Checksum-verification progress during `listModels` (`ModelVerifyProgress`). Emitted
   * to the calling renderer (`event.sender`) while first-run weight hashing runs, so the
   * first-run gate + first cold Models visit can show a determinate bar instead of an
   * opaque spinner. First-run-only in practice (the hash cache makes later passes a no-op).
   *
   * #420: `runId` is the RENDERER's id when it supplied one to `listModels` (the Models
   * screen's "Check all model files" always does), which makes it the handle
   * `cancelModelVerify` takes; otherwise main mints one, exactly as before. Either way the
   * renderer locks onto one pass by it. A cancelled pass still emits its terminal `done`
   * event, so the bar settles rather than lingering.
   */
  modelVerifyProgress: 'models:verifyProgress',
  /**
   * The registered knowledge-pack set changed (#301 P3b, finding L7) — `KnowledgePacksChangedEvent`.
   * Broadcast to EVERY window (not just the calling one, unlike `modelVerifyProgress`) on
   * reconciliation start/end and on register/remove/enable, so a mounted Chat/panel can refetch
   * without navigating away and back. A consumer ignores an event whose `epoch` is below the last
   * one it saw (an old session's late announcement).
   */
  knowledgePacksChanged: 'packs:changed',
  /**
   * Payload-free (#530): the session's engine verdict changed — an engine on the drive turned out
   * not to run on this computer, or "Check again" found that it runs now. Broadcast to every live
   * window; a mounted screen re-reads `AppStatus.engineProblems`.
   */
  engineProblemsChanged: 'engine:problemsChanged'
} as const