Skip to content

AI, fully local on your computer.

42.4 KB
Raw Blame
// @vitest-environment jsdom
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import { render, screen, cleanup, waitFor, act, within, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { TranslateScreen } from '../../src/renderer/screens/TranslateScreen'
import { clearTranslateSession, setLastTranslateChoice } from '../../src/renderer/lib/translateSession'
import { clearFileTranslate } from '../../src/renderer/lib/fileTranslateSession'
import { clearDocTaskSession, getActiveDocTask, isDocTaskTerminal, startTask } from '../../src/renderer/lib/doctasks'
import { en, t } from '../../src/shared/i18n'
import { I18nProvider, UI_LANGUAGE_STORAGE_KEY } from '../../src/renderer/i18n'
import type { AppStatus, DocTaskStatus, DocumentInfo, TranslateJob } from '../../src/shared/types'
import { stubApi, assertNoUnexpectedApiCalls } from '../helpers/renderer'
import type { PreloadApi } from '../../src/preload'
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). The `appStatus`/`docTask` builders return the real shared types and
// the `streamStubs`/`fileStubs` `api` bags are structurally checked against `Partial<PreloadApi>`
// on the `stubApi(translateScreenStubs(...))` call, so a rename of any mocked method or return shape reddens typecheck.

// Renderer test (jsdom + RTL) for the Translate screen state machine (TranslateGemma plan §2 D6/D7,
// TG-4/5). The TEXT path is driven by capturing the onTranslate* subscriber callbacks and invoking
// them; the DOCUMENT path drives the import → doc-task → materialize polling with stubbed IPC.
// Both active translations live in module-level stores (survive navigation), reset between tests.

// The DOC-7 language-pair memory is module-level and no clear resets it (the lock purge keeps it by
// design), so without a seed every row would open on whatever pair the previous translating row left —
// a German-UI row that runs first records en → de, and the literal-pair rows below then fail (#682:
// `--sequence.shuffle` found such orders). Each row starts from de → en through the production writer.
// The UI-language defaults themselves are pinned in translateSession.test.ts on a fresh module.
beforeEach(() => setLastTranslateChoice('de', 'en'))

afterEach(() => {
  cleanup()
  // The production clears (lib/lockPurge.ts runs the same three).
  clearTranslateSession()
  clearFileTranslate()
  clearDocTaskSession()
  assertNoUnexpectedApiCalls()
})

/** What the screen reads at mount beside the rows' own stubs (#832): no document task running. `over` spreads last. */
function translateScreenStubs(over: Partial<PreloadApi>): Partial<PreloadApi> {
  return { listActiveDocTasks: vi.fn<PreloadApi['listActiveDocTasks']>(async () => []), ...over }
}

function appStatus(over: Partial<AppStatus> = {}): AppStatus {
  return {
    appName: 'x',
    appVersion: '0',
    offlineMode: true,
    networkAllowed: false,
    activeModelId: null,
    hardwareProfile: 'UNKNOWN',
    workspaceMode: 'plaintext_dev',
    workspaceReady: true,
    machineRamGb: 16,
    dictationAvailable: false,
    ocrAvailable: false,
    translationAvailable: true,
    ...over
  } as AppStatus
}

/** Stream-driving stubs: capture the subscriber callbacks so a test can push tokens/done/error. */
function streamStubs(startJob: TranslateJob = { jobId: 'j1', state: 'queued', text: '' }) {
  const token: { fn?: (t: string) => void } = {}
  const done: { fn?: (j: TranslateJob) => void } = {}
  const error: { fn?: (j: TranslateJob) => void } = {}
  const translateStart = vi.fn(async () => startJob)
  const translateCancel = vi.fn(async () => ({ jobId: 'j1', state: 'cancelled' }) as TranslateJob)
  const copyToClipboard = vi.fn(async () => true)
  return {
    token,
    done,
    error,
    translateStart,
    translateCancel,
    copyToClipboard,
    api: {
      getAppStatus: vi.fn(async () => appStatus()),
      getActiveTranslateJob: vi.fn(async () => null),
      translateStart,
      translateCancel,
      copyToClipboard,
      onTranslateToken: vi.fn((_id: string, cb: (t: string) => void) => {
        token.fn = cb
        return () => {}
      }),
      onTranslateDone: vi.fn((_id: string, cb: (j: TranslateJob) => void) => {
        done.fn = cb
        return () => {}
      }),
      onTranslateError: vi.fn((_id: string, cb: (j: TranslateJob) => void) => {
        error.fn = cb
        return () => {}
      })
    }
  }
}

describe('TranslateScreen — availability (O2 install path)', () => {
  it('shows the model-missing EmptyState and deep-links to AI Model', async () => {
    const onNavigate = vi.fn()
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () => appStatus({ translationAvailable: false })),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={onNavigate} />)

    expect(await screen.findByText(t('en', 'translate.avail.noModel'))).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: t('en', 'translate.avail.cta') }))
    // #539: on the translation model itself, not the screen's default view.
    expect(onNavigate).toHaveBeenCalledWith('models:translation')
  })
})

