Skip to content

AI, fully local on your computer.

31.2 KB
Raw Blame
import type { IpcMainInvokeEvent } from 'electron'
import { STREAM, type AnswerSpeed, type CompactionNotice } from '../../shared/ipc'
import type { RuntimeTimings } from '../services/runtime'
import type { AppContext } from '../services/context'
import {
  DOC_TASK_BUSY_MESSAGE,
  type ContextUsage,
  type Conversation,
  type EndedEarly,
  type Message
} from '../../shared/types'
import {
  clearUnansweredMark,
  deleteLastAssistantMessage,
  emptyAssistantMessage,
  getConversation,
  getLatestMessage,
  getRegenerableAssistantMessageId,
  getUnansweredQuestion,
  isEmptyCompletionError,
  markUnansweredQuestion,
  restoreMessage
} from '../services/chat'
import { hasReviewForMessage } from '../services/evidence-reviews'
import type { Db } from '../services/db'
import type { ModelRuntime } from '../services/runtime'
import {
  isChatStreamError,
  isExceedContextError,
  isRuntimeConnectionLostError,
  isRuntimeUnresponsiveError
} from '../services/runtime/llama'
import { endedEarlyCause } from '../services/chat/ended-early'
import { noModelMessageKey } from '../../shared/runtime-status'
import { modelBusyMessageKey } from '../services/runtime/occupancy'
import { tMain } from '../services/i18n'
import { isEngineCannotRunError } from '../services/runtime/engine-load'
import { isEmbedderError, type EmbedderFailureKind } from '../services/embeddings/errors'
import type { MessageKey } from '../../shared/i18n'
import { log } from '../services/logging'
import { perfMark, perfMs } from '../services/perf'
import { inFlightStreams, streamBuffers, streamSettled } from './inflight'

// M-A2 (audit-2026-06-13): the plain-chat (`sendChatMessage`) and RAG (`askDocuments`)
// handlers duplicated the entire stream lifecycle verbatim — the guard preamble plus the
// AbortController / inFlight registration / token-send-with-`isDestroyed`-guard /
// done-error-finally dance. That is the most safety-sensitive path in the app, and two
// hand-kept copies invite drift. These helpers are the single owner.

/**
 * Shared guard preamble: the conversation must exist, a runtime must be active, no doc
 * task and no model-lane skill run may be working, and no stream may already be in flight
 * for this conversation. Throws the same friendly/ephemeral errors both handlers used.
 * Returns the looked-up conversation + the active runtime so the caller can proceed.
 */
export async function assertChatStreamReady(
  ctx: AppContext,
  conversationId: string
): Promise<{ conv: Conversation; runtime: ModelRuntime }> {
  const conv = getConversation(ctx.db, conversationId)
  if (!conv) throw new Error(`Unknown conversation: ${conversationId}`)

  const runtime = ctx.runtime.active()
  if (!runtime) {
    // Ephemeral IPC guard → tMain (i18n record §3.3); DOC_TASK_BUSY_MESSAGE stays
    // canonical English on the wire (renderer exact-match + display map). #599: while a start is
    // requested or loading, say so — "start one first" would send the user to start it twice.
    throw new Error(tMain(noModelMessageKey(ctx.runtime.isStarting?.() === true)))
  }
  // Strict one-at-a-time vs document tasks: the one local model serves either a chat
  // answer or a task, never both. A YIELDING deep-index build is the exception — it cedes
  // the slot (chat pauses it via the model-slot arbiter inside `withChatStream`, then it
  // resumes in-session). Any OTHER active task (summary/translate/compare/ocr, or a tree
  // build that is only queued, not yet holding the slot) still refuses chat (plan §4.1/H10).
  if (ctx.docTasks?.hasActiveTask() && !ctx.docTasks.isYieldingBuildActive()) {
    throw new Error(DOC_TASK_BUSY_MESSAGE)
  }
  // #186: the same one-at-a-time rule for a skill run whose tool streams on the chat runtime
  // directly (the `modelLane: 'direct'` redaction / document-edit locate passes). It is the
  // same shape of work as a doc task — user-started, cancellable, visible in the run bar — and
  // a `categorize_transactions` run has ALWAYS refused chat this way, because its model call
  // happens inside a doc task. Without this, that one skill run was excluded and its two
  // siblings were not. The benchmark is deliberately NOT in this check: it is short, and the
  // first-run benchmark fires right after unlock, where refusing the user's first message
  // would be a regression — it yields to chat instead (#185, `benchmark.ts` modelBusy).
  // Optional-chained: partial test contexts build a fake `runtime` object with only `active()`.
  if (ctx.runtime.occupancy?.held('skill-run')) {
    throw new Error(tMain(modelBusyMessageKey('skill-run')))
  }
  // One active stream per conversation (shared registry across plain chat + RAG).
  if (inFlightStreams.has(conversationId)) {
    throw new Error(tMain('main.chat.streamInFlight'))
  }
  return { conv, runtime }
}

