Skip to content

AI, fully local on your computer.

27.6 KB
Raw Blame
import { existsSync, readFileSync } from 'node:fs'
import { lstat, mkdir, realpath, rename, rm } from 'node:fs/promises'
import { randomUUID } from 'node:crypto'
import { isAbsolute, join, relative } from 'node:path'
import { parse as parseYaml } from 'yaml'
import { tMain } from './i18n'
import type { MessageKey } from '../../shared/i18n'
import type {
  OcrInstallJob,
  OcrInstallLanguage,
  OcrInstallStatus,
  OcrRefreshOutcome
} from '../../shared/types'
import { validateRuntimeSources, type OcrSources } from '../../shared/runtime-sources'
import {
  downloadToFile,
  failureReason,
  isDiskError,
  planOcrDownloads,
  verifyDownloadedFile,
  type FetchFn,
  type OcrFileTask
} from './assets'
import { assertDownloadAllowed, NetworkSwitch, type DownloadGates } from './downloads'
import { ocrAssetsDir } from './ocr/factory'
import { OCR_ORIENTATION_LANG } from './ocr/orientation'

// In-app installer for the OCR language files (#410). OCR is deliberately NOT an engine family
// (`RuntimeFamily` / `SIDECAR_FAMILY_SPECS` are archive-shaped: download → verify → clean →
// extract → flatten → marker); the language files are a handful of plain, hash-verified files
// where the hash IS the install state. So this is its own narrow service, composed from the same
// audited parts the drive builder and the engine installer use:
//
// - WHAT is installed is anchored in CODE (`OCR_PINS`: language, sha256, exact size), drift-tested
//   against the committed `model-manifests/runtime-sources.yaml`. The drive's user-writable yaml
//   contributes ONLY the download URL of each pinned language — an entry whose sha256 differs from
//   the pin is never used, its `dest` is ignored (the destination is always `ocr/<lang>.traineddata.gz`
//   under the drive root) and its other languages are ignored. So the yaml can at most redirect the
//   host (the accepted trust-by-location residual, security-model.md S4), never choose the bytes or
//   the path. No URL literal lives in `src/` (the R-O2 no-CDN sentinel in tests/unit/ocr.test.ts).
// - Sources, per pinned file (#841): the first list whose entry for it carries the pinned sha256,
//   the drive's `model-manifests/` first (a drive owner's mirror keeps working), then the app's own
//   copy, which matches the pins by construction (a bare portable exe reads the bundled one anyway).
//   A yaml that does not validate as a whole offers no list. No list → unavailable; a file that
//   matches in no list → mismatch, refused.
// - `planOcrDownloads` decides what to fetch, so a present file matching its pin is skipped — the
//   same hash-is-state rule `prepare-drive` / `fetch-runtime --family ocr` and the sell gate use.
// - Per file: `<dest>.part` → `downloadToFile` (https-only per hop, private-host deny, ≤5 redirects,
//   `maxBytes` = the pinned size + 1 MiB) → `verifyDownloadedFile` against the PIN → rename over
//   `<dest>` (the effective cap is the pinned size + 2 MiB: this 1 MiB headroom plus
//   `downloadToFile`'s own margin). A mismatch deletes the `.part` and leaves an existing file
//   untouched. Nothing else in `ocr/` is ever listed, deleted or modified (a user-added third
//   language survives).
// - `ocr/` is created when missing and refused when it is a symlink/junction or resolves outside the
//   drive root — checked at start and again before every write.
// - After ALL files are in place, the caller's `activate` (the engine-slot refresh,
//   `refreshOcrSlot`) runs and its outcome lands on the job; the job reaches 'done' only after it.
// - Gates are the model downloader's (`assertDownloadAllowed`: policy ceiling ∧ the allowNetwork
//   setting), re-checked on every start. One install at a time (a synchronous latch — the
//   downloads.ts precedent). Jobs live in memory for the session. Logs carry language codes, byte
//   counts and outcomes only — never URLs, paths or error text.

/** The licence of the tesseract language data (approved, docs/model-policy.md). Code-side. */
const OCR_LICENSE = 'Apache-2.0'