describe('TranslateScreen — device hint (issue #42 reopen)', () => {
  it('shows the full-offload GPU hint once the sidecar has started', async () => {
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () =>
        appStatus({ translationDevice: { device: 'auto', gpuLayers: 49, totalLayers: 49, live: true } })
      ),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    render(<TranslateScreen onNavigate={vi.fn()} />)
    expect(
      await screen.findByText(t('en', 'translate.device.gpu', { done: 49, total: 49 }))
    ).toBeInTheDocument()
  })

  // #42 (owner decision 2026-09-08, "no runtime change — fix the copy"): before this, the two
  // starved fact lines stated only the SYMPTOM ("about processor speed"), leaving a user who
  // reads no further with nothing to act on. The cause now rides the fact line in BOTH locales,
  // and the remedy line below it is the ACTION only — so neither can silently regress to
  // symptom-only, and the two lines cannot drift back into saying the same thing twice.
  describe('#42 — the starved device lines name the cause, not just the symptom', () => {
    // Assert on MEANING, not on the exact sentence: "chat model" is the cause the record
    // (`known-limitations.md`, "A large resident chat model can starve GPU translation…") names,
    // and the hedge is deliberate — a chat model is the usual cause, not the only one.
    const namesTheCause = (s: string, lang: 'en' | 'de'): boolean =>
      (lang === 'en' ? /chat model/i : /Chat-Modell/).test(s) &&
      (lang === 'en' ? /usually/i : /meist/).test(s)

    for (const lang of ['en', 'de'] as const) {
      it(`${lang}: the partial and none fact lines both name the chat model as the usual cause`, () => {
        const partial = t(lang, 'translate.device.gpuPartial', { done: 12, total: 49 })
        const none = t(lang, 'translate.device.gpuNone', { total: 49 })
        expect(namesTheCause(partial, lang), partial).toBe(true)
        expect(namesTheCause(none, lang), none).toBe(true)
        // The partial line still states the consequence too — the cause did not displace it.
        expect(partial).toMatch(lang === 'en' ? /processor speed/i : /Prozessor-Tempo/)
      })

      it(`${lang}: the remedy line is the ACTION, and no longer repeats the cause sentence`, () => {
        for (const key of ['translate.device.partialTitle', 'translate.device.gpuNoneTitle'] as const) {
          const remedy = t(lang, key)
          // It tells the user what to DO…
          expect(remedy, key).toMatch(lang === 'en' ? /smaller chat model/i : /kleineres Chat-Modell/)
          // …and does not restate the cause the fact line above now carries.
          expect(namesTheCause(remedy, lang), `${key} still restates the cause`).toBe(false)
        }
      })
    }
  })

  it('CODE-23: a fully-starved fit (0 layers) says processor, not "partly on the graphics card"', async () => {
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () =>
        appStatus({ translationDevice: { device: 'auto', gpuLayers: 0, totalLayers: 49, live: false } })
      ),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    render(<TranslateScreen onNavigate={vi.fn()} />)
    // Pre-fix this rendered the contradictory "runs only partly on the graphics card
    // (0/49 layers)" (full-audit 2026-07-11 CODE-23).
    const hint = await screen.findByText(t('en', 'translate.device.gpuNone', { total: 49 }))
    expect(hint).toHaveAttribute('title', t('en', 'translate.device.gpuNoneTitle'))
    expect(
      screen.queryByText(t('en', 'translate.device.gpuPartial', { done: 0, total: 49 }))
    ).not.toBeInTheDocument()
  })

  it('#163 (T-7): GPU posture with NO parseable offload line shows the gpuUnknown form', async () => {
    // The fallback branch — the one that renders exactly on machines where the offload parse
    // failed — was the only device-hint branch without a test.
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () =>
        appStatus({ translationDevice: { device: 'auto', gpuLayers: null, totalLayers: null, live: true } })
      ),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    render(<TranslateScreen onNavigate={vi.fn()} />)
    const hint = await screen.findByText(t('en', 'translate.device.gpuUnknown'))
    expect(hint).toHaveAttribute('title', t('en', 'translate.device.title'))
  })

  it('#161 (FE-4): the partial-offload cause/remedy is VISIBLE text, not tooltip-only', async () => {
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () =>
        appStatus({ translationDevice: { device: 'auto', gpuLayers: 12, totalLayers: 49, live: false } })
      ),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    render(<TranslateScreen onNavigate={vi.fn()} />)
    const hint = await screen.findByText(t('en', 'translate.device.gpuPartial', { done: 12, total: 49 }))
    expect(hint).toHaveAttribute('title', t('en', 'translate.device.partialTitle')) // the tooltip too, not only
    // The remedy ("a smaller chat model frees memory…") is reachable WITHOUT a pointer hover —
    // a title attribute on a non-focusable <p> is invisible to keyboard/touch/screen readers.
    expect(screen.getByText(t('en', 'translate.device.partialTitle'))).toBeInTheDocument()
  })

  it('a forced-CPU start shows the CPU form; no outcome yet shows NO hint', async () => {
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () =>
        appStatus({ translationDevice: { device: 'cpu', gpuLayers: null, totalLayers: null, live: true } })
      ),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    const { unmount } = render(<TranslateScreen onNavigate={vi.fn()} />)
    expect(await screen.findByText(t('en', 'translate.device.cpu'))).toBeInTheDocument()
    unmount()

    // Before the sidecar's first start (translationDevice null) the line is absent entirely.
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () => appStatus()),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    const { container } = render(<TranslateScreen onNavigate={vi.fn()} />)
    await screen.findByText(t('en', 'translate.action'))
    expect(container.querySelector('.translate-device-hint')).toBeNull()
  })

  // #671: on a PC with no usable graphics card the GPU posture starts on the processor, and the load
  // log still reads `offloaded 49/49 layers to GPU`; only the missing GPU buffers tell.
  it('#671: a GPU-posture start that put no buffer on a graphics device says processor, whatever its split', async () => {
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () =>
        appStatus({ translationDevice: { device: 'auto', gpuLayers: 49, totalLayers: 49, gpuBuffers: false, live: true } })
      ),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    render(<TranslateScreen onNavigate={vi.fn()} />)
    expect(await screen.findByText(t('en', 'translate.device.cpu'))).toBeInTheDocument()
    expect(screen.queryByText(t('en', 'translate.device.gpu', { done: 49, total: 49 }))).toBeNull()
  })

  // #473: a processor start the headroom gate chose names its reason, like the starved forms; only
  // "beside the chat model" has something the user can do about it.
  it.each([
    ['beside-chat', 'translate.device.cpuBesideChat', true],
    ['chat-starting', 'translate.device.cpuChatStarting', false],
    ['too-large', 'translate.device.cpuTooLarge', false]
  ] as const)('#473: a processor start the gate chose names its reason (%s)', async (cpuCause, key, hasRemedy) => {
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () =>
        appStatus({ translationDevice: { device: 'cpu', gpuLayers: null, totalLayers: null, live: true, cpuCause } })
      ),
      getActiveTranslateJob: vi.fn(async () => null)
    }))
    render(<TranslateScreen onNavigate={vi.fn()} />)
    expect(await screen.findByText(t('en', key))).toBeInTheDocument()
    expect(screen.queryByText(t('en', 'translate.device.gpuNoneTitle')) != null).toBe(hasRemedy)
  })
})

