Skip to content

AI, fully local on your computer.

47.4 KB
Raw Blame
// @vitest-environment jsdom
import { describe, it, expect, vi, afterEach } from 'vitest'
import {
  getFileTranslate,
  translateDroppedFiles,
  translatePickedFile,
  cancelFileTranslation,
  adoptActiveFileTranslation,
  resetFileTranslation,
  clearFileTranslate
} from '../../src/renderer/lib/fileTranslateSession'
import {
  startTask,
  getActiveDocTask,
  isDocTaskTerminal,
  clearDocTaskSession
} from '../../src/renderer/lib/doctasks'
import {
  translate,
  getTranslateSession,
  clearTranslateSession
} from '../../src/renderer/lib/translateSession'
import type { DocTaskStatus, TranslateJob, ImportJobStatus } from '../../src/shared/types'
import type { PreloadApi } from '../../src/preload'
import { stubApi, assertNoUnexpectedApiCalls } from '../helpers/renderer'
import { hangBudgetMs, testBudgetMs } from '../helpers/hang-budget'

// F-41 (audit-2026-07-16): stub payloads are typed against the real PreloadApi bridge contract
// (no `as never` erasure) — a rename of any mocked method or its return shape reddens typecheck.
// `happyApi()` and the inline overrides below are `Partial<PreloadApi>`; the payload builders
// (`docTask`, `translateJob`) return the real shared types so field renames surface here too.

// Unit test for the document-translation store (TG-5, plan §2 D7): drop/pick → import as Temporary
// → translation doc-task → materialized Markdown, with the reject/guard paths. Polling is real; we
// wait on the module snapshot with vi.waitFor.

afterEach(() => {
  clearFileTranslate()
  clearTranslateSession()
  clearDocTaskSession()
  vi.restoreAllMocks()
  assertNoUnexpectedApiCalls()
})

const CHOICE = { sourceLang: 'de', targetLang: 'en' } as const

function docTask(over: Partial<DocTaskStatus> = {}): DocTaskStatus {
  return {
    jobId: 'task1',
    kind: 'translation',
    documentIds: ['d1'],
    state: 'running',
    progress: { stepsDone: 0, stepsTotal: 0 },
    ...over
  }
}

function translateJob(over: Partial<TranslateJob> = {}): TranslateJob {
  return { jobId: 't1', state: 'queued', text: '', ...over }
}

function happyApi(): Partial<PreloadApi> {
  let polls = 0
  return {
    getDroppedFilePath: vi.fn(() => 'C:\\docs\\a.pdf'),
    pickDocuments: vi.fn(async () => ({ token: 'tok1', paths: ['C:\\docs\\a.pdf'] })),
    importDocuments: vi.fn(async () => ({ jobId: 'imp1', documentIds: ['d1'] })),
    getImportJob: vi.fn(async () => ({ jobId: 'imp1', total: 1, completed: 1, failed: 0, done: true })),
    startDocTask: vi.fn(async () => ({ jobId: 'task1' })),
    getDocTask: vi.fn(async () => {
      polls += 1
      return polls === 1
        ? docTask({ progress: { stepsDone: 1, stepsTotal: 2 } })
        : docTask({ state: 'done', progress: { stepsDone: 2, stepsTotal: 2 }, resultRef: { documentId: 'gen1' } })
    }),
    previewDocument: vi.fn(async () => ({
      id: 'gen1',
      title: 'a (English)',
      mimeType: 'text/markdown',
      segments: [{ text: 'Hello world.', pageNumber: null, sectionLabel: null }],
      nextOffset: null
    }))
  }
}

describe('fileTranslateSession — happy path', () => {
  it('drops a file, imports it as Temporary, runs the doc-task, loads the materialized text', async () => {
    const api = happyApi()
    stubApi(api)
    const outcome = await translateDroppedFiles(
      [new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })],
      CHOICE
    )
    expect(outcome).toBe('started')
    expect(api.importDocuments).toHaveBeenCalledWith(['C:\\docs\\a.pdf'], {
      destination: { kind: 'temporary' }
    })

    await vi.waitFor(() => expect(getFileTranslate().state).toBe('done'), { timeout: hangBudgetMs(5000) })
    const snap = getFileTranslate()
    expect(snap.output).toBe('Hello world.')
    expect(snap.resultDocumentId).toBe('gen1')
    expect(snap.truncated).toBe(false)
    expect(snap.gaps).toBeNull() // #58: a complete translation carries no gap accounting
    expect(snap.busy).toBe(false)
    expect(api.startDocTask).toHaveBeenCalledWith({
      kind: 'translation',
      documentIds: ['d1'],
      params: { sourceLang: 'de', targetLang: 'en' }
    })
  }, testBudgetMs(8000))

  it('the picker path passes the capability token to the temporary import', async () => {
    const api = happyApi()
    stubApi(api)
    await translatePickedFile(CHOICE)
    await vi.waitFor(() => expect(api.importDocuments).toHaveBeenCalled(), { timeout: hangBudgetMs(5000) })
    expect(api.importDocuments).toHaveBeenCalledWith(['C:\\docs\\a.pdf'], {
      destination: { kind: 'temporary' },
      pickerToken: 'tok1'
    })
  }, testBudgetMs(8000))

  it('#58: the done status’ completeness accounting (gaps) reaches the snapshot', async () => {
    const gaps = { missingPageRanges: [{ from: 3, to: 3 }], failedWindows: 1 }
    const api = {
      ...happyApi(),
      getDocTask: vi.fn(async () =>
        docTask({ state: 'done', progress: { stepsDone: 2, stepsTotal: 2 }, resultRef: { documentId: 'gen1' }, gaps })
      )
    }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().state).toBe('done'), { timeout: hangBudgetMs(5000) })
    expect(getFileTranslate().gaps).toEqual(gaps)
  }, testBudgetMs(8000))

  it('the window label EXCLUDES the materialize step on a fresh start (a 2-window doc shows 1/2, not 1/3) — F-8', async () => {
    // The doc-task's stepsTotal counts the model windows PLUS the final materialize step
    // (`planTranslationBlocks`: windows + 1). The Translate view speaks in WINDOWS, so a 2-window
    // document (stepsTotal 3) at window 1 must read "(1/2)", never "(1/3)". Display-only.
    const api = {
      ...happyApi(),
      getDocTask: vi.fn(async () => docTask({ state: 'running', progress: { stepsDone: 1, stepsTotal: 3 } }))
    }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().windowsTotal).toBe(2), { timeout: hangBudgetMs(5000) })
    const snap = getFileTranslate()
    expect(snap.state).toBe('translating')
    expect(snap.windowsDone).toBe(1) // window 1 of 2 — the materialize step is not counted
    expect(snap.windowsTotal).toBe(2)
  }, testBudgetMs(8000))
})

