Skip to content

AI, fully local on your computer.

15.5 KB
Raw Blame
import { app } from 'electron'
import { guardedHandleFor } from './guarded-handle'
import { registerLogCopyHandlers } from './log-copy'
import { IPC } from '../../shared/ipc'
import type { AppContext } from '../services/context'
import { buildDriveStatus } from '../services/workspace'
import { getSettings, updateSettings } from '../services/settings'
import { applyUiLanguageSetting, tMain } from '../services/i18n'
import { workspaceAdmitsWork } from '../services/workspace-vault'
import { buildPolicyStatus, currentPolicyStatus } from '../services/policy'
import { applyLocalApiSettings } from '../services/local-api/lifecycle'
import { LOCAL_API_SETTINGS_KEYS } from '../../shared/local-api'
import { runPreflight } from '../services/preflight'
import { machineRamGb } from '../services/models'
import { log, readLogFull } from '../services/logging'
import { engineProblems } from '../services/runtime/engine-load'
import { saveTextExport } from './save-export'
import { notifyPerformanceChanged, PERFORMANCE_SETTINGS_KEYS } from './performance-notify'
import { RERANKER_POSTURE_SETTINGS_KEYS, rerankerPostureInputsChanged } from '../services/rag/device-posture'
import { SETTINGS_WRITERS, type MainSettingsKey, type RendererSettingsPatch } from '../../shared/settings-writers'

import type { AppSettings, AppStatus, PolicyStatus, PreflightResult } from '../../shared/types'

/**
 * #868: the part of a renderer's settings patch the renderer may write. A key `SETTINGS_WRITERS` marks
 * `main` (the workspace's mode, the active model ids, the benchmark, placement and GPU records, the
 * checksum cache) is dropped whatever its value, and so is a key that is no setting at all; the rest of
 * the patch is kept, never refused: a refusal would show the user a save error for a renderer bug they
 * cannot fix, and lose the keys that were fine.
 *
 * The result is a fresh object built from own keys only, so `__proto__` or `constructor` in the patch
 * cannot slip through the prototype. A key whose value is `undefined` writes nothing, so it is left out
 * of the result too, even a renderer-owned one: kept, it would still fire the hooks below (a
 * `settings_changed` audit event for a change that never happened, a Performance push, a local-API
 * re-apply). The log line names a dropped key only when it is a settings key (a fixed name from the
 * table) and its value is defined (the #858 rule); a key that is no setting is only counted, so
 * nothing the renderer made up reaches the log.
 */
function rendererWritablePatch(raw: Record<string, unknown>): RendererSettingsPatch {
  const kept: Array<[string, unknown]> = []
  const mainOwned: MainSettingsKey[] = []
  let notSettings = 0
  for (const key of Object.keys(raw)) {
    if (raw[key] === undefined) continue
    if (!Object.hasOwn(SETTINGS_WRITERS, key)) notSettings++
    else if (SETTINGS_WRITERS[key as keyof AppSettings] === 'renderer') kept.push([key, raw[key]])
    else mainOwned.push(key as MainSettingsKey)
  }
  if (mainOwned.length > 0 || notSettings > 0) {
    log.warn('Settings update ignored keys the renderer may not write', { mainOwned, notSettings })
  }
  return Object.fromEntries(kept) as RendererSettingsPatch
}