/**
 * #613 "Send again" — the one owner of the resend precondition for both channels (`chat:send`'s
 * `resendMessageId`, `rag:ask`'s 6th argument). Returns null when the call is not a resend (no id, or
 * `regenerate` set: regenerate wins), else the stored question it answers. That question must still be
 * the conversation's last visible message and carry the clicked id: an answer that landed since, or a
 * stale screen, refuses with `main.chat.nothingToResend` before any stream or write, rather than answer
 * some other turn (the SKA-37 rule). The caller appends nothing — the question is already history.
 */
export function resendableQuestion(
  db: Db,
  conversationId: string,
  regenerate: boolean,
  resendMessageId: unknown
): Message | null {
  if (regenerate || typeof resendMessageId !== 'string' || resendMessageId.length === 0) return null
  const question = getUnansweredQuestion(db, conversationId)
  if (!question || question.id !== resendMessageId) throw new Error(tMain('main.chat.nothingToResend'))
  return question
}

/**
 * #634: the chat copy for a search-model failure, by kind. An interruption is a lock or quit, whose
 * own abort normally ends the turn first (no error at all); if one still lands here, the generic
 * line is the honest one.
 */
const SEARCH_MODEL_CHAT_KEY: Record<EmbedderFailureKind, MessageKey> = {
  timeout: 'main.chat.searchModelTimeout',
  start: 'main.chat.searchModelCannotStart',
  failed: 'main.chat.searchModelFailed',
  interrupted: 'main.chat.searchModelFailed'
}

/** A guarded token sender: a no-op once the renderer is gone (window closed mid-stream). */
export type SendToken = (token: string) => void
/** A guarded reasoning-delta sender (Deep mode); buffers like `SendToken`. */
export type SendReasoning = (delta: string) => void
/**
 * A guarded one-shot ephemeral notifier (context-compaction plan §5.2). Fired from the compaction
 * pre-pass's `onStart` (default `'compaction'` → "summarizing earlier messages…"), and reused by U5
 * for `'analysis'` → an exhaustive skill handler starting a long extraction ("reading the document…").
 * Unlike the token/reasoning senders it is EPHEMERAL (R14): never buffered into `streamBuffers`, so a
 * screen that remounts mid-stream simply misses the transient hint — acceptable, the answer still streams.
 */
export type SendCompaction = (kind?: CompactionNotice['kind']) => void
/**
 * A guarded one-shot sender for the REAL assembled-prompt context usage of the in-flight turn
 * (meter honesty): fired right after prompt assembly so the composer meter reflects what the
 * model actually received — including a document turn's injected excerpt/whole-document block,
 * which the renderer-side word estimate cannot see. EPHEMERAL like `SendCompaction` (R14):
 * never buffered; a remount misses it and the meter falls back to the resting estimate.
 */