describe('fileTranslateSession — reject + guard paths', () => {
  it('rejects a multi-file drop without importing', async () => {
    const api = happyApi()
    stubApi(api)
    await translateDroppedFiles(
      [new File(['a'], 'a.pdf'), new File(['b'], 'b.pdf')],
      CHOICE
    )
    expect(getFileTranslate().error).toBe('multiDrop')
    expect(api.importDocuments).not.toHaveBeenCalled()
  })

  it('rejects a drop with no on-disk path (a browser-origin drag)', async () => {
    const api = { ...happyApi(), getDroppedFilePath: vi.fn(() => '') }
    stubApi(api)
    await translateDroppedFiles([new File(['x'], 'a.pdf')], CHOICE)
    expect(getFileTranslate().error).toBe('noPath')
    expect(api.importDocuments).not.toHaveBeenCalled()
  })

  it('surfaces an unsupported file (nothing imported) as a friendly error', async () => {
    const api = { ...happyApi(), importDocuments: vi.fn(async () => ({ jobId: 'imp1', documentIds: [] })) }
    stubApi(api)
    await translateDroppedFiles([new File(['x'], 'a.xyz')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().error).toBe('unsupported'), { timeout: hangBudgetMs(5000) })
    expect(api.startDocTask).not.toHaveBeenCalled()
  }, testBudgetMs(8000))

  it('refuses while a foreign document task holds the lane (D9)', async () => {
    // Populate the GLOBAL doc-task store so getActiveDocTask() is non-null.
    const globalApi = {
      startDocTask: vi.fn(async () => ({ jobId: 'foreign' })),
      getDocTask: vi.fn(async () => docTask({ jobId: 'foreign' }))
    }
    stubApi(globalApi)
    await startTask('summary', 'doc9')

    const api = happyApi()
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    expect(getFileTranslate().error).toBe('docTaskBusy')
    expect(api.importDocuments).not.toHaveBeenCalled()
  })

  // #162 (FE-2), #682: the store's own same-language defense — the screen guards first, so only a call
  // that slips past it lands here. It runs BEFORE the start guard: with a foreign task on the lane (the
  // guard would fail docTaskBusy), a same-language pair still reads, imports and raises nothing.
  const SAME = { sourceLang: 'de', targetLang: 'de' } as const
  it.each([
    { entry: 'a drop', run: () => translateDroppedFiles([new File(['%PDF'], 'a.pdf')], SAME) },
    { entry: 'a pick', run: () => translatePickedFile(SAME) }
  ])('#162 (FE-2): $entry with the same language on both ends is a noop that imports nothing', async ({ run }) => {
    const api = {
      ...happyApi(),
      startDocTask: vi.fn(async () => ({ jobId: 'foreign' })),
      getDocTask: vi.fn(async () => docTask({ jobId: 'foreign', kind: 'summary' }))
    }
    stubApi(api)
    await startTask('summary', 'doc9')

    expect(await run()).toBe('noop')
    const snap = getFileTranslate()
    expect(snap.state).toBe('idle')
    expect(snap.error).toBeNull() // not docTaskBusy: the language check came first
    expect(api.getDroppedFilePath).not.toHaveBeenCalled()
    expect(api.pickDocuments).not.toHaveBeenCalled()
    expect(api.importDocuments).not.toHaveBeenCalled()
  })

  it('busy-rejects a second document translation while one runs', async () => {
    const api = happyApi()
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    // The first is now importing/translating (busy). A second returns 'busy' immediately.
    const second = await translateDroppedFiles([new File(['%PDF'], 'b.pdf')], CHOICE)
    expect(second).toBe('busy')
  }, testBudgetMs(8000))

  it('does NOT block on a TERMINAL foreign doc task lingering in the global store (C4)', async () => {
    // Seed the GLOBAL store with a DONE (terminal) foreign task — it must NOT refuse a translation.
    const globalApi = {
      startDocTask: vi.fn(async () => ({ jobId: 'foreign' })),
      getDocTask: vi.fn(async () =>
        docTask({ jobId: 'foreign', state: 'done', progress: { stepsDone: 1, stepsTotal: 1 }, resultRef: { documentId: 'x' } })
      )
    }
    stubApi(globalApi)
    await startTask('summary', 'doc9')
    await vi.waitFor(() => expect(isDocTaskTerminal(getActiveDocTask()?.status ?? null)).toBe(true), { timeout: hangBudgetMs(3000) })

    const api = happyApi()
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    // Proceeds to import (not blocked with docTaskBusy).
    await vi.waitFor(() => expect(api.importDocuments).toHaveBeenCalled(), { timeout: hangBudgetMs(3000) })
    expect(getFileTranslate().error).not.toBe('docTaskBusy')
  }, testBudgetMs(8000))

  it('cancels the orphan backend task when Stop lands during the startDocTask round-trip (C2/C3)', async () => {
    // Hold startDocTask pending so we can Stop while state is still 'importing'.
    let resolveStart: (v: { jobId: string }) => void = () => {}
    const startDocTask = vi.fn(() => new Promise<{ jobId: string }>((r) => { resolveStart = r }))
    const cancelDocTask = vi.fn(async () => {})
    const api = { ...happyApi(), startDocTask, cancelDocTask }
    stubApi(api)

    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(startDocTask).toHaveBeenCalled(), { timeout: hangBudgetMs(5000) })
    // The start round-trip is in flight; the panel is still 'importing' (translating is set AFTER).
    expect(getFileTranslate().state).toBe('importing')

    // User hits Stop in that window — the store must cancel the orphan once it materializes.
    cancelFileTranslation()
    expect(getFileTranslate().state).toBe('cancelled')
    resolveStart({ jobId: 'task1' })
    await vi.waitFor(() => expect(cancelDocTask).toHaveBeenCalledWith('task1'), { timeout: hangBudgetMs(5000) })
  }, testBudgetMs(8000))
})