describe('TranslateScreen — translate → stream → copy', () => {
  it('types text, translates, streams the output, and copies it', async () => {
    const s = streamStubs()
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    const input = await screen.findByLabelText(t('en', 'translate.input.label'))
    await user.type(input, 'Hallo Welt.')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))

    // The selects start at the pair the beforeEach put in the session's memory.
    expect(s.translateStart).toHaveBeenCalledWith(
      expect.objectContaining({ sourceLang: 'de', targetLang: 'en', text: 'Hallo Welt.' })
    )
    // The stream is wired once the start round-trip resolves. Scope assertions to the output
    // panel (aria-label "Translation") — the sr-only StreamAnnouncer also mirrors the text.
    await waitFor(() => expect(s.token.fn).toBeDefined())
    act(() => s.token.fn!('Hello '))
    const outPanel = screen.getByLabelText(t('en', 'translate.output.label'))
    expect(await within(outPanel).findByText('Hello', { exact: false })).toBeInTheDocument()
    act(() => s.done.fn!({ jobId: 'j1', state: 'done', text: 'Hello world.' }))
    expect(await within(outPanel).findByText('Hello world.')).toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: t('en', 'translate.copy') }))
    expect(s.copyToClipboard).toHaveBeenCalledWith('Hello world.')
  })

  it('shows Stop while translating and cancels the job', async () => {
    const s = streamStubs()
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    await waitFor(() => expect(s.token.fn).toBeDefined())
    // One busy state (TG-5): the document zone's picker is shut while the text translation runs.
    expect(screen.getByRole('button', { name: t('en', 'translate.drop.choose') })).toBeDisabled()

    await user.click(screen.getByRole('button', { name: t('en', 'translate.stop') }))
    expect(s.translateCancel).toHaveBeenCalledWith('j1')
  })

  it("surfaces the backend's docTaskBusy refusal as a friendly banner", async () => {
    const s = streamStubs({ jobId: 'x', state: 'failed', error: 'docTaskBusy' })
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    expect(await screen.findByText(t('en', 'translate.err.docTaskBusy'))).toBeInTheDocument()
  })

  // #162 (FE-3), #682: the screen's busy state covers only its own two paths, so with a Documents-row
  // task on the lane Translate stays enabled and the click reaches the store's guard. A RUNNING task
  // refuses with its own banner before any job starts; a FINISHED one, which the store keeps until a
  // screen acknowledges it, does not block (the file path's guardStart rule).
  async function startForeignDocTask(
    s: ReturnType<typeof streamStubs>,
    state: DocTaskStatus['state']
  ): Promise<void> {
    stubApi(translateScreenStubs({
      ...s.api,
      startDocTask: vi.fn(async () => ({ jobId: 'foreign' })),
      getDocTask: vi.fn(async () => docTask({ jobId: 'foreign', kind: 'summary', documentIds: ['doc9'], state }))
    }))
    await startTask('summary', 'doc9')
  }

  it('#162 (FE-3): a RUNNING document task started elsewhere refuses with the docTaskBusy banner, no job starts', async () => {
    const s = streamStubs()
    await startForeignDocTask(s, 'running')
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    expect(await screen.findByText(t('en', 'translate.err.docTaskBusy'))).toBeInTheDocument()
    expect(s.translateStart).not.toHaveBeenCalled()
  })

  it('#162 (FE-3): a FINISHED document task still in the store does not block the translation', async () => {
    const s = streamStubs()
    await startForeignDocTask(s, 'done')
    await vi.waitFor(() => expect(isDocTaskTerminal(getActiveDocTask()?.status ?? null)).toBe(true), {
      timeout: hangBudgetMs(3000)
    })
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    await waitFor(() => expect(s.translateStart).toHaveBeenCalled())
    expect(screen.queryByText(t('en', 'translate.err.docTaskBusy'))).not.toBeInTheDocument()
  })

  // #913: the start check refused a translation model a check found damaged — its own copy, which points back to the
  // AI Model screen, not the "low on memory" one of a failed start.
  it('a modelDamaged job shows the download-again banner, not the start-failed one (#913)', async () => {
    const s = streamStubs({ jobId: 'x', state: 'failed', error: 'modelDamaged' })
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)
    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    expect(await screen.findByText(t('en', 'translate.err.modelDamaged'))).toBeInTheDocument()
    expect(screen.queryByText(t('en', 'translate.err.startFailed'))).not.toBeInTheDocument()
  })

  // #1012 code review round 4: the engine's files could not be read just now — the "try again in a minute"
  // banner, not the start-failed or the generic runtime one.
  it('a filesUnreadable job shows the try-again banner (#1012)', async () => {
    const s = streamStubs({ jobId: 'x', state: 'failed', error: 'filesUnreadable' })
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)
    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    expect(await screen.findByText(t('en', 'main.engine.filesUnreadable'))).toBeInTheDocument()
    expect(screen.queryByText(t('en', 'translate.err.runtimeFailed'))).not.toBeInTheDocument()
  })

  it('a dismissed error banner clears the store state (does not stick / reappear on remount)', async () => {
    const s = streamStubs({ jobId: 'x', state: 'failed', error: 'runtimeFailed' })
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    const { unmount } = render(<TranslateScreen onNavigate={() => {}} />)

    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    expect(await screen.findByText(t('en', 'translate.err.runtimeFailed'))).toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: t('en', 'common.dismiss') }))
    expect(screen.queryByText(t('en', 'translate.err.runtimeFailed'))).not.toBeInTheDocument()

    // Remount: the failed state was cleared in the store, so the banner does NOT come back.
    unmount()
    render(<TranslateScreen onNavigate={() => {}} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))
    expect(screen.queryByText(t('en', 'translate.err.runtimeFailed'))).not.toBeInTheDocument()
  })
})