export type SendUsage = (usage: ContextUsage) => void
/**
 * #290: a one-shot sink for the runtime's per-request `timings` of a COMPLETED answer. The
 * stream lifecycle turns them into ONE ephemeral `chat:speed:<id>` payload (tokens/sec, the
 * user-felt time to first token measured on its own clock, the token count) keyed to the
 * persisted message id, fired right before `done`. EPHEMERAL like `SendUsage` (R14): never
 * buffered, nothing persisted. Only the plain-chat channel wires it; a runFn that never calls it
 * (document answers, the mock runtime, an aborted answer) emits no speed payload at all.
 */
export type SendTimings = (timings: RuntimeTimings) => void

/** The generation body run under the locked streaming contract — handed the turn's abort signal
 *  and the guarded senders, resolving with the persisted assistant Message. */
export type ChatStreamRunFn = (
  signal: AbortSignal,
  sendToken: SendToken,
  sendReasoning: SendReasoning,
  sendCompaction: SendCompaction,
  sendUsage: SendUsage,
  sendTimings: SendTimings
) => Promise<Message>

/**
 * F2 (post-merge audit) — make a regenerate turn's destructive delete safe. The previous
 * assistant reply must NOT be dropped until the stream slot is held: the old ordering committed
 * the delete (node:sqlite is synchronous) before `withChatStream` claimed the slot, so a
 * non-abort failure between the delete and the first persisted token — `acquireSlot` rejecting,
 * a sidecar that died mid-session, or (most reachably) an `exceed_context_size_error` HTTP 400
 * because regenerate replays the full history near the window — destroyed the prior answer with
 * nothing in its place.
 *
 * This wraps a `runFn` so the delete runs INSIDE the stream (slot held, controller registered)
 * and the snapshot is RESTORED when generation throws with nothing saved in its place (before
 * #600: a non-abort throw only). A user Stop that resolves keeps the delete: the new partial/empty
 * reply stands, exactly as before. When `regenerate` is false only the #600 "Not answered" rule
 * below applies. The caller is
 * expected to have already bailed (read-only `hasRegenerableAssistantReply`) when there is no
 * prior reply; the snapshot being null here is a benign race (nothing deleted, nothing to
 * restore).
 *
 * AUD-01 — it also REFUSES outright when the reply about to be dropped carries an evidence
 * review (see the guard body). This is the choke point every regenerate passes through — plain
 * chat and the document channel alike — and `regenerate` is caller-supplied over IPC, so the
 * refusal belongs here rather than in either handler.
 *
 * #600 / #612 — the same choke point carries the ended-early rules, for EVERY turn, re-ask or not.
 * The cause is the turn's abort reason (`endedEarlyCause`): 'model' (the user stopped or switched the
 * chat model), 'user' (the Stop button) or 'lock' (lock or quit):
 *  - a re-ask that a model stop, lock or quit cut keeps the previous COMPLETE answer: the partial is
 *    removed and the snapshot restored. Those ended the stream, not the wish for an answer; the Stop
 *    button keeps its partial, as before, because that was the user's own choice about the answer;
 *  - a re-ask that THROWS restores its snapshot whenever nothing was saved in its place, abort or
 *    not. An abort thrown before anything streamed (document search, the reranker, a knowledge-pack
 *    arm, the categorizer) used to skip the restore and lose the previous answer, the Stop button
 *    included (reachable through "Answer without it" / "Run with <skill>" in a document chat). #779:
 *    after restoring, an abort RESOLVES with the restored answer, like CB-2's Stop before the first
 *    token, so `chat:done` carries the answer the transcript shows; any other failure rethrows (F2);
 *  - a turn that ended early with no answer at all marks its question "Not answered", with its cause
 *    (`markUnansweredQuestion`, which touches the last row only when it IS the question).
 *    A Stop during the pre-generation slot handoff (REL-3) ends before this wrapper runs and is not
 *    marked;
 *  - #613: the "Not answered" cause always describes the LATEST attempt on the question. Every attempt
 *    clears the tail question's mark once it starts (slot held) and sets it again if it too ends early,
 *    so an error leaves it unmarked like any failed turn. Today only a resend ("Send again") starts on a
 *    marked tail — a plain send's fresh question carries no mark and a regenerate's tail is an answer —
 *    but any future path that re-answers a trailing question is a new attempt and gets the same rule.
 */