describe('fileTranslateSession — lifecycle', () => {
  it('cancel + reset return the panel to idle', async () => {
    const api = happyApi()
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    cancelFileTranslation()
    expect(getFileTranslate().state).toBe('cancelled')
    expect(getFileTranslate().busy).toBe(false)
    resetFileTranslation()
    expect(getFileTranslate().state).toBe('idle')
  })

  it('clear drops all resident state on workspace lock', async () => {
    const api = happyApi()
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().state).toBe('done'), { timeout: hangBudgetMs(5000) })
    clearFileTranslate()
    const snap = getFileTranslate()
    expect(snap.state).toBe('idle')
    expect(snap.output).toBe('')
    expect(snap.resultDocumentId).toBe(null)
  }, testBudgetMs(8000))
})

// ---- TA-3 hardening: H4 poll latch, M8 post-picker guard, doc-task terminal + failure edges ----

describe('fileTranslateSession — H4 per-timer poll latch', () => {
  it('does not double-fire startDocTask when a stale generation callback releases the poll latch', async () => {
    // Regression for H4: with a MODULE-level latch reset by stopPolling(), a stale generation's slow
    // import round-trip resolving after Stop + re-drop would free the NEW generation's in-flight
    // latch (its `finally { pollInFlight = false }` runs on the stale early-return), letting two
    // ticks fire concurrently → a double startDocTask (a zombie backend task on the one-at-a-time
    // lane). The per-timer latch keeps each generation's reentrancy guard private. Fake timers drive
    // the poll; deferred getImportJob calls model the slow round-trips.
    vi.useFakeTimers()
    try {
      const makeDeferred = (): { promise: Promise<ImportJobStatus>; resolve: (v: ImportJobStatus) => void } => {
        let resolve: (v: ImportJobStatus) => void = () => {}
        const promise = new Promise<ImportJobStatus>((r) => (resolve = r))
        return { promise, resolve }
      }
      const importCalls: Array<{ promise: Promise<ImportJobStatus>; resolve: (v: ImportJobStatus) => void }> = []
      const DONE = { jobId: 'imp1', total: 1, completed: 1, failed: 0, done: true }
      const api = {
        getDroppedFilePath: vi.fn(() => 'C:\\docs\\a.pdf'),
        importDocuments: vi.fn(async () => ({ jobId: 'imp1', documentIds: ['d1'] })),
        getImportJob: vi.fn(() => {
          const d = makeDeferred()
          importCalls.push(d)
          return d.promise
        }),
        startDocTask: vi.fn(async () => ({ jobId: 'task1' })),
        getDocTask: vi.fn(async () => docTask({ progress: { stepsDone: 0, stepsTotal: 1 } })),
        cancelDocTask: vi.fn(async () => {})
      }
      stubApi(api)

      // gen A: drop → import resolves → import poll timer installed.
      await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
      // gen A's first import tick fires and awaits a SLOW getImportJob (call #0, unresolved).
      await vi.advanceTimersByTimeAsync(400)
      expect(importCalls).toHaveLength(1)

      // Stop supersedes gen A (clears its timer; its tick's IPC is still in flight). A new drop
      // starts gen B with its OWN import timer.
      cancelFileTranslation()
      await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
      // gen B's first import tick fires and awaits its own SLOW getImportJob (call #1, unresolved).
      await vi.advanceTimersByTimeAsync(400)
      expect(importCalls).toHaveLength(2)

      // The STALE gen-A round-trip resolves. With a shared latch its `finally` would free gen B's
      // in-flight latch; the per-timer latch keeps gen B's tick reentrancy-guarded.
      importCalls[0].resolve(DONE)
      await Promise.resolve()
      await Promise.resolve()
      // A further tick would, under the bug, fire a SECOND concurrent gen-B import round-trip.
      await vi.advanceTimersByTimeAsync(400)

      // Resolve every outstanding import round-trip as done; under the bug BOTH gen-B ticks reach
      // startTranslationTask (two startDocTask calls). With the fix exactly one does.
      for (const d of importCalls) d.resolve(DONE)
      await vi.advanceTimersByTimeAsync(400)
      await vi.advanceTimersByTimeAsync(400)

      expect(api.startDocTask).toHaveBeenCalledTimes(1)
    } finally {
      vi.useRealTimers()
    }
  })
})

describe('fileTranslateSession — M8 post-picker guard', () => {
  it('re-checks the start guard after the picker await; a text job that starts meanwhile makes it bail busy without touching the text session', async () => {
    let resolvePick: (v: { token: string; paths: string[] }) => void = () => {}
    const pickP = new Promise<{ token: string; paths: string[] }>((r) => (resolvePick = r))
    const api = {
      ...happyApi(),
      pickDocuments: vi.fn(() => pickP),
      translateStart: vi.fn(async () => translateJob()),
      translateCancel: vi.fn(async () => translateJob()),
      onTranslateToken: vi.fn(() => () => {}),
      onTranslateDone: vi.fn(() => () => {}),
      onTranslateError: vi.fn(() => () => {})
    }
    stubApi(api)

    // Start the picker path — guardStart passes (nothing busy), then it awaits the OS dialog.
    const pickPromise = translatePickedFile(CHOICE)
    // While the dialog is open, a TEXT translation starts (the non-modal-dialog race).
    await translate({ sourceLang: 'de', targetLang: 'en', text: 'Hallo' })
    expect(getTranslateSession().translating).toBe(true)
    expect(getTranslateSession().activeJobId).toBe('t1')

    // The dialog now returns a file. The re-check must see the text job and bail busy.
    resolvePick({ token: 'tok1', paths: ['C:\\docs\\a.pdf'] })
    const outcome = await pickPromise
    expect(outcome).toBe('busy')
    // The text session is UNTOUCHED (never cleared): it still holds its job, still translating.
    expect(getTranslateSession().activeJobId).toBe('t1')
    expect(getTranslateSession().translating).toBe(true)
    expect(api.importDocuments).not.toHaveBeenCalled()
  })
})