/** One pinned OCR file: what the app installs, anchored in code (#410). */
export interface OcrPin {
  /**
   * Traineddata code — also the file name (`<lang>.traineddata.gz`). A recognition language, or
   * `osd`: the orientation data that turns sideways pages upright (#538), never read with.
   */
  lang: string
  /** SHA-256 of the file AS DOWNLOADED (the gzip), lower-case hex. */
  sha256: string
  /** Exact byte size of that file. */
  sizeBytes: number
}

/**
 * The pinned bundle (D6: `deu` + `eng`, installed together; #538 added `osd`, the orientation
 * data). Hashes = the committed `runtime-sources.yaml` `ocr:` block; hashes and sizes = docs/model-policy.md
 * "The OCR asset class" (both drift-tested, tests/unit/ocr-pins.test.ts); sizes measured
 * from the pinned files themselves (`@tesseract.js-data/{deu,eng,osd}@1.0.0`, `4.0.0_best_int` —
 * deu/eng on 2026-09-22, osd on 2026-10-05; 1.27 / 2.82 / 4.12 MB in docs/model-policy.md "The OCR
 * asset class"). A drive that already has deu + eng downloads only `osd` (`planOcrDownloads`).
 */
export const OCR_PINS: readonly OcrPin[] = [
  { lang: 'deu', sha256: '306c4280d0cbed46fbff727486bd43b92730181bae80f56941a091f363bdf28b', sizeBytes: 1_333_102 },
  { lang: 'eng', sha256: '45b4cb346724ac1774f1c36f42f182b887bcdb28ebe63e6fff90ac41f3fcff91', sizeBytes: 2_952_873 },
  { lang: 'osd', sha256: 'be028ddaac8b03402b92cbf526075c068ec39a9f1dbbcd7536dddb9b22209934', sizeBytes: 4_320_130 }
]

/** Headroom over a pinned size for the download body cap (the file is exact; this is framing). */
export const OCR_SIZE_CAP_HEADROOM = 1024 * 1024

/** The fixed, drive-relative destination of a pinned language (the yaml's `dest` is ignored). */
export function ocrPinRelPath(lang: string): string {
  return `ocr/${lang}.traineddata.gz`
}

/** Where a pinned language lands on this drive. */
function ocrPinDest(rootPath: string, lang: string): string {
  return join(ocrAssetsDir(rootPath), `${lang}.traineddata.gz`)
}

/** A user-facing refusal: the message is the localized copy for `key`. */
class OcrInstallError extends Error {
  constructor(readonly key: MessageKey) {
    super(tMain(key))
    this.name = 'OcrInstallError'
  }
}

/**
 * Validate the renderer's `ocr:install` arguments (#410): the install takes NO payload. Anything
 * but "nothing" is refused with friendly copy — the argument is never inspected further or echoed.
 */
export function assertNoOcrInstallPayload(args: readonly unknown[]): void {
  if (args.some((a) => a !== undefined)) throw new OcrInstallError('main.ocr.badRequest')
}

/** The yaml `ocr:` block of one manifests dir, or null when absent/unreadable/invalid. */
function loadOcrBlock(manifestsDir: string): OcrSources | null {
  const path = join(manifestsDir, 'runtime-sources.yaml')
  if (!existsSync(path)) return null
  try {
    const result = validateRuntimeSources(parseYaml(readFileSync(path, 'utf8')))
    return result.ok ? (result.ocr ?? null) : null
  } catch {
    return null
  }
}

type OcrSourceResolution =
  | { kind: 'ok'; urls: ReadonlyMap<string, string> }
  | { kind: 'none' }
  | { kind: 'mismatch' }

/**
 * Where to download each pinned file from: per file, the first source list whose entry for it
 * carries the pinned sha256 — the drive's yaml first (a drive owner's own mirror keeps working),
 * then the app's own copy, which matches the pins by construction (drift-tested,
 * tests/unit/ocr-pins.test.ts). #841: a drive's list written before this app's pins changed (one
 * prepared before `osd` existed, #538) used to refuse the whole install although the app's own
 * list carried every file; that is the normal state after copying a new app onto a Kit. An entry
 * with another sha256 is never used, so the bytes are still the code pins': the yaml only ever
 * chooses the host. `mismatch` when some pinned file has a matching entry in no list (version skew
 * or tampering, with the app's own list missing or damaged too); `none` when no list offers a
 * usable `ocr:` block (none, or a yaml that does not validate).
 */