export function withRegenerateGuard(
  db: Db,
  conversationId: string,
  regenerate: boolean,
  runFn: ChatStreamRunFn
): ChatStreamRunFn {
  const guarded = regenerate ? regenerateGuarded(db, conversationId, runFn) : runFn
  return markUnansweredOnEarlyEnd(db, conversationId, guarded)
}

/**
 * #612 — a re-ask cut by one of these causes restores the previous complete answer (see the guard
 * above): the user acted on the model or the workspace, not on the answer. The Stop button ('user')
 * is absent on purpose: there the half-written answer is the one the user chose to keep.
 */
const RESTORES_PREVIOUS_ANSWER: ReadonlySet<EndedEarly> = new Set<EndedEarly>(['model', 'lock'])

/** #600/#612 — mark the question when the turn ended early with no answer (see the guard above). */
function markUnansweredOnEarlyEnd(db: Db, conversationId: string, runFn: ChatStreamRunFn): ChatStreamRunFn {
  const mark = (signal: AbortSignal): void => {
    const cause = endedEarlyCause(signal)
    if (!cause) return
    try {
      markUnansweredQuestion(db, conversationId, cause)
    } catch {
      /* a marker is a courtesy; it must never fail the turn */
    }
  }
  return async (signal, sendToken, sendReasoning, sendCompaction, sendUsage, sendTimings) => {
    // #613: the mark describes the latest attempt (see the guard above). The slot is held, so this
    // attempt has really started; a refusal before this point (no model, busy, a Stop during the slot
    // handoff) keeps the old cause. `mark` below sets it again if this attempt ends early too.
    try {
      clearUnansweredMark(db, conversationId)
    } catch {
      /* a marker is a courtesy; it must never fail the turn */
    }
    try {
      const result = await runFn(signal, sendToken, sendReasoning, sendCompaction, sendUsage, sendTimings)
      if (result.content === '') mark(signal)
      return result
    } catch (err) {
      mark(signal)
      throw err
    }
  }
}