describe('fileTranslateSession — doc-task terminal + failure edges', () => {
  it('surfaces a failed doc-task with the backend error message (failWith)', async () => {
    const api = { ...happyApi(), getDocTask: vi.fn(async () => docTask({ state: 'failed', error: 'Kaputt' })) }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().state).toBe('failed'), { timeout: hangBudgetMs(5000) })
    expect(getFileTranslate().errorMessage).toBe('Kaputt')
    expect(getFileTranslate().busy).toBe(false)
  }, testBudgetMs(8000))

  it('a failed doc-task with no error message falls back to the runtimeFailed code', async () => {
    const api = { ...happyApi(), getDocTask: vi.fn(async () => docTask({ state: 'failed' })) }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().state).toBe('failed'), { timeout: hangBudgetMs(5000) })
    expect(getFileTranslate().error).toBe('runtimeFailed')
  }, testBudgetMs(8000))

  it('a cancelled doc-task settles the panel to cancelled', async () => {
    const api = { ...happyApi(), getDocTask: vi.fn(async () => docTask({ state: 'cancelled' })) }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().state).toBe('cancelled'), { timeout: hangBudgetMs(5000) })
    expect(getFileTranslate().busy).toBe(false)
  }, testBudgetMs(8000))

  it('a previewDocument failure surfaces as a friendly error (not a blank done panel)', async () => {
    const api = {
      ...happyApi(),
      previewDocument: vi.fn(async () => {
        throw new Error('locked')
      })
    }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().state).toBe('failed'), { timeout: hangBudgetMs(5000) })
    expect(getFileTranslate().errorMessage).toBeTruthy()
  }, testBudgetMs(8000))

  // FE-3 (ocr-audit 2026-07-18): imported-but-nothing-ingested no longer collapses to
  // 'unsupported' (the file IS a supported type) — the session reads the failed row's reason
  // via listDocuments; with the failed row unreadable (the list read throws) it lands the generic
  // import-failed frame. The scanned/real-message branches are covered in TranslateScreen tests.
  it('an import that ingests nothing (completed === 0) fails as importFailed when the row is unreadable', async () => {
    const api = {
      ...happyApi(),
      getImportJob: vi.fn(async () => ({ jobId: 'imp1', total: 1, completed: 0, failed: 1, done: true })),
      listDocuments: vi.fn(async () => {
        throw new Error('locked')
      })
    }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().error).toBe('importFailed'), { timeout: hangBudgetMs(5000) })
    expect(api.startDocTask).not.toHaveBeenCalled()
  }, testBudgetMs(8000))
})

// ---- FA-3 / F-3: reload adoption of a still-running document translation ----