function resolveOcrSources(
  manifestsDir: string | null,
  bundledManifestsDir: string | null,
  pins: readonly OcrPin[] = OCR_PINS
): OcrSourceResolution {
  const dirs = [manifestsDir, bundledManifestsDir].filter(
    (d, i, all): d is string => typeof d === 'string' && d !== '' && all.indexOf(d) === i
  )
  const blocks = dirs.map(loadOcrBlock).filter((b): b is OcrSources => b !== null)
  if (blocks.length === 0) return { kind: 'none' }
  const entries = blocks.flatMap((b) => b.files) // in list order: the drive's first
  const urls = new Map<string, string>()
  for (const pin of pins) {
    const file = entries.find((f) => f.lang === pin.lang && f.sha256 === pin.sha256)
    if (!file) return { kind: 'mismatch' }
    urls.set(pin.lang, file.url)
  }
  return { kind: 'ok', urls }
}

/** The pins as `planOcrDownloads` input: the code's hash + fixed destination, the yaml's URL. */
function pinnedSources(pins: readonly OcrPin[], urls: ReadonlyMap<string, string> | null): OcrSources {
  return {
    version: 'pinned',
    files: pins.map((pin) => ({
      lang: pin.lang,
      url: urls?.get(pin.lang) ?? '',
      sha256: pin.sha256,
      dest: ocrPinRelPath(pin.lang)
    }))
  }
}

/** The distinct hosts of the pinned URLs, for the confirmation dialog ("From"). */
function sourceHosts(urls: ReadonlyMap<string, string>): string | null {
  const hosts: string[] = []
  for (const url of urls.values()) {
    try {
      const host = new URL(url).host
      if (!hosts.includes(host)) hosts.push(host)
    } catch {
      /* the validator only admits https URLs; an unparsable one names no host */
    }
  }
  return hosts.length > 0 ? hosts.join(', ') : null
}

/**
 * Make sure `<root>/ocr` is an ordinary folder inside the drive root before anything is written
 * into it (#410): created when missing; refused when it is a symlink/junction, not a directory,
 * or resolves (realpath) outside the root. Returns the folder path.
 */
async function prepareOcrFolder(rootPath: string): Promise<string> {
  const dir = ocrAssetsDir(rootPath)
  try {
    await lstat(dir)
  } catch {
    try {
      await mkdir(dir, { recursive: true })
    } catch {
      throw new OcrInstallError('main.ocr.writeFailed')
    }
  }
  let unsafe = false
  try {
    const st = await lstat(dir)
    if (st.isSymbolicLink() || !st.isDirectory()) {
      unsafe = true
    } else {
      const [realRoot, realDir] = await Promise.all([realpath(rootPath), realpath(dir)])
      const rel = relative(realRoot, realDir)
      unsafe = rel === '' || rel.startsWith('..') || isAbsolute(rel)
    }
  } catch {
    throw new OcrInstallError('main.ocr.writeFailed')
  }
  if (unsafe) throw new OcrInstallError('main.ocr.unsafeFolder')
  return dir
}

/** Where the install sources live — the drive's manifests dir and the app-bundled one. */
export interface OcrInstallSourceOptions {
  rootPath: string
  /** The resolved (drive or env-override) `model-manifests/` dir, or null. */
  manifestsDir: string | null
  /** The app-bundled `model-manifests/` (no env override), or null. */
  bundledManifestsDir: string | null
}

/** The OCR install's audit events (#843). */
export type OcrInstallAuditType = 'ocr_install_started' | 'ocr_install_finished' | 'ocr_install_failed'

/**
 * Where a job's audit events go (#843): the IPC layer passes the app recorder (`ctx.audit`) and adds
 * the job's `trigger`. The metadata is language codes, byte counts and content-free codes only
 * (`{ jobId, languages, bytes }`, plus `outcome` when finished, `reason`/`cause` when not) — never the
 * job's `error` text.
 */