/** The regenerate leg of `withRegenerateGuard`: AUD-01 refusal, in-stream delete, restore rules. */
function regenerateGuarded(db: Db, conversationId: string, runFn: ChatStreamRunFn): ChatStreamRunFn {
  return async (signal, sendToken, sendReasoning, sendCompaction, sendUsage, sendTimings) => {
    // AUD-01 (data loss): `evidence_reviews.message_id` is a foreign key with ON DELETE CASCADE
    // and the workspace runs with `PRAGMA foreign_keys = ON`, so the `DELETE FROM messages` below
    // does not just drop an answer — it takes the reply's ENTIRE review chain with it: the review
    // head (title, Ready status, reviewer label, general note, freshness acknowledgement), every
    // per-block decision and reviewer note, every evidence link, and the whole export history.
    // The `DeletedMessage` snapshot the restore legs replay covers the `messages` row and the
    // answer's `result_tables` rows — NOT the review chain — so even the F2 (non-abort failure)
    // and CB-2 (Stop before the first token) paths — the ones designed to lose nothing — would
    // bring the answer back WITHOUT the human's work, permanently.
    // Deleting a whole CONVERSATION counts its reviews and warns first; a message-level replace
    // deserves at least as much care, and there is no per-turn confirm surface here, so refuse.
    // Resolving the target id up front means we inspect the exact row the delete would destroy.
    const targetId = getRegenerableAssistantMessageId(db, conversationId)
    if (targetId != null && hasReviewForMessage(db, targetId)) {
      throw new Error(tMain('main.chat.reviewBlocksRegenerate'))
    }
    const deleted = deleteLastAssistantMessage(db, conversationId)
    try {
      const result = await runFn(signal, sendToken, sendReasoning, sendCompaction, sendUsage, sendTimings)
      // CB-2: a Stop BEFORE the first token RESOLVES (it does not throw) with an unpersisted empty
      // message (`content === ''`, the sole empty-return path of `generateAssistantMessage`). Without
      // this the destructive regenerate delete would stand with NOTHING in its place — two clicks
      // (Regenerate, Stop) silently erase the answer. Restore the prior reply byte-faithfully (the
      // snapshot re-inserts the original id/created_at → no duplicate) and return it so `chat:done`
      // carries the answer to re-show. A real partial (`content !== ''`) keeps the delete, unchanged.
      // (A completed-but-empty stream now THROWS via CB-4 → handled in the catch below; composes.)
      if (deleted && result.content === '') {
        restoreMessage(db, deleted)
        return getLatestMessage(db, conversationId) ?? result
      }
      // #600/#612: a model stop, lock or quit cut the re-ask — the previous complete answer comes
      // back, the partial goes. Keyed on the saved answer's own "Reply stopped" marker, not the signal:
      // a stop that lands after a COMPLETE answer was saved (a post-answer step still awaiting) must
      // not throw that answer away. The partial is already saved, so it is removed first, or two would
      // remain — in one transaction, so a failed restore rolls back to the saved partial, never to
      // neither. A lock runs this while the teardown awaits the turn's settle, so the DB is still open.
      if (deleted && result.endedEarly != null && RESTORES_PREVIOUS_ANSWER.has(result.endedEarly)) {
        db.exec('BEGIN')
        try {
          if (getRegenerableAssistantMessageId(db, conversationId) === result.id) {
            deleteLastAssistantMessage(db, conversationId)
          }
          restoreMessage(db, deleted)
          db.exec('COMMIT')
        } catch (err) {
          try {
            db.exec('ROLLBACK')
          } catch {
            /* keep the partial either way */
          }
          log.warn('chat: kept the stopped re-ask — restoring the previous answer failed', {
            conversationId,
            error: String(err)
          })
          return result
        }
        return getLatestMessage(db, conversationId) ?? result
      }
      return result
    } catch (err) {
      // Restore whenever the re-ask threw with nothing saved in its place (#600: aborts included).
      // Every path that saves a partial resolves instead of throwing; the tail check keeps a saved
      // answer from ever sitting next to a restored one should that change.
      if (deleted && getRegenerableAssistantMessageId(db, conversationId) == null) {
        restoreMessage(db, deleted)
        // #779: an abort (a Stop, a model stop, lock or quit while documents were still being searched)
        // is a cancellation, not a failure. Resolve with the restored answer, as CB-2 does above, so
        // `chat:done` carries the answer the transcript shows rather than an empty one. A non-abort
        // failure still rethrows (F2): `withChatStream` sends `chat:error` and the invoke rejects.
        const restored = signal.aborted ? getLatestMessage(db, conversationId) : null
        if (restored) return restored
      }
      throw err
    }
  }
}

/**
 * The single answer-speed observer (the Performance screen's session latch, registered in
 * index.ts — read-speed.ts's observer idiom). Called with every `chat:speed` payload the
 * stream emits; last registration wins; a throwing observer never fails an answer.
 */
let answerSpeedObserver: ((speed: AnswerSpeed) => void) | null = null

export function setAnswerSpeedObserver(cb: ((speed: AnswerSpeed) => void) | null): void {
  answerSpeedObserver = cb
}