describe('fileTranslateSession — adoptActiveFileTranslation (reload recovery)', () => {
  it('adopts a RUNNING translation doc-task, seeds progress with a null fileName, polls to done + loads the result', async () => {
    let polls = 0
    const api = {
      // A full reload lost the module store; main still has a running translation doc-task.
      listActiveDocTasks: vi.fn(async () => [
        docTask({ jobId: 'task1', state: 'running', progress: { stepsDone: 2, stepsTotal: 5 } })
      ]),
      getDocTask: vi.fn(async () => {
        polls += 1
        return polls === 1
          ? docTask({ jobId: 'task1', progress: { stepsDone: 3, stepsTotal: 5 } })
          : docTask({
              jobId: 'task1',
              state: 'done',
              progress: { stepsDone: 5, stepsTotal: 5 },
              resultRef: { documentId: 'gen1' }
            })
      }),
      previewDocument: vi.fn(async () => ({
        id: 'gen1',
        title: 'a (English)',
        mimeType: 'text/markdown',
        segments: [{ text: 'Adopted translation.', pageNumber: null, sectionLabel: null }],
        nextOffset: null
      }))
    }
    stubApi(api)
    // The reload killed the module-level GLOBAL doc-task store too, so nothing there claims this
    // task — that emptiness is exactly what marks the task as ours to re-adopt (see the foreign-task
    // case below). This is the whole point of the function: it MUST still adopt here.
    expect(getActiveDocTask()).toBe(null)

    await adoptActiveFileTranslation()
    // Seeds immediately from the doc-task status: translating, its progress, fileName tolerated null.
    const seeded = getFileTranslate()
    expect(seeded.state).toBe('translating')
    expect(seeded.busy).toBe(true)
    expect(seeded.fileName).toBe(null)
    // F-8: the doc-task's stepsTotal (5) counts the windows PLUS the materialize step; the label
    // speaks in WINDOWS, so the materialize step is subtracted for display (→ 4) on the adopt path too.
    expect(seeded.windowsDone).toBe(2)
    expect(seeded.windowsTotal).toBe(4)

    await vi.waitFor(() => expect(getFileTranslate().state).toBe('done'), { timeout: hangBudgetMs(5000) })
    const snap = getFileTranslate()
    expect(snap.output).toBe('Adopted translation.')
    expect(snap.resultDocumentId).toBe('gen1')
    expect(snap.busy).toBe(false)
  }, testBudgetMs(8000))

  it('is a no-op when NO doc-task is active', async () => {
    const api = { listActiveDocTasks: vi.fn(async () => []), getDocTask: vi.fn(async () => docTask()) }
    stubApi(api)
    await adoptActiveFileTranslation()
    expect(getFileTranslate().state).toBe('idle')
    expect(api.getDocTask).not.toHaveBeenCalled()
  })

  it('is a no-op when the active doc-task is NOT a translation (e.g. a summary)', async () => {
    const api = {
      listActiveDocTasks: vi.fn(async () => [docTask({ kind: 'summary', state: 'running' })]),
      getDocTask: vi.fn(async () => docTask())
    }
    stubApi(api)
    await adoptActiveFileTranslation()
    expect(getFileTranslate().state).toBe('idle')
    expect(api.getDocTask).not.toHaveBeenCalled()
  })

  it('#157 (DT-5): adopts a translation QUEUED behind a foreign running task (DOC-8 teeth)', async () => {
    // The exact DT-5 shape: a foreign summary RUNS, our translation sits QUEUED behind it.
    // getActiveDocTask could only ever report the running task, so this adopt was dead code;
    // the lane list carries both and the adopt picks the translation.
    const api = {
      listActiveDocTasks: vi.fn(async () => [
        docTask({ jobId: 'foreignSum', kind: 'summary', state: 'running', progress: { stepsDone: 1, stepsTotal: 3 } }),
        docTask({ jobId: 'ourTr', state: 'queued', progress: { stepsDone: 0, stepsTotal: 0 } })
      ]),
      getDocTask: vi.fn(async () => docTask({ jobId: 'ourTr', state: 'queued', progress: { stepsDone: 0, stepsTotal: 0 } })),
      cancelDocTask: vi.fn(async () => {})
    }
    stubApi(api)
    await adoptActiveFileTranslation()
    const seeded = getFileTranslate()
    expect(seeded.state).toBe('translating')
    expect(seeded.busy).toBe(true)
    // Stop targets OUR queued task's id (exact-id since DT-2), never the foreign running one.
    cancelFileTranslation()
    expect(api.cancelDocTask).toHaveBeenCalledWith('ourTr')
    expect(getFileTranslate().state).toBe('cancelled')
  })

  it('yields to a live TEXT job (precedence — the two adopts never both claim the panel)', async () => {
    // A text job is streaming (translateSession busy); the file adopt must not seed even if main
    // reported a running doc-task (it cannot in practice — the D9 lane — but precedence is enforced).
    const textApi = {
      translateStart: vi.fn(async () => translateJob()),
      onTranslateToken: vi.fn(() => () => {}),
      onTranslateDone: vi.fn(() => () => {}),
      onTranslateError: vi.fn(() => () => {})
    }
    stubApi(textApi)
    await translate({ sourceLang: 'de', targetLang: 'en', text: 'Hallo' })
    expect(getTranslateSession().translating).toBe(true)

    const fileApi = {
      listActiveDocTasks: vi.fn(async () => [docTask({ jobId: 'task1', state: 'running' })]),
      getDocTask: vi.fn(async () => docTask())
    }
    stubApi(fileApi)
    await adoptActiveFileTranslation()
    expect(getFileTranslate().state).toBe('idle')
    expect(fileApi.listActiveDocTasks).not.toHaveBeenCalled()
  })

  // ---- AUD-04: the adopt runs on EVERY Translate mount, not only after a reload ----

  it('AUD-04: does NOT wipe a COMPLETED translation result when the panel is re-entered', async () => {
    // `busy` is false in every terminal state, so a busy-only guard let a plain navigate-back run
    // the adopt straight over a FINISHED translation: the held output/gaps/truncated/result id were
    // replaced with an empty `translating` frame. Drive a real translation to done first, with all
    // four result fields populated, so the assertions name exactly what was being destroyed.
    const gaps = { missingPageRanges: [{ from: 3, to: 3 }], failedWindows: 1 }
    const api = {
      ...happyApi(),
      getDocTask: vi.fn(async () =>
        docTask({
          state: 'done',
          progress: { stepsDone: 2, stepsTotal: 2 },
          resultRef: { documentId: 'gen1' },
          gaps
        })
      ),
      previewDocument: vi.fn(async () => ({
        id: 'gen1',
        title: 'a (English)',
        mimeType: 'text/markdown',
        segments: [{ text: 'Finished translation.', pageNumber: null, sectionLabel: null }],
        nextOffset: 400 // a long document: only the start is in the panel
      }))
    }
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.waitFor(() => expect(getFileTranslate().state).toBe('done'), { timeout: hangBudgetMs(5000) })
    const settled = getFileTranslate()

    // The user goes elsewhere, a translation doc-task is running again, and they come back: the
    // mount effect re-runs the adopt while this store still shows the finished result.
    const adoptApi = {
      listActiveDocTasks: vi.fn(async () => [
        docTask({ jobId: 'other', state: 'running', progress: { stepsDone: 1, stepsTotal: 4 } })
      ]),
      getDocTask: vi.fn(async () => docTask({ jobId: 'other' }))
    }
    stubApi(adoptApi)
    await adoptActiveFileTranslation()

    const snap = getFileTranslate()
    expect(snap.state).toBe('done')
    expect(snap.output).toBe('Finished translation.')
    expect(snap.resultDocumentId).toBe('gen1')
    expect(snap.truncated).toBe(true)
    expect(snap.gaps).toEqual(gaps)
    expect(snap.fileName).toBe('a.pdf')
    expect(snap.busy).toBe(false)
    // Nothing was written at all (same snapshot object) and no poll was installed over the result.
    expect(snap).toBe(settled)
    expect(adoptApi.getDocTask).not.toHaveBeenCalled()
  }, testBudgetMs(8000))

  it('AUD-04: does NOT pull in a FOREIGN translation task another screen started', async () => {
    // A Documents-row "Translate" runs through the GLOBAL doc-task store; this store never registers
    // its own task there, so a live entry is by definition someone else's — and the backend's
    // one-at-a-time lane means main reports that same task as the active one. Merely navigating to
    // the Translate screen must not claim it: adopting would put a stranger's task in the panel,
    // point Stop at it, and load its output here as if it were a file translation.
    const globalApi = {
      startDocTask: vi.fn(async () => ({ jobId: 'foreign' })),
      getDocTask: vi.fn(async () =>
        docTask({ jobId: 'foreign', state: 'running', progress: { stepsDone: 1, stepsTotal: 4 } })
      )
    }
    stubApi(globalApi)
    await startTask('translation', 'doc9', { sourceLang: 'de', targetLang: 'en' })
    expect(getActiveDocTask()?.jobId).toBe('foreign')

    const idle = getFileTranslate()
    const api = {
      listActiveDocTasks: vi.fn(async () => [
        docTask({ jobId: 'foreign', state: 'running', progress: { stepsDone: 1, stepsTotal: 4 } })
      ]),
      getDocTask: vi.fn(async () => docTask({ jobId: 'foreign' }))
    }
    stubApi(api)
    await adoptActiveFileTranslation()

    const snap = getFileTranslate()
    expect(snap.state).toBe('idle')
    expect(snap.busy).toBe(false)
    expect(snap.windowsTotal).toBe(0)
    expect(snap).toBe(idle) // untouched — the store was never written
  }, testBudgetMs(8000))

  it('AUD-04: bails when a rejected drop turned the panel TERMINAL while the active-task read was in flight', async () => {
    // The post-await re-check follows the same `idle` rule as the entry guard: a drop rejected
    // SYNCHRONOUSLY (multi-file here; a browser-origin drag with no path and a busy lane behave the
    // same) lands `failed` with a banner the user just triggered, and `busy` is false there too — a
    // busy-only re-check would replace that banner with "Translating…".
    let resolveActive: (v: DocTaskStatus[]) => void = () => {}
    const activeP = new Promise<DocTaskStatus[]>((r) => (resolveActive = r))
    const api = {
      ...happyApi(),
      listActiveDocTasks: vi.fn(() => activeP),
      getDocTask: vi.fn(async () => docTask({ jobId: 'task1' }))
    }
    stubApi(api)

    // Mount adopt starts; it is parked on the active-task read.
    const adoptPromise = adoptActiveFileTranslation()
    expect(api.listActiveDocTasks).toHaveBeenCalledTimes(1) // the adopt calls it before its first await

    // The user drops two files in that window — rejected on the spot, panel goes terminal.
    await translateDroppedFiles([new File(['a'], 'a.pdf'), new File(['b'], 'b.pdf')], CHOICE)
    expect(getFileTranslate().state).toBe('failed')
    expect(getFileTranslate().error).toBe('multiDrop')
    const rejected = getFileTranslate()

    resolveActive([docTask({ jobId: 'task1', state: 'running', progress: { stepsDone: 1, stepsTotal: 4 } })])
    await adoptPromise

    expect(getFileTranslate().state).toBe('failed')
    expect(getFileTranslate().error).toBe('multiDrop')
    expect(getFileTranslate()).toBe(rejected)
    expect(api.getDocTask).not.toHaveBeenCalled()
  }, testBudgetMs(8000))
})

