Skip to content

AI, fully local on your computer.

8.8 KB
Raw Blame
import { randomUUID } from 'node:crypto'
import { writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { guardedHandleFor } from './guarded-handle'
import { IPC } from '../../shared/ipc'
import type { AppContext } from '../services/context'
import { documentsDir } from '../services/ingestion'
import { shredFile, workspaceAdmitsWork } from '../services/workspace-vault'
import { t } from '../../shared/i18n'
import { tMain } from '../services/i18n'
import { isEngineCannotRunError, isEngineFilesUnreadableError } from '../services/runtime/engine-load'
import { isWhisperPathError } from '../services/transcriber/argv'
import { log } from '../services/logging'
import {
  describeDictationLevel,
  judgeDictationLevel,
  measureWavPcm16Level
} from '../../shared/dictation-level'

// Voice dictation IPC (wave-3 plan §10). The renderer records and resamples
// in-page and sends WAV BYTES (never a path); this handler writes them to a
// transient temp file — the whisper CLI takes file paths only — runs the
// transcriber, shreds the temp, and returns plain text for the composer to
// insert. Privacy posture:
//   • The temp WAV lives in the workspace documents dir under the `.parse` infix,
//     so the startup `shredStalePlaintext` crash sweep covers a crash mid-dictation
//     (the ingestion-temp pattern), and it is shredded in `finally`.
//   • Lock-gated (S3, full-audit-2026-06-30): because it lands a transient PLAINTEXT WAV in
//     the documents dir (which holds only `.enc` sidecars while locked), the handler refuses
//     on a locked vault — closing the F16 lock-guard parity gap (it dispatched on the
//     transcriber's presence only). No file is written when locked.
//   • No audit event — dictation is content-adjacent, like search.
//   • Errors back to the renderer are friendly copy; the technical reason goes to
//     the local log only (transcriber error tails are stderr-only — never
//     transcript content).

/** Friendly refusal when no transcriber is selected (binary or weights absent). The
 *  renderer shows the "not installed" mic in this state, so this is a defensive backstop. It
 *  names neither piece (#527): the engine can be the missing one, and the hint says which. */
export const DICTATION_UNAVAILABLE_MESSAGE = t('en', 'main.dictation.unavailable')

/** Friendly catch-all for a failed transcription (never the raw CLI error). The four refusal
 *  constants are the canonical English (tests compare against them); the handler throws the
 *  user's language via tMain (#530 — they were English-only literals before). */
export const DICTATION_FAILED_MESSAGE = t('en', 'main.dictation.failed')

/** Refusal for an implausibly large recording. 64 MB ≈ 35 min of 16 kHz mono PCM16 —
 *  far past any composer dictation; anything bigger belongs in a document import. */
export const DICTATION_MAX_BYTES = 64 * 1024 * 1024
export const DICTATION_TOO_LONG_MESSAGE = t('en', 'main.dictation.tooLong')

/** Refusal when a dictation is already transcribing (REL-3 concurrency guard). The
 *  renderer disables the mic while one is in flight; this is the defensive backstop that
 *  keeps rapid mic presses from spawning N concurrent whisper children. */
export const DICTATION_BUSY_MESSAGE = t('en', 'main.dictation.busy')

/**
 * Wall-clock ceiling for a single dictation (REL-3). The recording is already capped at
 * `DICTATION_MAX_BYTES` (~35 min of audio); transcription should never run much past that,
 * so a child still going at this point is wedged. On expiry the whisper child is killed via
 * the abort signal and the renderer gets the friendly failure copy instead of a hung mic
 * spinner. Override with `HILBERTRAUM_DICTATION_TIMEOUT_MS`.
 */
export const DEFAULT_DICTATION_TIMEOUT_MS = 10 * 60 * 1000

function resolveDictationTimeoutMs(): number {
  const env = Number(process.env.HILBERTRAUM_DICTATION_TIMEOUT_MS)
  return Number.isFinite(env) && env > 0 ? env : DEFAULT_DICTATION_TIMEOUT_MS
}

export function registerDictationIpc(ctx: AppContext): void {
  const ipcHandle = guardedHandleFor(ctx)
  const storeDir = documentsDir(ctx.paths.workspacePath)
  const maxDurationMs = resolveDictationTimeoutMs()
  // Single-flight guard: whisper is NOT internally serialized, so without this a second
  // mic press would spawn a concurrent child (REL-3). Reject the second invocation rather
  // than queue it — dictation is interactive, a stale queued result would surprise the user.
  let inFlight = false

  ipcHandle(IPC.transcribeDictation, async (_e, audio: unknown): Promise<string> => {
    // S3: refuse on a locked vault BEFORE any disk write — a transient plaintext WAV must
    // never land in the workspace documents dir while it holds only `.enc` sidecars. AUD-02:
    // `workspaceAdmitsWork`, not a bare `isUnlocked()` — the DB stays open for the whole
    // multi-second lock teardown, so a bare check would still let that WAV land mid-lock.
    if (!workspaceAdmitsWork(ctx.workspace)) throw new Error(tMain('main.dictation.locked'))
    const transcriber = ctx.transcriber
    if (!transcriber) throw new Error(tMain('main.dictation.unavailable'))
    // IPC delivers the renderer's Uint8Array as a Buffer (a Uint8Array subclass).
    if (!(audio instanceof Uint8Array) || audio.byteLength === 0) {
      throw new Error(tMain('main.dictation.failed'))
    }
    if (audio.byteLength > DICTATION_MAX_BYTES) throw new Error(tMain('main.dictation.tooLong'))
    // Refuse a concurrent dictation BEFORE touching disk or spawning (no double-spawn).
    if (inFlight) throw new Error(tMain('main.dictation.busy'))
    // #497: refuse a recording with no usable signal BEFORE the temp write and the whisper
    // spawn — the pinned whisper hallucinates a word ("you") on digital silence rather than
    // returning nothing. The renderer applies the same rule first (`assertUsableDictation`)
    // with the actionable copy; this is the backstop on the bytes (shared rule:
    // `shared/dictation-level.ts`). Numbers only in the log — never content. Bytes that are
    // not our PCM16 mono WAV get no verdict here; whisper's decode failure covers them.
    const level = measureWavPcm16Level(audio)
    const verdict = level ? judgeDictationLevel(level) : 'ok'
    if (level && verdict !== 'ok') {
      log.info('Dictation refused before transcription', { verdict, ...describeDictationLevel(level) })
      throw new Error(tMain(verdict === 'silent' ? 'main.dictation.silent' : 'main.dictation.tooShort'))
    }
    inFlight = true

    // Wall-clock bound: abort (→ kills the whisper child → transcribe rejects) so a wedged
    // child can never hang the mic spinner forever.
    const controller = new AbortController()
    const timer = setTimeout(() => controller.abort(), maxDurationMs)

    const tempPath = join(storeDir, `${randomUUID()}.parse-dictation.wav`)
    // #237: registered (under the timeout above) so a lock/quit aborts the whisper child too and
    // sweeps the WAV if the transcription outlives the settle bound.
    const op = ctx.plaintextOps?.register('dictation', controller.signal)
    op?.track(tempPath)
    try {
      // PERF-2: write the up-to-64 MiB WAV off the main thread (the handler is already async); the
      // existing try/finally still shreds tempPath on any failure, including a write rejection.
      await writeFile(tempPath, audio)
      const segments = await transcriber.transcribe(tempPath, {
        workDir: storeDir,
        signal: op?.signal ?? controller.signal,
        // #504: Silero VAD first — a dictation with speech in only part of the clip is decoded
        // where it speaks, and one with none (the noise band the level gate cannot judge)
        // comes back EMPTY → the composer's no-speech notice, never a stray word.
        vad: true
      })
      return segments
        .map((s) => s.text)
        .join(' ')
        .replace(/\s+/g, ' ')
        .trim()
    } catch (err) {
      // The reason is for the local log only (stderr tails, never content); the
      // renderer gets the friendly copy (timeout included — a wedged child is a failure).
      log.warn('Dictation transcription failed', { error: String(err) })
      // #869: a voice model whose path the voice engine cannot read here — moving it fixes that.
      if (isWhisperPathError(err)) throw new Error(tMain('main.dictation.voiceModelPathUnsupported'))
      // #530: the OS refused to start the voice engine — say so; a retry would not help.
      if (isEngineCannotRunError(err)) throw new Error(tMain('main.dictation.engineCannotRun'))
      // #1012 code review round 4: a file of the voice engine could not be read just now — try again in a minute.
      if (isEngineFilesUnreadableError(err)) throw new Error(tMain('main.engine.filesUnreadable'))
      throw new Error(tMain('main.dictation.failed'))
    } finally {
      clearTimeout(timer)
      shredFile(tempPath)
      op?.release()
      inFlight = false
    }
  })
}