/**
 * #290: build the per-answer speed payload, or null when any input is unusable. Pure and
 * exported for the IPC test. Requires a persisted non-empty reply, a first token on the stream
 * clock, and finite positive `predicted_per_second` + `predicted_n` from the runtime — a
 * runtime without timings (the mock), an aborted answer (no timings) or an empty reply yields
 * null, so the line is absent rather than wrong.
 */
export function answerSpeedFrom(
  assistant: Message,
  timings: RuntimeTimings | null,
  ttftMs: number | null
): AnswerSpeed | null {
  if (!timings || ttftMs == null || assistant.content === '' || !assistant.id) return null
  const tps = timings.predicted_per_second
  const tokens = timings.predicted_n
  if (typeof tps !== 'number' || !Number.isFinite(tps) || tps <= 0) return null
  if (typeof tokens !== 'number' || !Number.isFinite(tokens) || tokens <= 0) return null
  return { messageId: assistant.id, tokensPerSecond: tps, ttftMs, tokens: Math.round(tokens) }
}

/**
 * Run a streaming generation under the LOCKED streaming contract: register an
 * AbortController in the shared in-flight registry, run `runFn` (handed the abort signal,
 * a guarded token sender, and a guarded reasoning sender), emit `chat:done:<id>` with the
 * final Message on success or `chat:error:<id>` (+ log under `logLabel`) on failure, and
 * always clear our own registry entry. Returns the final assistant Message so the invoke
 * can resolve with it.
 *
 * Both senders also append to the shared `streamBuffers` snapshot, so a Chat screen that
 * unmounted mid-stream (navigated away) can recover the in-progress reply on remount via
 * the `getActiveStream` IPC instead of seeing an idle screen that still rejects new turns.
 */