// ---- The adopt's await window must be guarded by the GENERATION, not by the `idle` state alone ----
//
// `state === 'idle'` answers "is anything on screen right now?", which is the wrong question for
// work that happened DURING the active-task read. Both paths that INVALIDATE this store while
// leaving it idle — the workspace-lock purge, and a Stop the user then dismissed — land exactly the
// shape the idle rule admits, so an idle-only re-check re-seeds `translating` and resumes polling a
// task main has already aborted. Only a generation token captured BEFORE the await, and re-checked
// after it, tells a genuinely-reloaded store apart from one that was just invalidated.

describe('fileTranslateSession — the adopt must not re-seed a session that was invalidated mid-read', () => {
  it('bails when a workspace LOCK purged the store while the active-task read was in flight', async () => {
    // `App.lockNow` purges every session store AFTER main aborted the doc-task and re-encrypted the
    // vault. `clearFileTranslate()` resets this store to EMPTY — i.e. `idle` — so an idle-only guard
    // reads the freshly-purged store as "safe to adopt" and puts the panel back into `translating`
    // with a poll running against a dead task, ending in a materialized preview loaded into renderer
    // memory behind the lock screen.
    let resolveActive: (v: DocTaskStatus[]) => void = () => {}
    const activeP = new Promise<DocTaskStatus[]>((r) => (resolveActive = r))
    const api = {
      listActiveDocTasks: vi.fn(() => activeP),
      getDocTask: vi.fn(async () => docTask({ jobId: 'task1' })),
      previewDocument: vi.fn(async () => ({
        id: 'gen1',
        title: 'a (English)',
        mimeType: 'text/markdown',
        segments: [{ text: 'Vertraulich.', pageNumber: null, sectionLabel: null }],
        nextOffset: null
      }))
    }
    stubApi(api)

    // The mount adopt is parked on the active-task read.
    const adoptPromise = adoptActiveFileTranslation()
    expect(api.listActiveDocTasks).toHaveBeenCalledTimes(1) // the adopt calls it before its first await

    clearFileTranslate() // the workspace locks in that window (the renderer lock seam)
    const purged = getFileTranslate()

    resolveActive([docTask({ jobId: 'task1', state: 'running', progress: { stepsDone: 1, stepsTotal: 4 } })])
    await adoptPromise

    const snap = getFileTranslate()
    expect(snap.state).toBe('idle') // not flipped back to 'translating' behind the lock
    expect(snap.busy).toBe(false)
    expect(snap.windowsDone).toBe(0)
    expect(snap.windowsTotal).toBe(0)
    // Nothing was written at all (same snapshot object) — and since the poll is only installed after
    // that write, no poll can be running against the aborted task either.
    expect(snap).toBe(purged)
    expect(api.getDocTask).not.toHaveBeenCalled()
  }, testBudgetMs(8000))

  it('bails when the user STOPPED the document translation and dismissed it while the read was in flight', async () => {
    // Stop alone leaves `cancelled` (which the idle rule already refuses), but the "Translate another
    // document" dismiss right after it returns the panel to `idle` — the same shape as the lock
    // purge. Both bump the generation, which is what makes the parked adopt detectable as stale.
    let resolveActive: (v: DocTaskStatus[]) => void = () => {}
    const activeP = new Promise<DocTaskStatus[]>((r) => (resolveActive = r))
    const api = {
      ...happyApi(),
      listActiveDocTasks: vi.fn(() => activeP),
      getDocTask: vi.fn(async () => docTask({ jobId: 'task1' })),
      cancelDocTask: vi.fn(async () => {})
    }
    stubApi(api)

    const adoptPromise = adoptActiveFileTranslation()
    expect(api.listActiveDocTasks).toHaveBeenCalledTimes(1) // the adopt calls it before its first await

    // The user drops a document, stops it, then dismisses the cancelled panel — all while the
    // active-task read is still parked.
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    cancelFileTranslation()
    expect(getFileTranslate().state).toBe('cancelled')
    resetFileTranslation()
    const dismissed = getFileTranslate()
    expect(dismissed.state).toBe('idle')

    resolveActive([docTask({ jobId: 'task1', state: 'running', progress: { stepsDone: 1, stepsTotal: 4 } })])
    await adoptPromise

    expect(getFileTranslate()).toBe(dismissed) // the dismissed panel stayed dismissed
    expect(getFileTranslate().state).toBe('idle')
    expect(getFileTranslate().busy).toBe(false)
  }, testBudgetMs(8000))

  it('CONTROL: still adopts through a slow active-task read and polls to done', async () => {
    // The guard must not cost the case the adopt exists for. The earlier lock is deliberate: the
    // generation is a running counter, so the entry token has to be READ, never assumed to be zero —
    // and the poll must still run under a generation of its own afterwards.
    clearFileTranslate() // a previous lock already moved the generation on
    let resolveActive: (v: DocTaskStatus[]) => void = () => {}
    const activeP = new Promise<DocTaskStatus[]>((r) => (resolveActive = r))
    let polls = 0
    const api = {
      listActiveDocTasks: vi.fn(() => activeP),
      getDocTask: vi.fn(async () => {
        polls += 1
        return polls === 1
          ? docTask({ jobId: 'task1', progress: { stepsDone: 3, stepsTotal: 5 } })
          : docTask({
              jobId: 'task1',
              state: 'done',
              progress: { stepsDone: 5, stepsTotal: 5 },
              resultRef: { documentId: 'gen1' }
            })
      }),
      previewDocument: vi.fn(async () => ({
        id: 'gen1',
        title: 'a (English)',
        mimeType: 'text/markdown',
        segments: [{ text: 'Adopted translation.', pageNumber: null, sectionLabel: null }],
        nextOffset: null
      }))
    }
    stubApi(api)

    const adoptPromise = adoptActiveFileTranslation()
    expect(api.listActiveDocTasks).toHaveBeenCalledTimes(1) // the adopt calls it before its first await
    resolveActive([docTask({ jobId: 'task1', state: 'running', progress: { stepsDone: 2, stepsTotal: 5 } })])
    await adoptPromise

    const seeded = getFileTranslate()
    expect(seeded.state).toBe('translating')
    expect(seeded.busy).toBe(true)
    expect(seeded.windowsDone).toBe(2)
    expect(seeded.windowsTotal).toBe(4) // the materialize step is not a window

    await vi.waitFor(() => expect(getFileTranslate().state).toBe('done'), { timeout: hangBudgetMs(5000) })
    expect(getFileTranslate().output).toBe('Adopted translation.')
    expect(getFileTranslate().resultDocumentId).toBe('gen1')
  }, testBudgetMs(8000))

  it('CONTROL: the adopted poll runs under its OWN generation — a later Stop still kills it', async () => {
    // The entry token must not REPLACE the polling generation: `pollDocTask` still has to run under a
    // generation a later Stop/clear moves past, or Stop would leave the loop writing progress over a
    // cancelled panel. Fake timers drive the poll so this needs no sleeps.
    vi.useFakeTimers()
    try {
      const api = {
        listActiveDocTasks: vi.fn(async () => [
          docTask({ jobId: 'task1', state: 'running', progress: { stepsDone: 1, stepsTotal: 4 } })
        ]),
        getDocTask: vi.fn(async () => docTask({ jobId: 'task1', progress: { stepsDone: 2, stepsTotal: 4 } })),
        cancelDocTask: vi.fn(async () => {})
      }
      stubApi(api)

      await adoptActiveFileTranslation()
      expect(getFileTranslate().state).toBe('translating')
      expect(getFileTranslate().windowsDone).toBe(1) // seeded from the active-task read

      await vi.advanceTimersByTimeAsync(400)
      expect(api.getDocTask).toHaveBeenCalledTimes(1) // the adopted poll is live
      expect(getFileTranslate().windowsDone).toBe(2) // and writing progress under its generation

      cancelFileTranslation()
      expect(getFileTranslate().state).toBe('cancelled')
      expect(api.cancelDocTask).toHaveBeenCalledWith('task1') // the adopted task id was held for Stop
      const stopped = getFileTranslate()

      await vi.advanceTimersByTimeAsync(1200) // three more poll intervals
      expect(api.getDocTask).toHaveBeenCalledTimes(1) // the loop really stopped
      expect(getFileTranslate()).toBe(stopped) // nothing written over the cancelled panel
    } finally {
      vi.useRealTimers()
    }
  }, testBudgetMs(8000))
})