export type OcrInstallAudit = (type: OcrInstallAuditType, message: string, metadata: Record<string, unknown>) => void

export interface StartOcrInstallOptions extends OcrInstallSourceOptions {
  gates: DownloadGates
  /** #843: records the job's start and its end (finished, or failed with a reason code). */
  audit?: OcrInstallAudit
  /**
   * Bring the engine slot up to date once every file is in place (`refreshOcrSlot`). Its outcome
   * is the job's `outcome`. Expected never to reject; a rejection reads as `'startFailed'`.
   */
  activate: () => Promise<OcrRefreshOutcome>
}

export interface OcrInstallDeps {
  fetchImpl?: FetchFn
  /** Injected verifier (default `verifyDownloadedFile`) — tests gate it to pin cancel-in-verify. */
  verifyImpl?: typeof verifyDownloadedFile
  /** The pinned bundle (default `OCR_PINS`); tests pass pins that hash their fake bodies. */
  pins?: readonly OcrPin[]
  /** Content-free log sink (language codes, byte counts, outcomes). */
  log?: (msg: string, meta?: Record<string, unknown>) => void
}

const LIVE: ReadonlySet<OcrInstallJob['status']> = new Set([
  'queued',
  'downloading',
  'verifying',
  'activating'
])

const MAX_TERMINAL_JOBS = 10

/**
 * Owns the in-app OCR install job (#410). One at a time; a single job fetches every pinned
 * language that is missing or does not match its pin, then activates the engine slot. The
 * renderer polls `get(jobId)`.
 */
export class OcrInstallManager {
  private readonly jobs = new Map<string, OcrInstallJob>()
  private active: { jobId: string; controller: AbortController } | null = null
  /** #782: the internet-access switch between this manager's gate checks. */
  private readonly network = new NetworkSwitch()
  /** Synchronous single-flight latch over the awaits inside `start()` (the downloads.ts rule). */
  private starting = false
  /** False while a `run()` is still settling — a cancelled job's activation may still be running. */
  private runSettled = true
  /** #843: why each job stopped (the first reason recorded stands), for its audit record. */
  private readonly endReasons = new Map<string, { reason: string; cause?: string }>()
  private readonly pins: readonly OcrPin[]

  constructor(private readonly deps: OcrInstallDeps = {}) {
    this.pins = deps.pins ?? OCR_PINS
  }

  /**
   * What the confirmation dialog states and whether the action can be offered: per pinned
   * language its size and whether it is on the drive AND matches its pin; the bytes still to
   * download; the source host from the yaml URL; the code-side licence. Never throws.
   */
  async status(opts: OcrInstallSourceOptions): Promise<OcrInstallStatus> {
    const resolved = resolveOcrSources(opts.manifestsDir, opts.bundledManifestsDir, this.pins)
    const urls = resolved.kind === 'ok' ? resolved.urls : null
    let tasks: OcrFileTask[] = []
    try {
      tasks = await planOcrDownloads(opts.rootPath, pinnedSources(this.pins, urls))
    } catch {
      tasks = []
    }
    const languages: OcrInstallLanguage[] = this.pins.map((pin) => ({
      lang: pin.lang,
      role: pin.lang === OCR_ORIENTATION_LANG ? 'orientation' : 'language',
      sizeBytes: pin.sizeBytes,
      installed: tasks.find((t) => t.lang === pin.lang)?.status === 'present-verified'
    }))
    // The confirmation's "From" names the hosts this install will contact: those of the files the plan
    // still downloads (#841 can mix the drive's list and the app's own), or every file's once all are
    // in place.
    const toFetch = new Map(tasks.filter((t) => t.status === 'download').map((t) => [t.lang, t.url]))
    return {
      available: resolved.kind === 'ok',
      languages,
      totalBytes: languages.filter((l) => !l.installed).reduce((sum, l) => sum + l.sizeBytes, 0),
      sourceHost: urls ? sourceHosts(toFetch.size > 0 ? toFetch : urls) : null,
      license: OCR_LICENSE
    }
  }