export async function withChatStream(
  event: IpcMainInvokeEvent,
  conversationId: string,
  logLabel: string,
  runFn: ChatStreamRunFn,
  /**
   * Optional model-slot claim (plan §4.1/H10): when a yielding deep-index build holds the
   * one chat runtime, this requests a pause and resolves once the builder parks (≈ one
   * node), returning a release fn that resumes the build. Called AFTER the in-flight entry
   * is registered and ALWAYS released in `finally`, so a build can never be left paused by
   * a failed/aborted chat turn. With no build active it resolves to a no-op immediately.
   * Receives the turn's abort `signal` (REL-3) so a "Stop" while parked unwinds at once.
   */
  acquireSlot?: (signal: AbortSignal) => Promise<() => void>
): Promise<Message> {
  const controller = new AbortController()
  inFlightStreams.set(conversationId, controller)
  streamBuffers.set(conversationId, { content: '', reasoning: '' })
  // R1: publish a "settled" promise the lock/quit teardown can await so a partial reply
  // persists BEFORE the DB closes. Resolved (never rejected) in the `finally` below, AFTER
  // `runFn` (and thus its abort-driven `appendMessage`) has fully unwound.
  let markSettled: () => void = () => {}
  streamSettled.set(
    conversationId,
    new Promise<void>((resolve) => {
      markSettled = resolve
    })
  )
  let releaseSlot: () => void = () => {}
  // Perf marks: TTFT is measured from stream registration (includes retrieval, context
  // fitting, and any compaction pre-pass inside runFn — the user-felt wait). A streamed
  // chunk approximates a token for llama-server; the mock streams words.
  const streamT0 = performance.now()
  let chunkCount = 0
  // #290: the user-felt time to first token, on the SAME clock as the `first_token` perf mark.
  let ttftMs: number | null = null
  const sendToken: SendToken = (token) => {
    if (chunkCount === 0) {
      ttftMs = perfMs(streamT0)
      perfMark('first_token', { ttftMs })
    }
    chunkCount += 1
    const buf = streamBuffers.get(conversationId)
    if (buf) buf.content += token
    if (!event.sender.isDestroyed()) {
      event.sender.send(STREAM.token(conversationId), token)
    }
  }
  const sendReasoning: SendReasoning = (delta) => {
    const buf = streamBuffers.get(conversationId)
    if (buf) buf.reasoning += delta
    if (!event.sender.isDestroyed()) {
      event.sender.send(STREAM.reasoning(conversationId), delta)
    }
  }
  // One-shot, EPHEMERAL (R14): no `streamBuffers` write, isDestroyed-guarded like the senders. A bare
  // call keeps the original `{ phase: 'start' }` payload byte-for-byte (compaction); an explicit
  // `'analysis'` kind rides the same channel for the U5 exhaustive-handler notice.
  const sendCompaction: SendCompaction = (kind) => {
    if (!event.sender.isDestroyed()) {
      const notice: CompactionNotice = kind ? { phase: 'start', kind } : { phase: 'start' }
      event.sender.send(STREAM.compaction(conversationId), notice)
    }
  }
  // The real assembled-prompt usage for the meter (fired once, post-assembly). EPHEMERAL (R14):
  // no `streamBuffers` write, isDestroyed-guarded — a remounted screen simply falls back to the
  // resting estimate until the turn settles.
  const sendUsage: SendUsage = (usage) => {
    if (!event.sender.isDestroyed()) {
      event.sender.send(STREAM.usage(conversationId), usage)
    }
  }
  // #290: the runtime's timings for a COMPLETED answer are parked here and turned into the one
  // `chat:speed` payload once the persisted message id is known (after runFn resolves). The
  // message id has to come from the persisted row, which is why this is not sent immediately.
  let pendingTimings: RuntimeTimings | null = null
  const sendTimings: SendTimings = (timings) => {
    pendingTimings = timings
  }
  try {
    // Hand the model slot off from a yielding build before any model call (no-op when none).
    // The abort signal is threaded in (REL-3) so a Stop while parked waiting for the build's
    // handoff rejects this acquire instead of blocking for up to one tree-node summarization.
    if (acquireSlot) releaseSlot = await acquireSlot(controller.signal)
    const assistant = await runFn(controller.signal, sendToken, sendReasoning, sendCompaction, sendUsage, sendTimings)
    perfMark('stream_done', {
      chunks: chunkCount,
      chars: streamBuffers.get(conversationId)?.content.length ?? 0,
      elapsedMs: perfMs(streamT0)
    })
    // #290: ONE ephemeral speed payload per finished answer, before `done`. Requires a persisted
    // (non-empty) reply, a first token on this clock, and usable server figures — anything less
    // (an abort carries no timings; a stripped-to-empty reply persists nothing) emits nothing,
    // never a wrong speed. Not buffered (R14): a remount or reload shows no line.
    const speed = answerSpeedFrom(assistant, pendingTimings, ttftMs)
    if (speed) {
      try {
        answerSpeedObserver?.(speed)
      } catch {
        /* an observer is a courtesy to the Performance screen, never the answer's problem */
      }
    }
    if (speed && !event.sender.isDestroyed()) {
      event.sender.send(STREAM.speed(conversationId), speed)
    }
    if (!event.sender.isDestroyed()) {
      event.sender.send(STREAM.done(conversationId), assistant)
    }
    return assistant
  } catch (err) {
    // REL-3: an abort (a Stop, a model stop or switch, lock or quit — the reasons in
    // chat/ended-early.ts) that lands BEFORE generation began. That is a clean cancellation, not a
    // failure: resolve exactly like an in-generation Stop that produced no token — emit `done` with
    // an empty message, never `chat:error` (the renderer surfaces a toast on any invoke rejection).
    // An in-generation abort never reaches here (generation swallows it and returns the partial).
    // Two pre-generation paths do: the slot park (the acquire rejects), and an abort thrown by a
    // step inside `runFn` before anything streamed (document search, the reranker, a knowledge-pack
    // arm, the categorizer). On a re-ask the second one no longer arrives here: `withRegenerateGuard`
    // restores the previous answer and resolves with it (#779), so `done` carries that answer. The
    // remaining twin is a Stop while a re-ask is still parked waiting for the chat slot behind a
    // deep-index build: the acquire rejects BEFORE the guard runs, so nothing was deleted and the
    // previous answer stands untouched, while this `done` carries an empty message. Kept as is: the
    // renderer re-lists the conversation after the invoke resolves and reads no `done` payload (it
    // never subscribes to `onDone`).
    if (controller.signal.aborted) {
      const assistant = emptyAssistantMessage(conversationId)
      if (!event.sender.isDestroyed()) {
        event.sender.send(STREAM.done(conversationId), assistant)
      }
      return assistant
    }
    const raw = err instanceof Error ? err.message : String(err)
    // Friendly-mapping chain (CB-4/CB-5/F-02), most-specific first: a HUNG sidecar
    // (runtimeUnresponsive) → a sidecar that DIED under the turn (connectionLost, #600) → a genuine
    // EMPTY completion (emptyCompletion) → a mid-stream
    // IN-BAND error frame (streamError, audit 2026-07-16 F-02) → a prompt-OVERFLOW HTTP 400
    // (contextExceeded) → an engine the OS refuses (#530) → a search-model failure by kind (#634)
    // → else the raw reason. Each mapped case shows actionable, CONTENT-FREE
    // copy to the user (the raw structural reason still goes to the local log only).
    const unresponsive = isRuntimeUnresponsiveError(err)
    // #600: the sidecar died under the turn (a crash, an OS kill) — never the raw "terminated".
    const connectionLost = isRuntimeConnectionLostError(err)
    const emptyCompletion = isEmptyCompletionError(err)
    const streamError = isChatStreamError(err)
    const overflow = isExceedContextError(err)
    // #530: a document question needs the embedder, and the OS refused to start the engine.
    const engine = isEngineCannotRunError(err)
    // #634: a document question's search step failed — the search model, not the AI model.
    const searchModel = isEmbedderError(err) ? SEARCH_MODEL_CHAT_KEY[err.kind] : null
    const message = unresponsive
      ? tMain('main.chat.runtimeUnresponsive')
      : connectionLost
        ? tMain('main.chat.connectionLost')
        : emptyCompletion
        ? tMain('main.chat.emptyCompletion')
        : streamError
          ? tMain('main.chat.streamError')
          : overflow
            ? tMain('main.model.contextExceeded')
            : engine
              ? tMain('main.engine.cannotRun')
              : searchModel
                ? tMain(searchModel)
                : raw
    log.error(logLabel, { conversationId, message: raw })
    if (!event.sender.isDestroyed()) {
      event.sender.send(STREAM.error(conversationId), message)
    }
    // Reject the invoke with the SAME friendly text the stream channel carries: the
    // renderer surfaces the invoke REJECTION (not the chat:error event), so a raw rethrow
    // here is what leaked the unmapped "ChatRequestError: HTTP 400 …" string to users. For
    // any other failure (incl. aborts) rethrow the original error untouched so its type and
    // message are preserved upstream.
    throw unresponsive || connectionLost || emptyCompletion || streamError || overflow || engine || searchModel
      ? new Error(message)
      : err
  } finally {
    // Resume any paused deep-index build first (idempotent; no-op when none was paused).
    releaseSlot()
    // Only clear our own entry — a later stream may already own this key. The buffer is
    // cleared in lockstep so `getActiveStream` reports "done" the instant the stream ends.
    if (inFlightStreams.get(conversationId) === controller) {
      inFlightStreams.delete(conversationId)
      streamBuffers.delete(conversationId)
      streamSettled.delete(conversationId)
    }
    // R1: signal this stream has fully unwound (its partial — if any — is persisted). A
    // lock/quit teardown awaiting the settled promise can now safely close the DB. Resolve
    // unconditionally and last, after the entry is cleared.
    markSettled()
  }
}