describe('TranslateScreen — language selects', () => {
  it('swaps the source and target languages', async () => {
    const s = streamStubs()
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    const from = (await screen.findByLabelText(t('en', 'translate.from'))) as HTMLSelectElement
    const to = screen.getByLabelText(t('en', 'translate.to')) as HTMLSelectElement
    // The starting pair is the session's last choice (DOC-7 memory the production clears keep), so the
    // swap is asserted against whatever the selects start at.
    const [src, dst] = [from.value, to.value]
    expect(src).not.toBe(dst)
    await user.click(screen.getByRole('button', { name: t('en', 'translate.swap') }))
    expect(from.value).toBe(dst)
    expect(to.value).toBe(src)
  })

  it('disables Translate and hints when source equals target', async () => {
    const s = streamStubs()
    stubApi(translateScreenStubs(s.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    // Make the target match the source, whatever pair the session memory starts at.
    const from = screen.getByLabelText(t('en', 'translate.from')) as HTMLSelectElement
    await user.selectOptions(screen.getByLabelText(t('en', 'translate.to')), from.value)
    expect(screen.getByRole('button', { name: t('en', 'translate.action') })).toBeDisabled()
    // #162 (FE-2): the document zone follows the text path's disabled Translate button.
    expect(screen.getByRole('button', { name: t('en', 'translate.drop.choose') })).toBeDisabled()
    expect(screen.getByText(t('en', 'translate.err.sameLang'))).toBeInTheDocument()
    expect(s.translateStart).not.toHaveBeenCalled()
  })
})

// ---- TG-5: document drag-and-drop + file translation ----

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

/** Stubs the full drop → import → doc-task → materialize pipeline. `getDocTask` returns `running`
 *  once, then the supplied `done`/`failed` status on every later poll. */
function fileStubs(opts: {
  documentIds?: string[]
  terminal?: DocTaskStatus
  preview?: { segments: { text: string }[]; nextOffset?: number | null }
} = {}) {
  const importDocuments = vi.fn(async () => ({
    jobId: 'imp1',
    documentIds: opts.documentIds ?? ['d1']
  }))
  const getImportJob = vi.fn(async () => ({
    jobId: 'imp1',
    total: 1,
    completed: 1,
    failed: 0,
    done: true
  }))
  const startDocTask = vi.fn(async () => ({ jobId: 'task1' }))
  let taskPolls = 0
  const terminal =
    opts.terminal ??
    docTask({ state: 'done', progress: { stepsDone: 3, stepsTotal: 3 }, resultRef: { documentId: 'gen1' } })
  const getDocTask = vi.fn(async () => {
    taskPolls += 1
    return taskPolls === 1 ? docTask({ progress: { stepsDone: 1, stepsTotal: 3 } }) : terminal
  })
  const previewDocument = vi.fn(async () => ({
    id: 'gen1',
    title: 'a (English)',
    mimeType: 'text/markdown',
    segments: (opts.preview?.segments ?? [{ text: 'Hello world.' }]).map((s) => ({
      text: s.text,
      pageNumber: null,
      sectionLabel: null
    })),
    nextOffset: opts.preview?.nextOffset
  }))
  const exportDocument = vi.fn(async () => 'C:\\out\\a (English).md')
  const pickDocuments = vi.fn(async () => ({ token: 'tok1', paths: ['C:\\docs\\a.pdf'] }))
  const getDroppedFilePath = vi.fn(() => 'C:\\docs\\a.pdf')
  return {
    importDocuments,
    getImportJob,
    startDocTask,
    getDocTask,
    previewDocument,
    exportDocument,
    pickDocuments,
    getDroppedFilePath,
    api: {
      getAppStatus: vi.fn(async () => appStatus()),
      getActiveTranslateJob: vi.fn(async () => null),
      copyToClipboard: vi.fn(async () => true),
      importDocuments,
      getImportJob,
      startDocTask,
      getDocTask,
      previewDocument,
      exportDocument,
      pickDocuments,
      getDroppedFilePath
    }
  }
}

function dropOnZone(files: File[], zoneName: string = t('en', 'translate.drop.title')): void {
  // #161 (FE-6): the zone is a plain drag surface (no button role) — locate it via its title.
  const zone = screen.getByText(zoneName).closest('.translate-dropzone')
  if (!(zone instanceof HTMLElement)) throw new Error('drop zone not rendered')
  // A real file drag reports the 'Files' type — the zone gates on it (L8).
  fireEvent.drop(zone, { dataTransfer: { files, types: ['Files'] } })
}

describe('TranslateScreen — document translation (TG-5)', () => {
  it('drops a document → imports as temporary → runs the doc-task → shows the materialized text', async () => {
    const f = fileStubs()
    stubApi(translateScreenStubs(f.api))
    render(<TranslateScreen onNavigate={() => {}} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    const pdf = new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })
    act(() => dropOnZone([pdf]))

    await waitFor(() => expect(f.importDocuments).toHaveBeenCalled())
    // Then the translation doc-task runs over the ingested document with the chosen languages.
    await waitFor(() => expect(f.startDocTask).toHaveBeenCalled())
    expect(f.startDocTask).toHaveBeenCalledWith({
      kind: 'translation',
      documentIds: ['d1'],
      params: { sourceLang: 'de', targetLang: 'en' }
    })
    // The materialized Markdown lands in the output panel.
    const outPanel = await screen.findByLabelText(t('en', 'translate.output.label'))
    expect(await within(outPanel).findByText('Hello world.', {}, { timeout: hangBudgetMs(8000) })).toBeInTheDocument()
  }, testBudgetMs(10000))

  it('translates a document via the choose-a-document picker path', async () => {
    const f = fileStubs()
    stubApi(translateScreenStubs(f.api))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    await user.click(screen.getByRole('button', { name: t('en', 'translate.drop.choose') }))
    await waitFor(() => expect(f.pickDocuments).toHaveBeenCalledWith('files'))
    await waitFor(() => expect(f.importDocuments).toHaveBeenCalled())
    const outPanel = await screen.findByLabelText(t('en', 'translate.output.label'))
    expect(await within(outPanel).findByText('Hello world.', {}, { timeout: hangBudgetMs(8000) })).toBeInTheDocument()
  }, testBudgetMs(10000))

  it('a rejected multi-drop keeps the existing text result (restored when the banner is dismissed)', async () => {
    // Combine the text stubs (for a text translation) with the file stubs' getDroppedFilePath.
    const s = streamStubs()
    const f = fileStubs()
    stubApi(translateScreenStubs({ ...s.api, ...f.api }))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={() => {}} />)

    // First: a completed TEXT translation showing in the panel.
    await user.type(await screen.findByLabelText(t('en', 'translate.input.label')), 'Hallo')
    await user.click(screen.getByRole('button', { name: t('en', 'translate.action') }))
    await waitFor(() => expect(s.done.fn).toBeDefined())
    act(() => s.done.fn!({ jobId: 'j1', state: 'done', text: 'Hello world.' }))
    const outPanel = screen.getByLabelText(t('en', 'translate.output.label'))
    await within(outPanel).findByText('Hello world.')

    // A fat-fingered multi-file drop is REJECTED. The text result must NOT be destroyed.
    act(() =>
      dropOnZone([
        new File(['a'], 'a.pdf', { type: 'application/pdf' }),
        new File(['b'], 'b.pdf', { type: 'application/pdf' })
      ])
    )
    expect(await screen.findByText(t('en', 'translate.file.err.multiDrop'))).toBeInTheDocument()
    expect(f.importDocuments).not.toHaveBeenCalled()

    // Dismissing the error restores the text translation (it was never cleared).
    await user.click(screen.getByRole('button', { name: t('en', 'common.dismiss') }))
    expect(await within(outPanel).findByText('Hello world.')).toBeInTheDocument()
  })

  // ---- FE-3 (OCR-R P2): honest handoff when a SUPPORTED file imports but INGESTION fails ----
  // A PDF imports fine, then ingestion fails: an image-only scan with no text, or a corrupt/
  // encrypted PDF. Pre-fix every such case collapsed to the misleading "unsupported file type"
  // copy. Now the failed row's persisted reason drives the banner — a scan → the OCR handoff;
  // anything else → its localized real message. The genuinely-unsupported EXTENSION path
  // (nothing imported at all) is unchanged (the control below).

  /** A failed `documents` row as `listDocuments` reports it after a failed ingestion. */
  function failedDoc(over: Partial<DocumentInfo> = {}): DocumentInfo {
    return {
      id: 'd1',
      title: 'a.pdf',
      originalPath: 'C:\\docs\\a.pdf',
      mimeType: 'application/pdf',
      sizeBytes: 2048,
      status: 'failed',
      errorMessage: null,
      chunkCount: 0,
      createdAt: '2026-01-01T00:00:00Z',
      updatedAt: '2026-01-01T00:00:00Z',
      ...over
    }
  }

  /** getImportJob reporting an import that finished with nothing ingested. */
  const importFailedJob = () =>
    vi.fn(async () => ({ jobId: 'imp1', total: 1, completed: 0, failed: 1, done: true }))

  it('FE-3: a scanned PDF (imported, ingestion failed) shows the OCR handoff, not "unsupported"', async () => {
    const f = fileStubs({ documentIds: ['d1'] })
    const listDocuments = vi.fn(async () => [
      failedDoc({ scanDetected: true, errorMessage: en['main.ingest.pdfScanDetected'] })
    ])
    stubApi(translateScreenStubs({ ...f.api, getImportJob: importFailedJob(), listDocuments }))
    const onNavigate = vi.fn()
    render(<TranslateScreen onNavigate={onNavigate} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    act(() => dropOnZone([new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })]))

    // The new scan copy points at the Documents "Make searchable (OCR)" action.
    expect(
      await screen.findByText(t('en', 'translate.file.err.scanned'), {}, { timeout: hangBudgetMs(8000) })
    ).toBeInTheDocument()
    // #570 parity: and a button takes the user there.
    fireEvent.click(screen.getByRole('button', { name: t('en', 'translate.file.err.scannedAction') }))
    expect(onNavigate).toHaveBeenCalledWith('documents')
    // And NONE of the misleading "Try a PDF, Word, Markdown, or text file." unsupported copy.
    expect(screen.queryByText(t('en', 'translate.file.err.unsupported'))).not.toBeInTheDocument()
    // No translation task runs over a document that has no text.
    expect(f.startDocTask).not.toHaveBeenCalled()
  }, testBudgetMs(10000))

  // Both failure messages are persist-canonical ENGLISH (D-L4): a failed row's ingestion reason (FE-3)
  // and a doc-task's error (CODE-42, full-audit 2026-07-11). The banner routes them through
  // localizeServerCopy like DocumentsScreen does (DR-7 parity) — rendered under the real I18nProvider
  // forced to German. Neither is a scan, so no button to Documents either.
  it.each([
    {
      label: 'FE-3: a corrupt/encrypted PDF (imported, ingestion failed)',
      key: 'main.ingest.parseTimeout',
      api: () => ({
        ...fileStubs({ documentIds: ['d1'] }).api,
        getImportJob: importFailedJob(),
        listDocuments: vi.fn(async () => [failedDoc({ scanDetected: false, errorMessage: en['main.ingest.parseTimeout'] })])
      })
    },
    {
      label: 'CODE-42: a persisted-English doc-task failure',
      key: 'main.chat.docTaskBusy',
      api: () => fileStubs({ terminal: docTask({ state: 'failed', error: en['main.chat.docTaskBusy'] }) }).api
    }
  ] as const)('$label surfaces its localized real message in the German UI, never the raw English or "unsupported"', async ({ key, api }) => {
    window.localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, 'de')
    try {
      stubApi(translateScreenStubs(api()))
      render(<I18nProvider><TranslateScreen onNavigate={() => {}} /></I18nProvider>)
      await screen.findByLabelText(t('de', 'translate.input.label'))
      act(() => dropOnZone([new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })], t('de', 'translate.drop.title')))
      expect(await screen.findByText(t('de', key), {}, { timeout: hangBudgetMs(8000) })).toBeInTheDocument()
      expect(screen.queryByText(en[key])).not.toBeInTheDocument()
      expect(screen.queryByRole('button', { name: t('de', 'translate.file.err.scannedAction') })).not.toBeInTheDocument()
      expect(screen.queryByText(t('de', 'translate.file.err.unsupported'))).not.toBeInTheDocument()
    } finally {
      window.localStorage.removeItem(UI_LANGUAGE_STORAGE_KEY)
    }
  }, testBudgetMs(10000))

  // #807: a stored error the display map does not know (a parser's own words) read alone, in English, in every
  // interface language. It now reads as on the Documents row for the same file: the translated lead, then the
  // parser's text as the detail. (A known message keeps reading alone, translated: the rows above.)
  it('#807: a parser’s own error (imported, ingestion failed) shows under the translated lead in the German UI', async () => {
    const parserError = 'Invalid PDF structure.'
    window.localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, 'de')
    try {
      stubApi(translateScreenStubs({
        ...fileStubs({ documentIds: ['d1'] }).api,
        getImportJob: importFailedJob(),
        listDocuments: vi.fn(async () => [failedDoc({ scanDetected: false, errorMessage: parserError })])
      }))
      render(<I18nProvider><TranslateScreen onNavigate={() => {}} /></I18nProvider>)
      await screen.findByLabelText(t('de', 'translate.input.label'))
      act(() => dropOnZone([new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })], t('de', 'translate.drop.title')))
      const lead = await screen.findByText(t('de', 'docs.failed.lead'))
      // One banner: the lead, then the parser's words as its detail line.
      const banner = lead.closest('.error-banner-region') as HTMLElement
      expect(within(banner).getByText(parserError)).toBeInTheDocument()
      expect(banner.textContent).toContain(`${t('de', 'docs.failed.lead')}${parserError}`)
      expect(screen.queryByText(t('de', 'translate.file.err.unsupported'))).not.toBeInTheDocument()
    } finally {
      window.localStorage.removeItem(UI_LANGUAGE_STORAGE_KEY)
    }
  }, testBudgetMs(10000))

  it('FE-3 control: a genuinely-unsupported extension (nothing imported) is byte-identical', async () => {
    // main imported nothing supported — the PRE-import path (`documentIds: []`). This must stay
    // exactly the old "unsupported" copy AND never reach the failed-row resolver (no row exists).
    const f = fileStubs({ documentIds: [] })
    const listDocuments = vi.fn(async () => [])
    stubApi(translateScreenStubs({ ...f.api, listDocuments }))
    render(<TranslateScreen onNavigate={() => {}} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    act(() => dropOnZone([new File(['x'], 'a.xyz', { type: '' })]))
    expect(await screen.findByText(t('en', 'translate.file.err.unsupported'))).toBeInTheDocument()
    expect(listDocuments).not.toHaveBeenCalled()
    expect(f.startDocTask).not.toHaveBeenCalled()
  }, testBudgetMs(10000))

  it('exports the materialized document and can show it in Documents', async () => {
    const f = fileStubs()
    stubApi(translateScreenStubs(f.api))
    const onNavigate = vi.fn()
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={onNavigate} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    act(() => dropOnZone([new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })]))
    const outPanel = await screen.findByLabelText(t('en', 'translate.output.label'))
    await within(outPanel).findByText('Hello world.', {}, { timeout: hangBudgetMs(8000) })

    await user.click(screen.getByRole('button', { name: t('en', 'translate.file.export') }))
    expect(f.exportDocument).toHaveBeenCalledWith('gen1')

    await user.click(screen.getByRole('button', { name: t('en', 'translate.file.show') }))
    expect(onNavigate).toHaveBeenCalledWith('documents')
  }, testBudgetMs(10000))

  it('surfaces a truncated hint when only the start of a long translation is shown', async () => {
    const f = fileStubs({ preview: { segments: [{ text: 'Beginning…' }], nextOffset: 40 } })
    stubApi(translateScreenStubs(f.api))
    render(<TranslateScreen onNavigate={() => {}} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    act(() => dropOnZone([new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })]))
    expect(
      await screen.findByText(t('en', 'translate.file.truncated'), {}, { timeout: hangBudgetMs(8000) })
    ).toBeInTheDocument()
  }, testBudgetMs(10000))

  it('#58: a done task with gaps shows the page-gap AND failed-parts warnings', async () => {
    const f = fileStubs({
      terminal: docTask({
        state: 'done',
        progress: { stepsDone: 3, stepsTotal: 3 },
        resultRef: { documentId: 'gen1' },
        gaps: {
          missingPageRanges: [
            { from: 3, to: 4 },
            { from: 7, to: 7 }
          ],
          failedWindows: 2
        }
      })
    })
    stubApi(translateScreenStubs(f.api))
    const { container } = render(<TranslateScreen onNavigate={() => {}} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    act(() => dropOnZone([new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })]))
    // 3 missing pages across two ranges → the plural copy with the formatted "3–4, 7".
    expect(
      await screen.findByText(
        t('en', 'translate.file.gapPages.other', { count: 3, pages: '3–4, 7' }),
        {},
        { timeout: hangBudgetMs(8000) }
      )
    ).toBeInTheDocument()
    expect(
      screen.getByText(t('en', 'translate.file.failedParts.other', { count: 2 }))
    ).toBeInTheDocument()
    // The selector the complete-translation row below relies on sees exactly these two warnings.
    expect(container.querySelectorAll('.translate-pane .hint.warn')).toHaveLength(2)
  }, testBudgetMs(10000))

  it('#58: a complete translation shows NO completeness warning', async () => {
    const f = fileStubs()
    stubApi(translateScreenStubs(f.api))
    const { container } = render(<TranslateScreen onNavigate={() => {}} />)
    await screen.findByLabelText(t('en', 'translate.input.label'))

    act(() => dropOnZone([new File(['%PDF'], 'a.pdf', { type: 'application/pdf' })]))
    const outPanel = await screen.findByLabelText(t('en', 'translate.output.label'))
    await within(outPanel).findByText('Hello world.', {}, { timeout: hangBudgetMs(8000) })
    expect(container.querySelector('.translate-pane .hint.warn')).toBeNull() // no gap or failed-parts warning of any count
  }, testBudgetMs(10000))
})