  /**
   * Check the gates and the sources, plan the files, and start the install in the background.
   * Throws a friendly, cause-specific error when a gate is closed, an install is already running,
   * no usable source list exists, every file is already in place, or `ocr/` is unsafe.
   */
  async start(opts: StartOcrInstallOptions): Promise<OcrInstallJob> {
    this.pruneTerminalJobs()
    assertDownloadAllowed(opts.gates)
    const networkMark = this.network.mark()
    if (this.activeJob() !== null || this.starting) {
      throw new OcrInstallError('main.ocr.alreadyRunning')
    }
    this.starting = true
    try {
      const resolved = resolveOcrSources(opts.manifestsDir, opts.bundledManifestsDir, this.pins)
      if (resolved.kind === 'none') throw new OcrInstallError('main.ocr.noSources')
      if (resolved.kind === 'mismatch') throw new OcrInstallError('main.ocr.sourcesMismatch')
      let tasks: OcrFileTask[]
      try {
        // Hashes a present file — an AV lock or an ACL can make that read fail; never surface the
        // raw error (it names the drive path).
        tasks = await planOcrDownloads(opts.rootPath, pinnedSources(this.pins, resolved.urls))
      } catch {
        throw new OcrInstallError('main.ocr.readFailed')
      }
      const toFetch = tasks.filter((t) => t.status === 'download')
      if (toFetch.length === 0) throw new OcrInstallError('main.ocr.alreadyInstalled')
      await prepareOcrFolder(opts.rootPath)
      // #782: internet access was switched off while this start planned (the plan hashes the files
      // already on the drive), and is still off: the gates it began with no longer hold.
      if (!this.network.stillAllowed(networkMark)) throw new OcrInstallError('main.download.networkOff')

      const plan = toFetch.map((task) => ({
        task,
        pin: this.pins.find((p) => p.lang === task.lang) as OcrPin
      }))
      const job: OcrInstallJob = {
        jobId: randomUUID(),
        status: 'queued',
        receivedBytes: 0,
        totalBytes: plan.reduce((sum, p) => sum + p.pin.sizeBytes, 0),
        outcome: null,
        error: null
      }
      this.jobs.set(job.jobId, job)
      const controller = new AbortController()
      this.active = { jobId: job.jobId, controller }
      this.runSettled = false
      const languages = plan.map((p) => p.pin.lang)
      this.deps.log?.('OCR install started', {
        jobId: job.jobId,
        languages,
        bytes: job.totalBytes
      })
      const auditMeta = { jobId: job.jobId, languages, bytes: job.totalBytes }
      // Never throws, like the end's: a failing sink here used to reject start() with the job already
      // active, so every later install read "already running" until the app restarted.
      try {
        opts.audit?.('ocr_install_started', `OCR install started: ${languages.join(', ')}`, { ...auditMeta })
      } catch (err) {
        this.deps.log?.('OCR install audit failed', { error: String(err) })
      }
      void this.run(job, plan, opts, controller).finally(() => {
        this.runSettled = true
        if (this.active?.jobId === job.jobId) this.active = null
        this.auditEnd(job, opts.audit, auditMeta, languages)
      })
      return { ...job }
    } finally {
      this.starting = false
    }
  }

  /** #843: the job's one terminal audit event, once its run has settled. Never throws. */
  private auditEnd(
    job: OcrInstallJob,
    audit: OcrInstallAudit | undefined,
    meta: Record<string, unknown>,
    languages: readonly string[]
  ): void {
    if (!audit) return
    const what = languages.join(', ')
    try {
      if (job.status === 'done') {
        audit('ocr_install_finished', `OCR install finished: ${what}`, { ...meta, outcome: job.outcome })
        return
      }
      const recorded = this.endReasons.get(job.jobId)
      const reason = recorded?.reason ?? (job.status === 'cancelled' ? 'cancelled' : 'failed')
      audit('ocr_install_failed', `OCR install failed: ${what}`, {
        ...meta,
        reason,
        ...(recorded?.cause ? { cause: recorded.cause } : {})
      })
    } catch (err) {
      this.deps.log?.('OCR install audit failed', { error: String(err) })
    }
  }

