AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { randomUUID } from 'node:crypto'
import { t, UI_LANGUAGES, type MessageKey } from '../../../shared/i18n'
import { tMain } from '../i18n'
import {
isTranslationLangCode,
type CoverageTier,
type DocTaskKind,
type DocTaskStatus,
type StartDocTaskRequest,
type TranslationSourceLang,
type TranslationTargetLang
} from '../../../shared/types'
import type { ChatMessage, ModelRuntime, RuntimeChatOptions } from '../runtime'
import { isExceedContextError } from '../runtime/llama'
import { modelBusyMessageKey } from '../runtime/occupancy'
import { noModelMessageKey } from '../../../shared/runtime-status'
import { ContextOverflowError } from './errors'
import { getDocument } from '../ingestion'
import { isPdfPath } from '../ingestion/parsers'
import { isAbortError, stripThinkBlocks } from '../chat'
import { ModelSlotArbiter } from '../analysis/model-slot-arbiter'
import { planSummaryWindows } from './summary'
import { log } from '../logging'
import type { DocTaskCtx, DocTaskDeps, InternalTask } from './context'
import { MODEL_TASK_HANDLERS, runCategorize, runOcr, runTranslation } from './handlers'
// `DocTaskDeps` lives in `./context` now (the per-kind handlers need it too); re-exported here so
// every existing `from '../services/doctasks'` importer is byte-for-byte unaffected.
export type { DocTaskDeps } from './context'
// The document-task manager (architecture.md "Document tasks"; wave-3 plan §6–§8, now in
// architecture.md "Functionality wave 3 — design record") — the shared engine for summary,
// translation, and compare: an async-with-polling job state machine. The window-math + prompt
// templates for each pipeline live in the sibling summary/translation/compare modules (audit
// M-A4); the per-kind WORK lives in the `handlers/` modules keyed by a registry (DX-1,
// full-audit-2026-06-29 follow-up Phase 8). THIS file is the orchestration: queue/pump, the
// model-slot arbiter handshake, the model loop (`generate`), and the dispatch wrapper that
// records success/failure/cancel. (Translation's window retry moved into its handler at TG-3 —
// it is sidecar-shaped, not `chatStream`-shaped.)
//
// Concurrency (strict one-at-a-time):
// - Tasks serialize among THEMSELVES: one FIFO queue, one running task.
// - A task REFUSES to start while a chat answer is streaming. The check reads the
// per-conversation in-flight registry, but tasks get their OWN AbortController and
// are NEVER entries in that map — `stopGeneration(conversationId)` must not be able
// to kill a document task, and a task must not block a conversation key.
// - The inverse guard lives in the chat/RAG IPC handlers: a chat message sent while a
// task is active gets DOC_TASK_BUSY_MESSAGE (with a renderer-side cancel option).
//
// Runtime use: tasks call the ACTIVE chat runtime via the same `chatStream` contract
// with EXPLICIT maxTokens/temperature — never the answer-depth modes. No runtime
// running → a friendly "start a model first" failure, never an auto-start surprise
// (same rule as sendChatMessage). TRANSLATION is the exception since TG-3 (plan D3/O2):
// it runs on the TranslateGemma sidecar (`deps.getTranslator()`), so the chat runtime is
// irrelevant to it — absent translator → a friendly "install the translation model"
// failure with the AI-Model deep link. The FIFO + chat↔task exclusion stay unchanged
// even so (D9: RAM co-residency — a 12B translate next to a resident chat model).
//
// Vault-lease note: a summary task only READS chunk rows and WRITES the
// `documents.summary_json` column of the open DB — it never touches the `.enc`
// document sidecars on disk. It therefore deliberately does NOT take the
// `beginDocumentWork()` lease (which exists to keep sidecar writers and the vault
// password change mutually exclusive). TRANSLATION and COMPARE tasks are the inverse:
// their materialize step writes a `.enc` sidecar through the normal import path, so
// that step — and ONLY that step — holds the lease. The long window-by-window model
// loop runs lease-free so a password change is never blocked for minutes; a change
// landing mid-loop just makes the final materialize fail friendly (VaultBusyError).
//
// Privacy: summaries, translations, and comparison reports are CONTENT. They are
// persisted only in the (possibly encrypted) workspace — `documents.summary_json` /
// the materialized `.enc` document — and the audit events carry ids and kinds only
// (`{ kind, documentId }`, plus `documentIdB` for a compare).
// Friendly copy (spec §11.4) for the guards + failure states. Task errors live ONLY in
// the in-memory polling status (never the DB — verified for the i18n boundary, plan §6
// fact-5 check), so the THROW sites localize via tMain() (i18n record §3.3 rule 2). The
// canonical-English constants stay exported for the exact-string tests (D-L8).
export const TASK_NEEDS_RUNTIME_MESSAGE = t('en', 'main.noModelRunning')
export const TASK_REFUSED_CHAT_STREAMING_MESSAGE = t('en', 'main.task.refusedChatStreaming')
export const TASK_COMPARE_PICK_TWO_MESSAGE = t('en', 'main.task.comparePickTwo')
export const TASK_COMPARE_REINDEX_MESSAGE = t('en', 'main.task.compareReindex')
export const TASK_DOCUMENT_NOT_READY_MESSAGE = t('en', 'main.task.documentNotReady')
export const TASK_GENERIC_FAILURE_MESSAGE = t('en', 'main.task.genericFailure')
export const TASK_EXPIRED_MESSAGE = t('en', 'main.task.expired')
export const TASK_TRANSLATION_TARGET_MESSAGE = t('en', 'main.task.translationTarget')
export const TASK_TRANSLATION_NO_MODEL_MESSAGE = t('en', 'main.translation.noModel')
export const TASK_SOURCE_UNREADABLE_MESSAGE = t('en', 'main.task.sourceUnreadable')
export const TASK_NEEDS_OCR_MESSAGE = t('en', 'main.task.needsOcr')
export const TASK_OCR_NOT_A_SCAN_MESSAGE = t('en', 'main.task.ocrNotAScan')
export const TASK_OCR_NO_TEXT_MESSAGE = t('en', 'main.task.ocrNoText')
export const TASK_DOCUMENT_BUSY_INGESTING_MESSAGE = t('en', 'main.task.documentBusyIngesting')
const TERMINAL: ReadonlySet<DocTaskStatus['state']> = new Set(['done', 'failed', 'cancelled'])
/**
* Cap on retained TERMINAL tasks in the `tasks` map (L11). Without a bound the map grew for
* the whole session (one entry per summary/translation/… ever run). Running and queued tasks
* are NEVER evicted; only completed ones past this many are dropped (oldest first). Mirrors the
* `TRANSLATE_MAX_JOB_HISTORY` bound the view-job store already applies.
*/
export const DOC_TASK_MAX_TERMINAL_HISTORY = 16
/**
* Cap on the retained jobId→kind recovery map (L11). Kept LARGER than the task cap so a
* poll landing after its task was evicted still gets the REAL kind (never a mislabelled
* `summary`), for at least this many recent jobs.
*/
const DOC_TASK_MAX_KIND_HISTORY = 64
export class DocTaskManager {
private readonly tasks = new Map<string, InternalTask>()
/**
* jobId → kind for every task issued this session (bounded, L11). Survives eviction of the
* task itself so `getDocTask` can echo the real kind of an evicted-but-recently-polled task
* instead of the old hardcoded `summary` fallback.
*/
private readonly kindHistory = new Map<string, DocTaskKind>()
private queue: string[] = []
private runningId: string | null = null
/**
* The in-flight `run(task)` dispatch promise (settles when the running task reaches a
* terminal state), or null while idle. `awaitActiveTaskSettled()` reads it so the
* lock/quit lifecycle can await the running task's abort-unwind before the DB closes.
*/
private runningPromise: Promise<void> | null = null
/**
* #936: a quit is under way, so `pump()` starts nothing (`holdQueueForQuit`). A quit the close guard holds while
* the main window saves (Ctrl+Q on Linux, ⌘Q or Dock Quit on macOS) closes the OCR window first, and the run ends
* before the quit's `will-quit` flushes the queue: without the hold the next task started into that gap and was
* cancelled a moment later.
*/
private quitHold = false
/**
* The single model-slot owner for a YIELDING tree build (plan §4.1, H9/H10). Only a
* running `tree` build registers with it; chat uses it to pause+hand-off, never to race.
*/
private readonly arbiter: ModelSlotArbiter
/** The narrow orchestration handle handed to each per-kind handler (DX-1). */
private readonly ctx: DocTaskCtx
constructor(private readonly deps: DocTaskDeps) {
// #399 D3(a): the resume delay is a 90 s wall-clock wait in production; `slotArbiterDeps`
// is the test-only fake-clock seam (see DocTaskDeps). Assigned here rather than as a field
// initializer because it reads `deps`.
this.arbiter = new ModelSlotArbiter(deps.slotArbiterDeps)
this.ctx = {
deps,
arbiter: this.arbiter,
generate: (runtime, systemPrompt, prompt, maxTokens, temperature, signal, schema) =>
this.generate(runtime, systemPrompt, prompt, maxTokens, temperature, signal, schema)
}
}
/**
* True while a YIELDING build (currently `tree`) is running and holds the model slot.
* The chat guard branches on this: a yielding build is PAUSED (chat acquires the slot
* via `acquireChatSlot`); any other active task makes chat refuse with DOC_TASK_BUSY.
*/
isYieldingBuildActive(): boolean {
return this.arbiter.isBuildActive()
}
/**
* Chat side: claim the model slot before streaming. If a yielding build holds it, this
* requests a pause and resolves once the builder parks (worst case ≈ one node); returns
* a release fn the caller MUST invoke when the stream ends (it resumes the build). With
* no build active it resolves immediately to a no-op. Idempotent release. REL-3: the chat
* turn's abort `signal` is threaded through so a "Stop" during the park unwinds at once.
*/
acquireChatSlot(signal?: AbortSignal): Promise<() => void> {
return this.arbiter.acquireForChat(signal)
}
/**
* Abort the running yielding build (workspace lock / app quit / cancel): abort its task
* controller AND reject the arbiter's parked `reacquire`, so a build parked awaiting a
* chat handoff unwinds to a resumable `tree_status='building'` instead of a hung await
* (plan §4.1 M9/H10). No-op when the running task is not a yielding build.
*/
abortActiveBuild(): void {
if (!this.runningId) return
const task = this.tasks.get(this.runningId)
if (!task || !isYieldingKind(task.status.kind)) return
log.info('Active deep-index build aborted', { jobId: task.status.jobId, kind: task.status.kind })
task.controller.abort()
this.arbiter.abort()
}
/**
* Auto-enqueue a deep-index (tree) build for a freshly-indexed document when it is worth
* it (plan Q1/Q4/§6). Gated and fire-and-forget — never throws into the import/reindex
* path: skips generated docs (M6), legacy not-`fully_chunked` docs (C4), already-built/
* building/pending trees, and documents the cheap capped summary already covers (size
* gate). With a chat runtime up it enqueues a `tree` task; otherwise it records
* `tree_status='pending'` for a later build. The "Build deep index" UI and coverage meter
* are in the renderer (rag-design.md §14.4).
*/
maybeEnqueueTreeBuild(documentId: string): void {
try {
const db = this.deps.getDb()
const doc = getDocument(db, documentId)
if (!doc || doc.status !== 'indexed' || doc.chunkCount === 0) return
if (doc.origin) return // generated work-products are excluded from the corpus (M6)
const row = db
.prepare('SELECT fully_chunked, tree_status FROM documents WHERE id = ?')
.get(documentId) as unknown as
| { fully_chunked: string | null; tree_status: string | null }
| undefined
if (!row?.fully_chunked) return // legacy/truncated — must re-index first (C4)
if (row.tree_status === 'ready' || row.tree_status === 'building' || row.tree_status === 'pending') {
return
}
// Size gate (Q4): only docs the capped one-pass summary cannot fully cover benefit
// from a deep index. `planSummaryWindows().truncated` is exactly "too big for the
// 12-window ceiling" — the silent-truncation case the tree fixes.
const texts = (
db
.prepare('SELECT text FROM chunks WHERE document_id = ? ORDER BY chunk_index')
.all(documentId) as unknown as Array<{ text: string }>
)
.map((r) => r.text)
.filter((t) => t.trim().length > 0)
if (!planSummaryWindows(texts, this.deps.getContextTokens()).truncated) return
if (!this.deps.getRuntime()) {
db.prepare('UPDATE documents SET tree_status = ?, updated_at = ? WHERE id = ?').run(
'pending',
new Date().toISOString(),
documentId
)
return
}
this.startDocTask({ kind: 'tree', documentIds: [documentId] })
} catch (err) {
// Auto-enqueue is best-effort: a refused start (chat streaming) or any error leaves
// the doc without a tree (the user can build it manually). Never breaks ingestion.
log.info('Deep-index auto-enqueue skipped', {
documentId,
reason: err instanceof Error ? err.message : String(err)
})
}
}
/**
* Validate + enqueue a task. Throws friendly errors for the guards (chat
* streaming, no runtime) and for invalid requests; a queued/running task is reported
* via `getDocTask` polling from then on.
*/
startDocTask(req: StartDocTaskRequest): { jobId: string } {
// AUD-02 — refuse while a workspace LOCK teardown is under way. This lives HERE, not only in
// the IPC handler, so every non-IPC caller inherits it (the guard posture of this manager).
// `getDb()` cannot express this: the lock closes the DB only at the very END of a
// multi-second awaited teardown, so a task admitted mid-teardown queues, pumps immediately,
// and lazily respawns the translation sidecar the teardown just suspended — the sidecar
// suspends are non-latching on purpose (they must come back after the next unlock). Same
// localized copy the doc-task IPC guard uses.
if (this.deps.isWorkspaceLocking()) {
throw new Error(tMain('main.task.workspaceLocked'))
}
const kind = req?.kind as DocTaskKind
if (
kind !== 'summary' &&
kind !== 'translation' &&
kind !== 'compare' &&
kind !== 'ocr' &&
kind !== 'tree' &&
kind !== 'extract' &&
kind !== 'categorize'
) {
throw new Error(tMain('main.task.unknownKind'))
}
// Translation languages are a closed set (`TRANSLATION_LANGUAGE_CODES`, shared/types —
// widened at issue #31 to the 51-code WMT24++ production tier recorded there).
// BOTH ends are validated: TranslateGemma's trained prompt requires an explicit
// source language (no auto-detect), and a same-language "translation" would be a
// multi-gigabyte no-op, so source ≠ target is enforced too.
let sourceLang: TranslationSourceLang | undefined
let targetLang: TranslationTargetLang | undefined
if (kind === 'translation') {
const src = req.params?.sourceLang
const tgt = req.params?.targetLang
if (!isTranslationLangCode(src) || !isTranslationLangCode(tgt) || src === tgt) {
throw new Error(tMain('main.task.translationTarget'))
}
sourceLang = src
targetLang = tgt
}
// Coverage tier for a summary (whole-document-analysis plan §4.5). Tolerant: any value
// other than 2 or 3 (incl. absent — the one-click summary) means Tier 1 (the default,
// 0 extra model calls when a tree is ready), so the existing call site is unchanged.
let summaryTier: CoverageTier | undefined
if (kind === 'summary') {
const raw = req.params?.tier
summaryTier = raw === 2 ? 2 : raw === 3 ? 3 : 1
}
if (this.deps.isChatStreaming()) {
throw new Error(tMain('main.task.refusedChatStreaming'))
}
// #185/#186: the other half of the same exclusion. `isChatStreaming` sees only the lanes
// that register in `inFlightStreams`, which a skill run's LLM locate pass and the hardware
// benchmark's speed probe never do — both reach `chatStream` directly, so a task admitted
// beside one of them would interleave two generations on the single llama-server slot.
const occupied = this.deps.occupiedLane?.() ?? null
if (occupied) {
throw new Error(tMain(modelBusyMessageKey(occupied)))
}
// OCR runs the local recognition engine, not the chat model — it needs the
// vendored language files instead of a running runtime. TRANSLATION (TG-3, plan D3/O2)
// runs the TranslateGemma sidecar — it needs the installed translation model, and the
// chat runtime is irrelevant to it. `categorize` (Phase 33) is the one
// model-OPTIONAL kind: with no runtime it degrades to the deterministic rule pass, so it must
// be allowed to start regardless — the runtime is read (possibly null) at run time.
if (kind === 'ocr') {
const engine = this.deps.getOcrEngine?.()
if (!engine) {
throw new Error(tMain('main.task.needsOcr'))
}
// Files present but the recognizer cannot run in this build (#232). The UI hides the offer
// on `ocrAvailable === false`; this guards a status read that predates the probe's verdict.
if (engine.availability() === 'unavailable') {
throw new Error(tMain('main.task.ocrUnavailable'))
}
} else if (kind === 'translation') {
if (!this.deps.getTranslator()) {
throw new Error(tMain('main.translation.noModel'))
}
} else if (kind !== 'categorize' && !this.deps.getRuntime()) {
throw new Error(tMain(this.noModelKey()))
}
// Compare runs over exactly TWO (distinct) documents; summary/translation/ocr over one.
const documentIds = (req.documentIds ?? []).filter((x) => typeof x === 'string' && x.length > 0)
const wanted = kind === 'compare' ? 2 : 1
if (documentIds.length !== wanted || new Set(documentIds).size !== wanted) {
throw new Error(
kind === 'compare'
? tMain('main.task.comparePickTwo')
: kind === 'translation'
? tMain('main.task.pickOneTranslate')
: kind === 'ocr'
? tMain('main.task.pickOneOcr')
: tMain('main.task.pickOneSummarize')
)
}
// BE-1 (ocr-audit 2026-07-18): the mirror of the docs IPC `requireNoActiveTask` guard —
// refuse EVERY kind while the ingestion layer (import loop / re-index) is mid-flight on a
// target document. Without this an OCR re-run admitted mid-re-index interleaves two chunk
// DELETE/INSERT transactions + two embed phases on one document (an already-OCR'd PDF
// keeps its `ocr` admission metadata through the whole re-index; every other kind is
// shielded only incidentally by `status === 'indexed'`). Optional predicate: absent ⇒
// never busy (partial test deps stay byte-green).
for (const id of documentIds) {
if (this.deps.isDocumentProcessing?.(id)) {
throw new Error(tMain('main.task.documentBusyIngesting'))
}
}
if (kind === 'ocr') {
// The target is a scan-DETECTED PDF (step 0 marked it), a text PDF with scanned pages
// (#575), or an already-OCR'd PDF being re-run (better assets / a bad first pass). Never an
// ordinary document.
const doc = getDocument(this.deps.getDb(), documentIds[0])
if (!doc || !isPdfPath(doc.title) || !(doc.scanDetected || doc.ocr || doc.scannedPages)) {
throw new Error(tMain('main.task.ocrNotAScan'))
}
} else {
for (const id of documentIds) {
const doc = getDocument(this.deps.getDb(), id)
if (!doc || doc.status !== 'indexed' || doc.chunkCount === 0) {
throw new Error(tMain('main.task.documentNotReady'))
}
// Deep-index precondition (C4): only a FULLY chunked document may be tree-built or
// extract-scanned, so "whole document"/"100% coverage" can never be claimed over a
// silently-truncated legacy chunk set. A legacy (NULL marker) doc must be re-indexed
// first (which sets it or fails over-cap). Same gate for the extract pass (Phase 3).
if (kind === 'tree' || kind === 'extract') {
const row = this.deps
.getDb()
.prepare('SELECT fully_chunked FROM documents WHERE id = ?')
.get(id) as unknown as { fully_chunked: string | null } | undefined
if (!row?.fully_chunked) throw new Error(tMain('main.task.documentNotReady'))
}
}
}
const jobId = randomUUID()
const task: InternalTask = {
status: {
jobId,
kind,
documentIds,
state: 'queued',
progress: { stepsDone: 0, stepsTotal: 0 },
error: null,
resultRef: null
},
controller: new AbortController(),
sourceLang,
targetLang,
summaryTier,
// #38: only an explicit tree start may chain the extract pass (the deep-index UI action);
// any other kind ignores the param.
withExtract: kind === 'tree' && req.params?.withExtract === true
}
this.tasks.set(jobId, task)
this.recordKind(jobId, kind)
this.queue.push(jobId)
log.info('Document task queued', { jobId, kind, documentId: documentIds[0] })
this.pump()
return { jobId }
}
/** Poll one task. Unknown/expired ids report a terminal state so pollers stop. */
getDocTask(jobId: string): DocTaskStatus {
const task = this.tasks.get(jobId)
if (task) {
// Return a copy — the renderer must not share mutable state with the engine.
return {
...task.status,
progress: { ...task.status.progress },
...(task.status.gaps
? {
gaps: {
...task.status.gaps,
missingPageRanges: task.status.gaps.missingPageRanges.map((r) => ({ ...r }))
}
}
: {})
}
}
// The task is gone — evicted past the terminal-history cap, or a never-issued id (L11).
// Echo its REAL kind if we still remember it (never mislabel an evicted translation as a
// summary); otherwise a neutral default. Pollers key off the terminal `state`, not `kind`.
return {
jobId,
kind: this.kindHistory.get(jobId) ?? 'summary',
documentIds: [],
state: 'failed',
progress: { stepsDone: 0, stepsTotal: 0 },
error: tMain('main.task.expired'),
resultRef: null
}
}
/**
* Cancel a task: a running one is aborted mid-stream, a queued one is dequeued.
* With no jobId, cancels the currently active (running, else next queued) task —
* the chat screen's "cancel the busy task" affordance.
*
* #157 (DT-2): an EXPLICIT jobId cancels that exact task, running OR QUEUED — this is now
* also the IPC's targeted-cancel routing. The former `cancelActiveDocTask` matched only
* `runningId ?? queue[0]`, so a Stop on a translation QUEUED BEHIND a foreign running task
* was a silent no-op and the "cancelled" job later ran to completion (hours of surprise
* compute + an unwanted document). Exact-id keeps the FA-3 / F-6 stale-Stop property for
* free: a settled task is TERMINAL (no-op below), and a newer task on the lane has a
* DIFFERENT id — a stale Stop can never touch it.
*
* #689: the one exception is a deep-index tree that finished and chained its extract pass
* (#38: one user concept). The Documents row cancels by the id it holds, which is still the
* tree's until its next poll adopts the extract, so the cancel passes on to that task.
*/
cancelDocTask(jobId?: string | null): void {
const id = jobId ?? this.runningId ?? this.queue[0] ?? null
if (!id) return
const task = this.tasks.get(id)
if (!task) return
if (TERMINAL.has(task.status.state)) {
if (task.chainedJobId) {
log.info('Document task cancel passed on to its chained task', { jobId: id, chainedJobId: task.chainedJobId })
this.cancelDocTask(task.chainedJobId)
}
return
}
log.info('Document task cancel requested', { jobId: id })
if (task.status.state === 'queued') {
this.queue = this.queue.filter((q) => q !== id)
task.status.state = 'cancelled'
return
}
task.controller.abort()
// A running yielding build (tree/extract) may be PARKED on the arbiter (yielded to chat);
// aborting its controller alone won't unstick that await, so reject the parked reacquire too.
if (isYieldingKind(task.status.kind)) this.arbiter.abort()
}
/**
* Flush the WHOLE pipeline — cancel the running task AND every queued task (TA-1 H2). The
* workspace-LOCK / quit paths call this instead of `cancelDocTask()`: cancelling only the
* ACTIVE task lets `pump()` dequeue the next queued task the moment the active one settles,
* and the DB is still OPEN while the lock/quit handler awaits the sidecar suspends — so a
* queued translation would dequeue INTO the lock window, decrypt document text to a `.parse`
* transient, and its retry could cold-start a fresh ~10 GB sidecar that outlives the lock.
* Flushing the queue closes that window. No permanent latch: `pump` is driven per
* `startDocTask`, so the manager is fully usable again after unlock.
*/
cancelAllDocTasks(): void {
// Snapshot the ids first — `cancelDocTask` mutates `this.queue` as it dequeues each one.
const ids = [...(this.runningId ? [this.runningId] : []), ...this.queue]
for (const id of ids) this.cancelDocTask(id)
}
/**
* Resolve when the CURRENTLY running task's dispatch settles (immediately if idle). The
* lock/quit paths await this — BOUNDED by the caller — after `cancelAllDocTasks()`, so the
* aborted task's abort-unwind (which materializes/shreds its transient synchronously) finishes
* while `ctx.db` is still open, before `lock()` re-encrypts. Mirrors the in-flight-stream
* settle await. `run()` never rejects (it records failure/cancel internally), so a plain await
* is safe; the `.catch` is belt-and-braces.
*/
async awaitActiveTaskSettled(): Promise<void> {
const p = this.runningPromise
if (!p) return
await p.catch(() => undefined)
}
/**
* #936: a quit has begun (the close guard committed to a close that quits, or an un-prevented `before-quit`):
* start nothing new until `releaseQueueHold()`. The running task goes on, and a task started meanwhile is queued,
* so it runs if the quit is called off. The quit's `will-quit` cancels everything anyway (`cancelAllDocTasks`).
*/
holdQueueForQuit(): void {
this.quitHold = true
}
/**
* #936: the quit was called off (Keep open): the queue goes on, starting its next task now if none is running. So
* the hold is never a permanent latch. Without a hold it changes nothing (an idle queue holds no waiting task).
*/
releaseQueueHold(): void {
this.quitHold = false
this.pump()
}
/** True while a task is running or queued — the chat-side busy guard reads this. */
hasActiveTask(): boolean {
return this.runningId !== null || this.queue.length > 0
}
/**
* The currently RUNNING task's status (a copy), or null when idle — the file/document
* translation RELOAD-adoption read (FA-3 / F-3), the doc-task mirror of the view job's
* `getActiveJob()`. A full renderer reload kills `fileTranslateSession`'s module store + its
* poll timers while the doc-task keeps running in main; this lets a freshly-mounted Translate
* screen re-attach to it. Only the RUNNING task is adoptable (a queued task has produced no
* progress yet, and the D9 one-at-a-time lane means at most one task exists anyway). The caller
* filters by `kind === 'translation'`.
*/
getActiveDocTask(): DocTaskStatus | null {
if (!this.runningId) return null
const task = this.tasks.get(this.runningId)
if (!task) return null
return { ...task.status, progress: { ...task.status.progress } }
}
/**
* Every non-terminal task on the lane — the running task first, then the queue in order
* (copies). #157 (DT-5): the reload-adoption read for the file/document translation path.
* `getActiveDocTask()` above returns only the RUNNING task — and a task becomes `running`
* synchronously in the same tick it becomes `runningId`, so `queued` could never be returned
* through it: a translation QUEUED behind a foreign task (a Documents-row Summarize took the
* lane during the import phase) was invisible to a remounting Translate screen — it ran later
* with no progress UI, no Stop, no result load, and the #150/DOC-8 "accept queued" branch was
* dead code. The caller filters by kind.
*/
listActiveDocTasks(): DocTaskStatus[] {
const ids = [...(this.runningId ? [this.runningId] : []), ...this.queue]
const out: DocTaskStatus[] = []
for (const id of ids) {
const task = this.tasks.get(id)
if (!task || TERMINAL.has(task.status.state)) continue
out.push({ ...task.status, progress: { ...task.status.progress } })
}
return out
}
/** True when an active (running/queued) task targets `documentId` — guards re-index/delete. */
isDocumentBusy(documentId: string): boolean {
const ids = [...(this.runningId ? [this.runningId] : []), ...this.queue]
return ids.some((id) => this.tasks.get(id)?.status.documentIds.includes(documentId) ?? false)
}
/** True when a running OR queued task of `kind` already targets `documentId` — the dedup guard the
* `extract` auto-offer uses so a re-run extract (or extract + a manual categorize) never enqueues a
* second `categorize` over the same statement (duplicate model work, overwriting the first's labels). */
hasPendingKind(documentId: string, kind: DocTaskKind): boolean {
const ids = [...(this.runningId ? [this.runningId] : []), ...this.queue]
return ids.some((id) => {
const t = this.tasks.get(id)
return t != null && t.status.kind === kind && t.status.documentIds.includes(documentId)
})
}
/** #599: the no-model refusal — "is starting" while a start is requested or loading. */
private noModelKey(): MessageKey {
return noModelMessageKey(this.deps.isModelStarting?.() === true)
}
/** Run the next queued task; tasks serialize among themselves. Nothing starts while a quit holds the queue (#936). */
private pump(): void {
if (this.runningId || this.quitHold) return
const next = this.queue.shift()
if (!next) return
const task = this.tasks.get(next)
if (!task || task.status.state !== 'queued') {
this.pump()
return
}
this.runningId = next
// #185/#186: hold the `doc-task` occupancy span for exactly the dispatch. Taken here — the
// single place a task starts running — and released in the SAME `finally` that clears
// `runningId`, so the span can never outlive the task it describes. A multi-step task is
// then continuously busy to the lanes that must not join it (skill runs, the benchmark, and
// external local-API admission) instead of flickering idle between its model calls.
const releaseOccupancy = this.deps.beginOccupancy?.() ?? ((): void => {})
// Track the dispatch promise so `awaitActiveTaskSettled()` (the lock/quit lifecycle) can
// wait for this task's abort-unwind before the DB closes. `run()` never rejects.
this.runningPromise = this.run(task).finally(() => {
releaseOccupancy()
this.runningId = null
this.runningPromise = null
this.evictTerminalTasks()
this.pump()
})
}
/** Record a task's kind in the bounded recovery map (L11), dropping the oldest past the cap. */
private recordKind(jobId: string, kind: DocTaskKind): void {
this.kindHistory.set(jobId, kind)
while (this.kindHistory.size > DOC_TASK_MAX_KIND_HISTORY) {
const oldest = this.kindHistory.keys().next().value
if (oldest === undefined) break
this.kindHistory.delete(oldest)
}
}
/**
* Bound the `tasks` map (L11): drop the oldest TERMINAL tasks past the history cap. The
* running task and every queued task are retained (they are still live); the dropped tasks'
* kinds survive in `kindHistory`, so a late poll still resolves the right kind. Called after
* each task settles.
*/
private evictTerminalTasks(): void {
if (this.tasks.size <= DOC_TASK_MAX_TERMINAL_HISTORY) return
for (const [id, task] of this.tasks) {
if (this.tasks.size <= DOC_TASK_MAX_TERMINAL_HISTORY) break
if (id === this.runningId) continue
if (!TERMINAL.has(task.status.state)) continue // queued tasks are still live
this.tasks.delete(id)
}
}
/**
* Dispatch one task to its per-kind handler (the registry), then record success/failure/
* cancel. The orchestration wrapper — state transitions, audit events, friendly-error
* mapping — lives here; the kind-specific work lives in `handlers/`.
*/
private async run(task: InternalTask): Promise<void> {
const { kind } = task.status
// The SOURCE document id(s) — the audit events carry these; a generated OUTPUT id
// travels in `resultRef` (and is appended to `documentIds` for the busy guard, so
// capture the sources BEFORE the task runs). A compare's second source rides as
// the additive ids-only `documentIdB`.
const documentId = task.status.documentIds[0]
const auditMeta: Record<string, unknown> = { kind, documentId }
if (kind === 'compare' && task.status.documentIds[1]) {
auditMeta.documentIdB = task.status.documentIds[1]
}
task.status.state = 'running'
try {
let resultId: string
if (kind === 'ocr') {
// OCR uses the recognition engine, not the chat runtime.
resultId = await runOcr(task, this.ctx)
} else if (kind === 'translation') {
// TG-3: translation runs on the TranslateGemma sidecar, not the chat runtime.
// Re-check at dequeue time — a quit may have stopped it while queued (a lock only
// SUSPENDS it; the next translate() lazily restarts the server).
const translator = this.deps.getTranslator()
if (!translator) throw new Error(tMain('main.translation.noModel'))
resultId = await runTranslation(task, translator, this.ctx)
} else if (kind === 'categorize') {
// The bank-statement LLM categorizer (Phase 33) — model-OPTIONAL: a null runtime degrades to
// the deterministic rule pass inside runCategorize (so it never fails for "no model").
resultId = await runCategorize(task, this.deps.getRuntime(), this.ctx)
} else {
// Re-check at dequeue time: the runtime may have been stopped while queued.
const runtime = this.deps.getRuntime()
if (!runtime) throw new Error(tMain(this.noModelKey()))
// Registry dispatch (DX-1): every runtime-requiring kind is a one-line entry in
// `MODEL_TASK_HANDLERS`, not another `else if` branch here.
resultId = await MODEL_TASK_HANDLERS[kind](task, runtime, this.ctx)
}
task.status.state = 'done'
task.status.resultRef = { documentId: resultId }
this.deps.audit?.('document_task_completed', `Document task completed: ${kind}`, auditMeta)
log.info('Document task completed', { jobId: task.status.jobId, kind, documentId })
// #38: "Build deep index" = tree + extract, one user concept. Chain the structured-extract
// pass ONLY after a SUCCESSFUL user-initiated tree build (never on cancel/failure — the
// catch below returns first, so a cancelled build never spawns surprise CPU work). Enqueued
// here (runningId still set), so the outer pump picks it up the moment this task settles.
// Best-effort like `maybeEnqueueTreeBuild`: a refused start (chat streaming, runtime gone,
// already pending) is logged and dropped — the deep-index row action stays visible until
// `extract_status='ready'`, so the user can finish the missing pass later.
if (task.withExtract && !this.hasPendingKind(documentId, 'extract')) {
try {
task.chainedJobId = this.startDocTask({ kind: 'extract', documentIds: [documentId] }).jobId
} catch (chainErr) {
log.info('Deep-index extract chain skipped', {
documentId,
reason: chainErr instanceof Error ? chainErr.message : String(chainErr)
})
}
}
} catch (err) {
if (isAbortError(err, task.controller.signal)) {
task.status.state = 'cancelled'
log.info('Document task cancelled', { jobId: task.status.jobId, kind, documentId })
return
}
const raw = err instanceof Error ? err.message : String(err)
// Friendly failures (§11.4): our own guard copy passes through (as does the
// vault lease's VaultBusyError — its message is written for users); anything
// else (runtime/HTTP/SQL errors) is replaced by the generic copy. The raw reason
// goes to the local log only — never to the renderer, never to the audit log.
const friendly =
isFriendlyTaskError(raw) || (err instanceof Error && err.name === 'VaultBusyError')
task.status.state = 'failed'
task.status.error = friendly ? raw : tMain('main.task.genericFailure')
this.deps.audit?.('document_task_failed', `Document task failed: ${kind}`, auditMeta)
log.error('Document task failed', { jobId: task.status.jobId, kind, documentId, error: raw })
}
}
/**
* One model call over the LOCKED `chatStream` contract: explicit
* maxTokens/temperature, NO depth mode, the task's own abort signal. Cancellation
* must never persist a half result — an abort throws instead of returning the
* partial text (chat keeps partials; tasks do not).
*/
private async generate(
runtime: ModelRuntime,
systemPrompt: string,
prompt: string,
maxTokens: number,
temperature: number,
signal: AbortSignal,
schema?: Pick<RuntimeChatOptions, 'responseSchema' | 'responseSchemaName'>
): Promise<string> {
const messages: ChatMessage[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: prompt }
]
let out = ''
const stream = runtime.chatStream(messages, {
signal,
maxTokens,
temperature,
// D55 grammar constraint (STR-1 §5.1) — only the extract pass sets this today; the
// spread keeps every schema-less caller's options object byte-identical.
...(schema ?? {})
})
try {
for await (const token of stream) {
out += token
}
} catch (err) {
// A document window that overflows the model context comes back as an HTTP 400.
// Surface the actionable "too large for this model" copy (a friendly task error)
// rather than the raw "Chat request failed: HTTP 400" the generic path would hide.
// Typed (issue #41) so the tree build can catch it and retry with a smaller
// packing budget instead of failing the whole task.
if (isExceedContextError(err)) throw new ContextOverflowError(tMain('main.model.contextExceeded'))
throw err
}
// The mock runtime returns cleanly on abort; the real one throws AbortError. Both
// must land in the `cancelled` state, so normalize the clean return into a throw.
if (signal.aborted) {
throw new DOMException('Document task cancelled', 'AbortError')
}
return stripThinkBlocks(out).trim()
}
}
/** The YIELDING build kinds (whole-document-analysis plan §4.1): they cede the model slot to
* chat via the arbiter and resume in-session, rather than refusing chat while active. */
function isYieldingKind(kind: DocTaskKind): boolean {
return kind === 'tree' || kind === 'extract'
}
/** Keys of the guard/validation copy that may pass through to the renderer on failure. */
const FRIENDLY_TASK_ERROR_KEYS: readonly MessageKey[] = [
'main.noModelRunning',
'main.modelStarting',
'main.translation.noModel',
'main.translation.startFailed',
// #530: the translation handler's copy when the OS refused to start the engine program.
'main.engine.cannotRun',
// #1012: …and when an engine file could not be read just now (try again in a minute).
'main.engine.filesUnreadable',
// #913: …and when the start check found the translation model's file damaged (the Translate
// screen's own copy: download it again on the AI Model screen).
'translate.err.modelDamaged',
'main.model.contextExceeded',
'main.task.refusedChatStreaming',
'main.task.documentNotReady',
'main.task.genericFailure',
'main.task.translationTarget',
'main.task.sourceUnreadable',
'main.task.comparePickTwo',
'main.task.compareReindex',
'main.task.needsOcr',
// Also thrown by the dequeue-time guard in handlers/ocr.ts — must pass the friendly filter
// or the user sees the generic failure (#232).
'main.task.ocrUnavailable',
'main.task.ocrNotAScan',
'main.task.ocrNoText',
'main.task.ocrFailed',
'main.task.documentBusyIngesting',
// #185/#186 — the occupancy refusals `startDocTask` can throw. Only these two lanes: the
// chat lane is refused by `main.task.refusedChatStreaming` above, and a doc task never
// refuses on the doc-task lane (the queue serializes tasks; see `DocTaskDeps.occupiedLane`).
'main.busy.skillRun',
'main.busy.benchmark'
]
/**
* True when a thrown message is our own friendly guard copy (exact match). The guards
* throw via tMain(), so the message may be in ANY registered UI language — and the cached
* language can even change between a guard throwing and the failure being recorded — so
* every catalog in the registry is checked, not just the current one (i18n record §3.3
* rule 3). A language left out would have its guard copy replaced by the generic failure.
*/
export function isFriendlyTaskError(raw: string): boolean {
return FRIENDLY_TASK_ERROR_KEYS.some((key) => UI_LANGUAGES.some(({ code }) => raw === t(code, key)))
}