// ---- #163 (T-2): the mount-adopt effect must have TEETH ----
//
// TranslateScreen's mount effect calls adoptActiveJob() + adoptActiveFileTranslation(). Every
// screen test used to stub getActiveTranslateJob → null and omit the doc-task read, so BOTH
// adopts no-opped in every screen test — deleting the entire effect passed the full suite,
// and the FA-3/F-3 reload recovery could regress silently (panel back idle while the job runs
// invisibly in main; new starts refused docTaskBusy). These two drive each adopt through the
// SCREEN's own mount effect against a main that reports a running job.

describe('TranslateScreen — mount adoption teeth (#163 / T-2)', () => {
  it('re-adopts a running TEXT job on mount: seeds the accumulated output, shows Stop, re-subscribes', async () => {
    const s = streamStubs()
    stubApi(translateScreenStubs({
      ...s.api,
      getActiveTranslateJob: vi.fn(async () => ({
        jobId: 'j9',
        state: 'translating',
        text: 'Halb übersetzt',
        windowsTotal: 2,
        windowsDone: 1
      } as TranslateJob))
    }))
    render(<TranslateScreen onNavigate={vi.fn()} />)

    // The adopt seeded the accumulated text into the live output panel…
    expect(await screen.findByText('Halb übersetzt')).toBeInTheDocument()
    // …the busy affordances are live (Stop present, the working hint shows)…
    expect(screen.getByRole('button', { name: t('en', 'translate.stop') })).toBeInTheDocument()
    // …and the stream channels were re-subscribed under the ADOPTED job id.
    expect(s.api.onTranslateToken).toHaveBeenCalledWith('j9', expect.any(Function))
    expect(s.api.onTranslateDone).toHaveBeenCalledWith('j9', expect.any(Function))
  })

  it('re-adopts a running DOCUMENT translation doc-task on mount (FA-3 / F-3): progress + Stop come back', async () => {
    const running = docTask({ jobId: 'task9', state: 'running', progress: { stepsDone: 2, stepsTotal: 5 } })
    const cancelDocTask = vi.fn(async () => {})
    stubApi(translateScreenStubs({
      getAppStatus: vi.fn(async () => appStatus()),
      getActiveTranslateJob: vi.fn(async () => null),
      listActiveDocTasks: vi.fn(async () => [running]),
      getDocTask: vi.fn(async () => running),
      cancelDocTask
    }))
    const user = userEvent.setup()
    render(<TranslateScreen onNavigate={vi.fn()} />)

    // The panel re-attached: window progress (stepsTotal minus the materialize step) + Stop.
    expect(
      await screen.findByText(t('en', 'translate.file.progress', { done: 2, total: 4 }))
    ).toBeInTheDocument()
    const stop = screen.getByRole('button', { name: t('en', 'translate.stop') })
    // Stop targets the ADOPTED task's id (the exact-id cancel, #157 DT-2).
    await user.click(stop)
    await waitFor(() => expect(cancelDocTask).toHaveBeenCalledWith('task9'))
  })
})