  /** #843: record why `job` stops; the first reason recorded for a job stands. */
  private noteEnd(job: OcrInstallJob, reason: string, cause?: unknown): void {
    if (this.endReasons.has(job.jobId)) return
    this.endReasons.set(job.jobId, { reason, ...(typeof cause === 'string' ? { cause } : {}) })
  }

  get(jobId: string): OcrInstallJob {
    const job = this.jobs.get(jobId)
    if (job) return { ...job }
    return {
      jobId: typeof jobId === 'string' ? jobId : '',
      status: 'failed',
      receivedBytes: 0,
      totalBytes: 0,
      outcome: null,
      error: tMain('main.ocr.unknownJob')
    }
  }

  /**
   * Cancel an install in ANY live state. A cancel during a download or the hash discards that
   * file's `.part`; files already renamed into place stay (they are verified). A cancel during
   * 'activating' marks the job cancelled, but the slot refresh itself is bounded and runs to its
   * end — the renderer re-reads the app status on every terminal state, so it shows the truth.
   */
  cancel(jobId: string): OcrInstallJob {
    const job = this.jobs.get(jobId)
    if (!job) return this.get(jobId)
    if (LIVE.has(job.status)) {
      job.status = 'cancelled'
      this.noteEnd(job, 'cancelled')
      if (this.active?.jobId === jobId) this.active.controller.abort()
      this.deps.log?.('OCR install cancelled', { jobId })
    }
    return { ...job }
  }

  /**
   * #782: internet access was switched off (`on` false) or back on. Off: a file download in progress
   * stops at once (its `.part` goes, as for a cancel); a job checking a file finishes that file and
   * stops before its next download; one past its last download finishes; a start still planning is
   * refused when its plan is done. `onStopped` runs once, when (and if) the job stops. On before
   * that: the job carries on.
   */
  networkSwitched(on: boolean, onStopped: () => void = () => undefined): void {
    if (on) return this.network.switchedOn()
    const active = this.active
    this.network.switchedOff(active?.controller ?? null, onStopped)
    const job = active ? this.jobs.get(active.jobId) : undefined
    if (active && job && (job.status === 'queued' || job.status === 'downloading')) {
      this.stopNetworkJob(job, active.controller)
    }
  }

  /** Stop `job` for #782: it reads `cancelled`, and its run cleans up as a cancel's does. */
  private stopNetworkJob(job: OcrInstallJob, controller: AbortController): void {
    job.status = 'cancelled'
    this.noteEnd(job, 'networkOff')
    controller.abort()
    this.deps.log?.('OCR install stopped: internet access was switched off', { jobId: job.jobId })
    this.network.stopped(controller)
  }

  /** The live job's id — also while a cancelled job's run is still settling. */
  activeJob(): string | null {
    if (!this.active) return null
    const job = this.jobs.get(this.active.jobId)
    if (!job) return null
    return LIVE.has(job.status) || !this.runSettled ? this.active.jobId : null
  }

  private pruneTerminalJobs(): void {
    const terminal = [...this.jobs.values()].filter((j) => !LIVE.has(j.status))
    for (const job of terminal.slice(0, Math.max(0, terminal.length - MAX_TERMINAL_JOBS))) {
      this.jobs.delete(job.jobId)
      this.endReasons.delete(job.jobId)
    }
  }

  private fail(job: OcrInstallJob, key: MessageKey, meta: Record<string, unknown>): void {
    // A cancel that landed during the cleanup await wins: the user asked to stop.
    if (job.status === 'cancelled') return
    job.status = 'failed'
    job.error = tMain(key)
    // #843: the key's last part is the audit's reason code (`downloadFailed`, `checksumMismatch`, …),
    // the log's own `reason` its cause (`http-404`, `mismatch`, `rename`, …): both content-free.
    this.noteEnd(job, key.replace(/^main\.(ocr|download)\./, ''), meta.reason)
    this.deps.log?.('OCR install failed', { jobId: job.jobId, ...meta })
  }

