AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import type { DocTaskKind, DocTaskStatus } from '@shared/types'
// Renderer-side watcher for the document task the Documents screen started (the backend
// runs one task at a time and queues the rest).
//
// Lives at MODULE level, not inside a screen component: a summary/translation keeps
// running in the main process while the user navigates away, so the busy/progress
// state (and its polling loop) must survive screen unmounts. Screens subscribe via
// `useSyncExternalStore(subscribeDocTask, getActiveDocTask)`. ONE store covers every task
// kind the Documents screen starts. It holds only those: a Translate-screen file translation,
// a skill's `categorize` or an import's deep-index build share the lane without an entry
// here, so a Cancel names the task it means (#689) — the Documents row's
// `cancelActiveDocTask()` sends this entry's id, the chat busy banner's
// `cancelRunningDocTask()` sends none.
//
// Lifecycle: start → poll every POLL_MS → terminal status stays visible (so a screen
// the user returns to can show the outcome) until a screen acknowledges it with
// `acknowledgeDocTask()`.
export interface ActiveDocTask {
jobId: string
kind: DocTaskKind
/**
* The SOURCE documents the task runs over (summary/translation: one; compare: two,
* in A/B order) — the rows that show the busy state.
*/
documentIds: string[]
/** Latest polled status; null until the first poll lands. */
status: DocTaskStatus | null
/** CODE-6: true after MAX_POLL_FAILURES consecutive poll errors — live state unknown, task kept. */
stateUnknown: boolean
/**
* DOC-5 (#150): the user clicked Cancel on this task (OCR's honest "Stopping if
* possible…" latch). On the STORE entry — not row state — so PERF-2 windowing can
* unmount/remount the row without re-enabling Cancel while the cancel is pending.
* Survives poll ticks (each spreads the entry as it is after its round-trip, #680); a rejected
* cancel clears it; a new task starts without it.
*/
cancelRequested?: boolean
}
const POLL_MS = 400
// CODE-6 (full-audit 2026-07-11) — the skillruns SKA-40 tolerance, ported: how many CONSECUTIVE
// poll failures the active task tolerates before the store gives up polling it. On give-up it
// keeps a labelled "state unknown" task (never silently dropping a live task — today ONE
// transient IPC error nulled the store: the busy/Cancel UI vanished while the task still ran,
// `anyTaskActive` flipped false so re-enabled actions hit backend busy-rejects, and the
// done-task effect never fired, so a finished task's outcome was never surfaced).
const MAX_POLL_FAILURES = 3
let active: ActiveDocTask | null = null
let timer: ReturnType<typeof setInterval> | null = null
/** CODE-6: consecutive poll-failure counter for the active task; any successful poll resets it. */
let pollFailures = 0
const listeners = new Set<() => void>()
function notify(): void {
for (const fn of listeners) fn()
}
function setActive(next: ActiveDocTask | null): void {
active = next
notify()
}
function stopPolling(): void {
if (timer) {
clearInterval(timer)
timer = null
}
}
export function subscribeDocTask(fn: () => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
/** Snapshot for useSyncExternalStore — a fresh object per change, stable between. */
export function getActiveDocTask(): ActiveDocTask | null {
return active
}
export function isDocTaskTerminal(status: DocTaskStatus | null): boolean {
return status != null && (status.state === 'done' || status.state === 'failed' || status.state === 'cancelled')
}
/**
* PF-7b (full-audit 2026-07-10): the fields whose change means subscribers must re-render —
* an identical 400 ms poll tick skips the set entirely (the skillruns `sameRun` precedent,
* SKA-39), so a long-running task no longer re-renders every subscribed screen ~2.5×/s.
*/
function sameStatus(a: DocTaskStatus | null, b: DocTaskStatus): boolean {
return (
a != null &&
a.state === b.state &&
a.progress.stepsDone === b.progress.stepsDone &&
a.progress.stepsTotal === b.progress.stepsTotal &&
(a.error ?? null) === (b.error ?? null) &&
(a.resultRef?.documentId ?? null) === (b.resultRef?.documentId ?? null)
)
}
/**
* Start a document task over one document (summary/translation) or two (compare,
* A/B order) and begin polling. Throws the backend's friendly error when the task is
* refused (chat streaming, no runtime, bad params, …).
*/
export async function startTask(
kind: DocTaskKind,
documentIds: string | string[],
params?: Record<string, unknown>
): Promise<void> {
const ids = Array.isArray(documentIds) ? documentIds : [documentIds]
const { jobId } = await window.api.startDocTask({ kind, documentIds: ids, params })
stopPolling()
pollFailures = 0 // CODE-6: the counter tracks the CURRENT task's polling run
setActive({ jobId, kind, documentIds: ids, status: null, stateUnknown: false })
// The id this timer is watching. Reassigned when a chained follow-up task is adopted
// (deep-index tree → extract, #38), so the same loop keeps polling through both passes.
let watchedJobId = jobId
/**
* #680: the entry this loop polls, read NOW — null once a lock purge (SH-4) dropped it or a newer
* task replaced it. A tick reads it again after its round-trips: writing back the entry it read
* before them undid a purge and dropped a Cancel latch (DOC-5) set in between.
*/
const watched = (): ActiveDocTask | null => (active?.jobId === watchedJobId ? active : null)
// #680: one tick at a time (fileTranslateSession's TA-3 / H4 latch, local to this timer): an
// overlapping tick could give up (CODE-6) while a slower one was still in flight.
let inFlight = false
timer = setInterval(() => {
if (inFlight) return // a slower-than-POLL_MS round-trip is still resolving; skip this tick
inFlight = true
void (async () => {
try {
if (!watched()) {
stopPolling()
return
}
const status = await window.api.getDocTask(watchedJobId)
// Chain adoption (#38): "Build deep index" starts a 'tree' task (withExtract) that
// chains a backend 'extract' task over the same document. When the tree completes,
// adopt the running follow-up task so the row busy state and the chat task banner
// stay truthful through both passes. No follow-up (chain dropped: chat streaming /
// runtime gone) or a foreign task over other documents keeps the ordinary terminal
// handling — the backend ran or dropped the extract either way.
const next =
status.state === 'done' && params?.withExtract === true
? await window.api.getActiveDocTask?.().catch(() => null)
: null
const current = watched()
if (!current) return // purged or replaced during the round-trips; its timer is gone
pollFailures = 0 // CODE-6: only CONSECUTIVE failures count — any success resets
if (
next &&
next.jobId !== watchedJobId &&
!isDocTaskTerminal(next) &&
next.documentIds.some((id) => current.documentIds.includes(id))
) {
watchedJobId = next.jobId
setActive({ jobId: next.jobId, kind: next.kind, documentIds: next.documentIds, status: next, stateUnknown: false })
return
}
// PF-7b: an unchanged tick sets nothing — subscribers keep the same snapshot object.
if (!sameStatus(current.status, status)) setActive({ ...current, status })
if (isDocTaskTerminal(status)) stopPolling()
} catch {
// CODE-6 (full-audit 2026-07-11; SKA-40 port): tolerate transient IPC errors; give up
// only after MAX_POLL_FAILURES in a row, and KEEP a labelled "state unknown" task
// rather than silently dropping a live one (one flaky poll used to null the store).
// Below the max the snapshot stays untouched, so subscribers see no churn at all.
const current = watched()
if (!current) return // #680: a purged or replaced entry's failures are not this task's
pollFailures += 1
if (pollFailures >= MAX_POLL_FAILURES) {
stopPolling()
setActive({ ...current, stateUnknown: true })
}
} finally {
inFlight = false
}
})()
}, POLL_MS)
}
/**
* Cancel this store's task, running or queued — the Documents row's Cancel. #689: by its id. With
* no id, main cancels whatever holds the lane, so a row task queued behind another screen's task
* stopped THAT task and then ran itself. An exact id is stale-safe (#157 DT-2): a settled task is a
* no-op, and a newer task has a different id.
*/
export async function cancelActiveDocTask(): Promise<void> {
const jobId = active?.jobId
if (!jobId) return
try {
await window.api.cancelDocTask(jobId)
} catch (e) {
// #680: a rejected cancel stopped nothing — drop the DOC-5 latch so the row offers Cancel
// again instead of a disabled "Stopping if possible…"; the caller shows the error (CODE-29).
if (active?.cancelRequested && active.jobId === jobId) setActive({ ...active, cancelRequested: false })
throw e
}
}
/**
* Cancel the task holding the lane (running, else the next queued) — the chat busy banner's
* Cancel. #689: deliberately untargeted. Chat is refused while ANY task is active
* (`hasActiveTask()`), the copy names the running one, and this store may hold nothing or a task
* queued behind it; cancelling that one would leave chat refused.
*/
export async function cancelRunningDocTask(): Promise<void> {
await window.api.cancelDocTask()
}
/** DOC-5 (#150): latch a requested cancel onto the active entry (see `cancelRequested`). */
export function markDocTaskCancelRequested(): void {
if (active && !active.cancelRequested) setActive({ ...active, cancelRequested: true })
}
/**
* Clear a finished (terminal) task after a screen has handled its outcome. A state-unknown
* task (CODE-6 give-up) is dismissible the same way — mirroring skillruns' acknowledge —
* so a task whose live state the store could no longer learn is never stuck forever.
*/
export function acknowledgeDocTask(): void {
if (active && (isDocTaskTerminal(active.status) || active.stateUnknown)) {
setActive(null)
}
}
/**
* Workspace-lock purge (SH-4, #149 — the lockPurge.ts seam; subsumes DOC-9): stop the 400 ms
* watcher (it would keep firing IPC against the locked workspace until the CODE-6 give-up
* parked a `stateUnknown` row that then SURVIVED into the next unlock for a task main already
* aborted) and drop the entry. Listeners are kept and notified.
*/
export function clearDocTaskSession(): void {
stopPolling()
pollFailures = 0
if (active) setActive(null)
}