// IPC for app/drive status + settings, the privacy policy surface (`getPolicy`),
// and the policy-aware `offlineMode` (spec §9.1, §3.6).
export function registerCoreIpc(ctx: AppContext): void {
  const ipcHandle = guardedHandleFor(ctx)

  // #782: the switch says "When off, the app makes no internet calls", and the downloaders read their
  // gates only when a job starts. So switching it off stops what is using the network: a transfer at
  // once, a job checking what it already has before its next request (each manager's
  // `networkSwitched`); switching it back on first lets that job carry on. Each job that stops shows
  // the notice; one that needs no more network finishes without it. A fault here never fails the
  // save, which has already landed.
  const networkSwitched = (on: boolean): void => {
    const tell = (): void => ctx.runtimeNotice?.(tMain('main.download.stoppedNetworkOff'), 'models')
    for (const report of [ctx.downloadsNetworkSwitched, ctx.installsNetworkSwitched]) {
      try {
        report?.(on, tell)
      } catch (err) {
        log.warn('Telling the downloads that internet access was switched failed', { on, error: String(err) })
      }
    }
  }

  // F16 (audit-postmerge-2026-06-29): the settings get/update handlers touch ctx.db. The getter
  // fail-closes when locked but throws the raw English vault string; gate them with the localized
  // copy (parity with the other DB-touching handler groups). The status/policy/preflight/clipboard
  // and the pre-unlock diagnostics-log channels stay usable while locked BY DESIGN — they are
  // workspace-agnostic or read their value safely (`currentPolicyStatus` reads a locked workspace's
  // allowNetwork setting as off).
  const requireUnlocked = (): void => {
    // AUD-02: `workspaceAdmitsWork`, never a bare `isUnlocked()` — the workspace DB stays
    // OPEN for the whole multi-second lock teardown, so a bare check admits work that then
    // lazily respawns the sidecars that teardown just killed. This module's copy is unchanged.
    if (!workspaceAdmitsWork(ctx.workspace)) throw new Error(tMain('main.settings.locked'))
  }

  ipcHandle(IPC.getAppStatus, (): AppStatus => {
    const ws = ctx.workspace.getState()
    const unlocked = ctx.workspace.isUnlocked()
    const s = unlocked ? getSettings(ctx.db) : null
    // Effective offline state = policy ceiling ∧ the user's allowNetwork setting.
    const policy = buildPolicyStatus(
      ctx.paths.configPath,
      s?.allowNetwork ?? false,
      (m) => log.warn(m),
      { isDev: ctx.isDev }
    )
    return {
      appName: 'HilbertRaum',
      appVersion: app.getVersion(),
      offlineMode: policy.offlineMode,
      networkAllowed: policy.networkAllowed,
      activeModelId: s?.activeModelId ?? null,
      // Real, persisted profile from the hardware benchmark; UNKNOWN until first run.
      hardwareProfile: s?.lastBenchmark?.profile ?? 'UNKNOWN',
      workspaceMode: ws.mode ?? 'plaintext_dev',
      workspaceReady: unlocked,
      machineRamGb: machineRamGb(),
      // Dictation is availability-driven (transcriber selected at startup iff
      // whisper binary + weights exist) — the composer mic gates on this flag.
      dictationAvailable: ctx.transcriber != null,
      // #527: which piece is missing, so the hint names it. Stored with the slot, never
      // recomputed here — the shell polls this handler, and the reason needs a manifest walk.
      transcriberMissing: ctx.transcriber != null ? null : (ctx.transcriberMissing ?? 'model'),
      // #530: engines on the drive that the OS refused to start this session (the chat engine
      // first) — a session verdict held in memory, never persisted; empty while nothing failed.
      engineProblems: engineProblems(),
      // OCR is availability-driven too — gates "Make searchable (OCR)" + the photo hint. Reads
      // the engine's execution state, not mere presence (#232): false while a packaged build's
      // startup probe runs and after a worker failure. `ocrState` tells the renderer why.
      ocrAvailable: ctx.ocrEngine != null && ctx.ocrEngine.availability() === 'available',
      ocrState: ctx.ocrEngine == null ? 'missing' : ctx.ocrEngine.availability(),
      // Translation is availability-driven the same way (TG-3: the TranslateGemma
      // sidecar is selected at startup iff llama-server + the translation GGUF exist) —
      // gates the Documents "Translate" action. Reading the composed handle keeps this
      // flag in lockstep with the doc-task guard.
      translationAvailable: ctx.translator != null,
      // Issue #42 reopen: the sidecar's last cold-start device outcome (posture + parsed
      // offload split + liveness) — the Translate screen's #36-style hint. Null before the
      // first start / when unavailable; optional on the Translator seam (fakes omit it).
      translationDevice: ctx.translator?.deviceStatus?.() ?? null,
      // Local API live state (counts + flags only, never content — D1). Null when no
      // server object exists at all; the object itself reports `running: false` when the
      // feature is off, so the Settings card can distinguish "off" from "failed to bind".
      localApi: ctx.localApi?.status() ?? null
    }
  })

  ipcHandle(IPC.getDriveStatus, () => buildDriveStatus(ctx.paths))

  // The friendly, non-blocking launch preflight (spec §11.4). Reuses the drive
  // status + benchmark probe; surfaced on Home for a non-technical first run.
  ipcHandle(
    IPC.runPreflight,
    (): Promise<PreflightResult> => runPreflight({ rootPath: ctx.paths.rootPath })
  )

  // The user's allowNetwork setting lives inside the (possibly locked) DB; a locked workspace reads
  // as off, which keeps the offline ceiling intact until the unlock. The offline tripwire asks the
  // same reader at every remote connect (#758), so it records a connection opened while this says offline.
  ipcHandle(IPC.getPolicy, (): PolicyStatus => currentPolicyStatus(ctx, (m) => log.warn(m)))

  // The log tail and the clipboard write (Diagnostics' Copy), shared with the start-failure state (#1024).
  registerLogCopyHandlers(ipcHandle)

  // Save the WHOLE current log to a user-chosen file as plaintext (".txt"), so a user can
  // hand diagnostics to support without unsealing the workspace. The dialog + write run in
  // MAIN (saveTextExport). The on-disk log stays encrypted; this writes a copy the user
  // deliberately places outside the vault (spec §7.11 — logs are FOR THE USER).
  ipcHandle(IPC.exportLog, async (): Promise<string | null> => {
    const filePath = await saveTextExport(
      {
        title: tMain('main.dialog.exportLog'),
        defaultPath: 'hilbertraum-logs.txt',
        filters: [
          { name: 'Log', extensions: ['txt', 'log'] },
          { name: tMain('main.dialog.filterAll'), extensions: ['*'] }
        ]
      },
      readLogFull()
    )
    if (filePath) log.info('Diagnostic logs exported')
    return filePath
  })

  ipcHandle(IPC.getSettings, () => {
    requireUnlocked()
    return getSettings(ctx.db)
  })

  ipcHandle(IPC.updateSettings, (_e, raw: unknown) => {
    requireUnlocked()
    // BE-1 (full-audit 2026-07-10): shape-check the patch BEFORE touching it —
    // `Object.keys(null)` threw a raw TypeError out of the handler; reject junk with the
    // friendly localized copy instead (the sibling registrars' validation style).
    if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
      throw new Error(tMain('main.settings.invalidPatch'))
    }
    // #868 (after #858, which did this for `workspaceMode` alone): only the keys SETTINGS_WRITERS
    // gives the renderer pass, and every hook below reads this filtered patch.
    const patch = rendererWritablePatch(raw as Record<string, unknown>)
    log.info('Settings updated', Object.keys(patch))
    // Read BEFORE the write so local_api_toggled records only a REAL flip — key-presence
    // alone would log phantom enable/disable events for rejected-junk or same-value
    // patches, polluting the exported audit trail's forensic value.
    const localApiBefore = 'localApiEnabled' in patch ? getSettings(ctx.db).localApiEnabled : null
    // Step 4-4 (Wave 4 ruling (a)): same REAL-flip discipline for the reranker's posture. A real
    // `gpuMode` change suspends the sidecar (never the permanent stop()) as an EARLY release, so
    // its NEXT rerank() gets a head start on re-evaluating the posture rather than waiting for its
    // own use-time check to notice; that re-check (`reranker/llama.ts`'s `resolveServer`, Wave 8
    // ruling (b)(Q)) is what keeps the posture correct at every moment. Since #868 `gpuMode` is the
    // only posture key a renderer patch can carry (`RERANKER_POSTURE_SETTINGS_KEYS`): `gpuAutoDisabled`
    // and `activeModelId` are main-owned, and `models:select` / `runtime:use` make the
    // `activeModelId` call themselves (`registerModelIpc.ts`), through the same shared predicate
    // `rerankerPostureInputsChanged`, never a second copy of the condition.
    const postureBefore = RERANKER_POSTURE_SETTINGS_KEYS.some((k) => k in patch)
      ? (({ gpuMode, gpuAutoDisabled, activeModelId }) => ({ gpuMode, gpuAutoDisabled, activeModelId }))(
          getSettings(ctx.db)
        )
      : null
    // #782: the same REAL-flip discipline for internet access — a same-value save reports nothing.
    const networkBefore = 'allowNetwork' in patch ? getSettings(ctx.db).allowNetwork : null
    const result = updateSettings(ctx.db, patch)
    if (networkBefore !== null && networkBefore !== result.allowNetwork) networkSwitched(result.allowNetwork)
    if (postureBefore && rerankerPostureInputsChanged(postureBefore, result)) {
      void ctx.reranker?.suspend?.().catch((err: unknown) => {
        log.warn('Reranker sidecar suspend after a posture-affecting settings change failed', {
          error: err instanceof Error ? err.message : String(err)
        })
      })
    }
    // Keep the main-side cached UI language in step with the setting (D-L3) — the
    // post-validation value, so junk patches can't move it.
    if ('uiLanguage' in patch) applyUiLanguageSetting(result.uiLanguage)
    // The Performance snapshot reads a few settings keys this channel can carry (the context
    // size, its override, the GPU mode); a patch touching one pushes the screen's re-read.
    // Deliberately NOT every settings write — the screen has no interest in the UI language or
    // the theme.
    if (PERFORMANCE_SETTINGS_KEYS.some((k) => k in patch)) notifyPerformanceChanged()

    // Local API start/stop/re-port on a live settings change (the seam precedent above).
    // A bind failure is logged + lands in `status().lastError` (running:false) — the P4
    // card reads THAT surface; the settings write itself always succeeds. Fire-and-forget
    // is safe: the server serializes start/stop internally.
    if (LOCAL_API_SETTINGS_KEYS.some((k) => k in patch)) {
      void applyLocalApiSettings(ctx).catch((err) => {
        log.warn('Local API settings change failed to apply', { error: String(err) })
      })
    }
    // Audit privacy rule: record ONLY the privacy-relevant keys — and their
    // post-validation values, which are booleans/enums — never any other setting's value.
    // The tuple is a hard allowlist: the local-API token cannot ride here structurally
    // (it never enters AppSettings at all — services/local-api/token.ts), and the port
    // is deliberately excluded (booleans only; the audit-log export writes metadata
    // verbatim to plaintext JSON outside the vault).
    const privacyKeys = (
      ['allowNetwork', 'gpuMode', 'developerMode', 'localApiEnabled', 'localApiTokenRequired'] as const
    ).filter((k) => k in patch)
    if (privacyKeys.length > 0) {
      ctx.audit?.(
        'settings_changed',
        `Privacy-relevant settings changed: ${privacyKeys.join(', ')}`,
        Object.fromEntries(privacyKeys.map((k) => [k, result[k]]))
      )
    }
    // The local-API master switch gets its own first-class audit event (boolean only) —
    // deliberately IN ADDITION to the settings_changed sweep (the filterable trust event
    // the export/Activity surface keys on), but only when the accepted value actually
    // changed.
    if (localApiBefore !== null && result.localApiEnabled !== localApiBefore) {
      ctx.audit?.(
        'local_api_toggled',
        `Local API ${result.localApiEnabled ? 'enabled' : 'disabled'}`,
        { enabled: result.localApiEnabled }
      )
    }
    return result
  })
}