  private async run(
    job: OcrInstallJob,
    plan: Array<{ task: OcrFileTask; pin: OcrPin }>,
    opts: StartOcrInstallOptions,
    controller: AbortController
  ): Promise<void> {
    const signal = controller.signal
    const verify = this.deps.verifyImpl ?? verifyDownloadedFile
    // Every abort path ends here: the `.part` (if any) is removed and the job reads 'cancelled'
    // — set explicitly, because a status assignment may have raced the synchronous cancel().
    const aborted = async (part: string | null): Promise<void> => {
      if (part) await rm(part, { force: true }).catch(() => undefined)
      job.status = 'cancelled'
    }
    let doneBytes = 0
    for (const { task, pin } of plan) {
      if (signal.aborted) return aborted(null)
      const dest = ocrPinDest(opts.rootPath, pin.lang)
      const part = `${dest}.part`
      try {
        await prepareOcrFolder(opts.rootPath)
        // A planted `.part` symlink must not redirect the write: remove whatever sits there first
        // (rm unlinks a link, never its target), then the download creates a fresh file.
        await rm(part, { force: true })
      } catch (err) {
        if (signal.aborted) return aborted(null)
        const key = err instanceof OcrInstallError ? err.key : 'main.ocr.writeFailed'
        this.fail(job, key, { lang: pin.lang, reason: 'folder' })
        return
      }
      // #782: internet access went off while an earlier file was checked: nothing new is fetched.
      if (!signal.aborted && this.network.stopsAt(controller)) this.stopNetworkJob(job, controller)
      if (signal.aborted) return aborted(part)

      job.status = 'downloading'
      try {
        await downloadToFile(task.url, part, {
          fetchImpl: this.deps.fetchImpl,
          signal,
          maxBytes: pin.sizeBytes + OCR_SIZE_CAP_HEADROOM,
          onProgress: (received) => {
            job.receivedBytes = doneBytes + received
          }
        })
      } catch (err) {
        if (signal.aborted) return aborted(part)
        await rm(part, { force: true }).catch(() => undefined)
        // A full or write-protected drive must not be reported as "check the internet".
        this.fail(job, isDiskError(err) ? 'main.ocr.writeFailed' : 'main.ocr.downloadFailed', {
          lang: pin.lang,
          reason: failureReason(err)
        })
        return
      }
      if (signal.aborted) return aborted(part)

      job.status = 'verifying'
      let result: Awaited<ReturnType<typeof verifyDownloadedFile>>
      try {
        result = await verify(part, pin.sha256)
      } catch {
        if (signal.aborted) return aborted(part)
        await rm(part, { force: true }).catch(() => undefined)
        this.fail(job, 'main.ocr.writeFailed', { lang: pin.lang, reason: 'verify' })
        return
      }
      if (signal.aborted) return aborted(part)
      if (!result.ok) {
        // Mismatch, missing, or (a mis-authored pin) a placeholder: never trusted. The existing
        // `<dest>` — if any — is untouched: only the `.part` is removed.
        await rm(part, { force: true }).catch(() => undefined)
        this.fail(job, 'main.ocr.checksumMismatch', {
          lang: pin.lang,
          reason: result.reason ?? 'mismatch'
        })
        return
      }

      try {
        await prepareOcrFolder(opts.rootPath)
        if (signal.aborted) return aborted(part)
        await rename(part, dest)
      } catch (err) {
        await rm(part, { force: true }).catch(() => undefined)
        if (signal.aborted) return aborted(null)
        const key = err instanceof OcrInstallError ? err.key : 'main.ocr.writeFailed'
        this.fail(job, key, { lang: pin.lang, reason: 'rename' })
        return
      }
      doneBytes += pin.sizeBytes
      job.receivedBytes = doneBytes
      this.deps.log?.('OCR language file installed', { lang: pin.lang, bytes: pin.sizeBytes })
    }
    if (signal.aborted) return aborted(null)

    // Every file is in place: bring the engine slot up to date (#410 D2). The job is 'done' only
    // after the outcome is known, so the renderer can say "ready" or "restart" definitely.
    job.status = 'activating'
    let outcome: OcrRefreshOutcome
    try {
      outcome = await opts.activate()
    } catch {
      outcome = 'startFailed'
    }
    this.deps.log?.('OCR install finished', { jobId: job.jobId, outcome, cancelled: signal.aborted })
    if (signal.aborted) return aborted(null)
    job.outcome = outcome
    job.status = 'done'
  }
}