// ---- #157 (DT-4): consecutive-poll-failure tolerance (the doctasks-store CODE-6 rule, ported) ----
//
// One rejected round-trip used to fail the panel outright while the main-side task kept decoding
// (and later materialized a document behind a "failed" panel; a retry then queued behind it —
// re-entering the DT-2 shape). The store now tolerates MAX_POLL_FAILURES-1 consecutive failures,
// resets the counter on any success, and on give-up ALSO cancels the backend task (exact-id).

describe('fileTranslateSession — poll-failure tolerance (#157 / DT-4)', () => {
  /** Drive a drop through import → startDocTask so the doc-task poll is installed. */
  async function driveToTranslating(api: Partial<PreloadApi>): Promise<void> {
    stubApi(api)
    await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
    await vi.advanceTimersByTimeAsync(400) // import poll tick → done → startDocTask resolves
    expect(getFileTranslate().state).toBe('translating')
  }

  it('tolerates two consecutive failed doc-task polls; the third fails the session AND cancels the task', async () => {
    vi.useFakeTimers()
    try {
      const api = {
        ...happyApi(),
        getDocTask: vi.fn(async () => {
          throw new Error('ipc broke')
        }),
        cancelDocTask: vi.fn(async () => {})
      }
      await driveToTranslating(api)

      await vi.advanceTimersByTimeAsync(400) // failure 1 — tolerated
      expect(getFileTranslate().state).toBe('translating')
      await vi.advanceTimersByTimeAsync(400) // failure 2 — tolerated
      expect(getFileTranslate().state).toBe('translating')
      await vi.advanceTimersByTimeAsync(400) // failure 3 — give up honestly
      expect(getFileTranslate().state).toBe('failed')
      expect(getFileTranslate().errorMessage).toBe('ipc broke')
      // Give-up also cancels the backend task (exact-id): the renderer's terminal state and the
      // backend agree — no invisible decode materializing a document behind a "failed" panel.
      expect(api.cancelDocTask).toHaveBeenCalledWith('task1')

      await vi.advanceTimersByTimeAsync(1200)
      expect(api.getDocTask).toHaveBeenCalledTimes(3) // polling really stopped
    } finally {
      vi.useRealTimers()
    }
  })

  it('any successful poll RESETS the counter: interleaved transients never fail a healthy run', async () => {
    vi.useFakeTimers()
    try {
      let calls = 0
      const api = {
        ...happyApi(),
        // throw, throw, success(reset), throw, throw, done — with the reset this never reaches
        // three CONSECUTIVE failures; without it the fifth call would wrongly fail the session.
        getDocTask: vi.fn(async () => {
          calls += 1
          if (calls === 3) return docTask({ progress: { stepsDone: 1, stepsTotal: 3 } })
          if (calls <= 5) throw new Error('flaky')
          return docTask({ state: 'done', progress: { stepsDone: 3, stepsTotal: 3 }, resultRef: { documentId: 'gen1' } })
        }),
        cancelDocTask: vi.fn(async () => {})
      }
      await driveToTranslating(api)

      for (let i = 0; i < 6; i++) await vi.advanceTimersByTimeAsync(400)
      await vi.waitFor(() => expect(getFileTranslate().state).toBe('done'), { timeout: hangBudgetMs(5000) })
      expect(getFileTranslate().output).toBe('Hello world.')
      expect(api.cancelDocTask).not.toHaveBeenCalled()
    } finally {
      vi.useRealTimers()
    }
  })

  it('the IMPORT poll tolerates transients too, and gives up without a doc-task cancel (none exists yet)', async () => {
    vi.useFakeTimers()
    try {
      const api = {
        ...happyApi(),
        getImportJob: vi.fn(async () => {
          throw new Error('ipc broke')
        }),
        cancelDocTask: vi.fn(async () => {})
      }
      stubApi(api)
      await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)

      await vi.advanceTimersByTimeAsync(400)
      expect(getFileTranslate().state).toBe('importing') // failure 1 tolerated
      await vi.advanceTimersByTimeAsync(400)
      expect(getFileTranslate().state).toBe('importing') // failure 2 tolerated
      await vi.advanceTimersByTimeAsync(400)
      expect(getFileTranslate().state).toBe('failed') // failure 3 — honest give-up
      expect(getFileTranslate().errorMessage).toBe('ipc broke') // the friendly IPC message, not a code
      expect(api.startDocTask).not.toHaveBeenCalled()
      expect(api.cancelDocTask).not.toHaveBeenCalled()
    } finally {
      vi.useRealTimers()
    }
  })
})

// ---- #165 (P-2): unchanged poll ticks must not re-render the screen ----

describe('fileTranslateSession — poll-tick render churn (#165 / P-2)', () => {
  it('identical 400 ms doc-task polls keep the SAME snapshot object', async () => {
    vi.useFakeTimers()
    try {
      const api = {
        ...happyApi(),
        // The counts never move — the long-window steady state (a CPU window decodes ~30 min,
        // so ~4500 consecutive identical ticks per window in production).
        getDocTask: vi.fn(async () => docTask({ progress: { stepsDone: 1, stepsTotal: 3 } }))
      }
      stubApi(api)
      await translateDroppedFiles([new File(['%PDF'], 'a.pdf')], CHOICE)
      await vi.advanceTimersByTimeAsync(400) // import done → doc-task poll installed
      expect(getFileTranslate().state).toBe('translating')

      await vi.advanceTimersByTimeAsync(400) // first poll writes the progress
      const settled = getFileTranslate()
      expect(settled.windowsDone).toBe(1)
      await vi.advanceTimersByTimeAsync(400)
      await vi.advanceTimersByTimeAsync(400)
      // useSyncExternalStore subscribers re-render on snapshot identity — unchanged ticks
      // must return the very same object (pre-fix: a fresh spread + notify per tick).
      expect(getFileTranslate()).toBe(settled)
      expect(api.getDocTask.mock.calls.length).toBeGreaterThanOrEqual(3) // polling continued
    } finally {
      vi.useRealTimers()
    }
  })
})

// ---- #163 (T-8): picker edges — cancel, multi-pick, and a throwing dialog ----

describe('fileTranslateSession — picker edges (#163 / T-8)', () => {
  it('a cancelled OS dialog resolves noop and leaves the store untouched', async () => {
    const api = { ...happyApi(), pickDocuments: vi.fn(async () => ({ token: '', paths: [] as string[] })) }
    stubApi(api)
    expect(await translatePickedFile(CHOICE)).toBe('noop')
    expect(getFileTranslate().state).toBe('idle')
    expect(api.importDocuments).not.toHaveBeenCalled()
  })

  it('a multi-path pick is rejected multiDrop before any import', async () => {
    const api = {
      ...happyApi(),
      pickDocuments: vi.fn(async () => ({ token: 'tok1', paths: ['C:\\a.pdf', 'C:\\b.pdf'] }))
    }
    stubApi(api)
    expect(await translatePickedFile(CHOICE)).toBe('started')
    const snap = getFileTranslate()
    expect(snap.state).toBe('failed')
    expect(snap.error).toBe('multiDrop')
    expect(api.importDocuments).not.toHaveBeenCalled()
  })

  it('a THROWING pickDocuments fails importFailed (never an unhandled rejection)', async () => {
    const api = {
      ...happyApi(),
      pickDocuments: vi.fn(async () => {
        throw new Error('dialog exploded')
      })
    }
    stubApi(api)
    expect(await translatePickedFile(CHOICE)).toBe('started')
    const snap = getFileTranslate()
    expect(snap.state).toBe('failed')
    expect(snap.error).toBe('importFailed')
    expect(api.importDocuments).not.toHaveBeenCalled()
  })
})