Skip to content

AI, fully local on your computer.

116 KB
Raw Blame
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, cleanup, waitFor, within, act, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { DocumentsScreen } from '../../src/renderer/screens/DocumentsScreen'
import { RAIL_COLLAPSED_KEY, LOCATIONS_MORE_KEY } from '../../src/renderer/screens/documents/types'
import {
  en,
  t as translate,
  UI_LANGUAGE_CODES,
  type MessageKey,
  type MessageParams,
  type UiLanguage
} from '../../src/shared/i18n'
import { ToastProvider } from '../../src/renderer/components'
import { startTask, clearDocTaskSession } from '../../src/renderer/lib/doctasks'
import type { AppStatus, Collection, DocTaskStatus, DocumentInfo } from '../../src/shared/types'
import { stubApi, assertNoUnexpectedApiCalls } from '../helpers/renderer'
import { documentsScreenStubs } from '../helpers/documents-screen'
import { hangBudgetMs } from '../helpers/hang-budget'
import { appStatus as appStatusFixture, makePolicyStatus } from '../helpers/status'
import { NO_OCR_SOURCES } from '../helpers/model-fixtures'
import { renderInLanguage } from '../helpers/render-language'
import { PROJECT_ORDER_CASES, inLanguageOrder } from '../helpers/project-order-fixtures'

// PERF-5: count DocRow renders test-side — production's memo object, inner component wrapped (no src seam).
const rowRenders = vi.hoisted(() => new Map<string, number>())
vi.mock('../../src/renderer/screens/documents/DocRow', async (importOriginal) => {
  const m = await importOriginal<typeof import('../../src/renderer/screens/documents/DocRow')>()
  const { countMemoRenders } = await import('../helpers/render-counter')
  return { ...m, DocRow: countMemoRenders(m.DocRow, (p) => p.d.id, rowRenders) }
})

// Renderer test (jsdom + RTL) for the Documents screen: list rendering + status, the
// stale-embedding re-index banner (M7), the failed-document error, the empty state, and
// the delete action's refresh.

function doc(over: Partial<DocumentInfo>): DocumentInfo {
  return {
    id: 'd1',
    title: 'contract.pdf',
    originalPath: '/u/contract.pdf',
    mimeType: 'application/pdf',
    sizeBytes: 2048,
    status: 'indexed',
    errorMessage: null,
    chunkCount: 7,
    createdAt: '2026-01-01T00:00:00Z',
    updatedAt: '2026-01-01T00:00:00Z',
    ...over
  }
}

function coll(over: Partial<Collection>): Collection {
  return {
    id: 'c1',
    name: 'Project',
    type: 'project',
    description: null,
    builtin: false,
    color: null,
    createdAt: '2026-01-01T00:00:00Z',
    updatedAt: '2026-01-01T00:00:00Z',
    archivedAt: null,
    ...over
  }
}

afterEach(() => {
  cleanup()
  clearDocTaskSession()
  assertNoUnexpectedApiCalls()
})

// ---- Document organization: section rail + chips + project management (plan §12) ----
describe('DocumentsScreen — organization', () => {
  it('renders the section rail and filters the list by the selected project', async () => {
    const user = userEvent.setup()
    const library = coll({ id: 'lib', name: 'Library', type: 'library', builtin: true })
    const tax = coll({ id: 'tax', name: 'Tax 2025' })
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [library, tax]),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'policy.pdf', collections: [{ id: 'lib', name: 'Library', type: 'library', role: 'source' }] }),
        doc({ id: 'd2', title: 'return.pdf', collections: [{ id: 'tax', name: 'Tax 2025', type: 'project', role: 'source' }] })
      ])
    }))
    window.localStorage.clear()
    render(<DocumentsScreen />)
    // Rail sections are present: the project, and the non-empty locations behind "More" (§11.16).
    expect(await screen.findByRole('button', { name: 'Tax 2025' })).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'More' }))
    expect(screen.getByRole('button', { name: 'Library' })).toBeInTheDocument()
    // Empty locations are not offered.
    expect(screen.queryByRole('button', { name: 'Generated' })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Archived' })).not.toBeInTheDocument()
    // Both docs show under "All documents" (default section).
    expect(screen.getByText('policy.pdf')).toBeInTheDocument()
    expect(screen.getByText('return.pdf')).toBeInTheDocument()
    // Selecting the project filters to its member.
    await user.click(screen.getByRole('button', { name: 'Tax 2025' }))
    expect(screen.getByText('return.pdf')).toBeInTheDocument()
    expect(screen.queryByText('policy.pdf')).not.toBeInTheDocument()
  })

  it('creates a project from the rail "+" and selects it', async () => {
    const user = userEvent.setup()
    const library = coll({ id: 'lib', name: 'Library', type: 'library', builtin: true })
    const created = coll({ id: 'new', name: 'Lawsuit' })
    const createCollection = vi.fn(async () => created)
    const listCollections = vi
      .fn<() => Promise<Collection[]>>()
      .mockResolvedValueOnce([library])
      .mockResolvedValue([library, created])
    stubApi(documentsScreenStubs({ listCollections, listDocuments: vi.fn(async () => [doc({})]), createCollection }))
    render(<DocumentsScreen />)
    await user.click(await screen.findByRole('button', { name: 'New project' }))
    await user.type(await screen.findByLabelText('Project name'), 'Lawsuit')
    await user.click(screen.getByRole('button', { name: 'Create' }))
    await waitFor(() => expect(createCollection).toHaveBeenCalledWith('Lawsuit'))
    expect(await screen.findByRole('button', { name: 'Lawsuit' })).toHaveAttribute('aria-current', 'true')
  })

  // ---- Phase E: smart views + generated-staleness badge (plan §7.6/§12.1/§15.3) ------

  it('shows a quiet staleness badge on a generated row whose source changed, but not a fresh one', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        // Source re-indexed (updatedAt) AFTER the translation was made → stale.
        doc({ id: 's1', title: 'report.pdf', updatedAt: '2026-05-01T00:00:00Z' }),
        doc({
          id: 'staleGen',
          title: 'report.de.md',
          origin: { kind: 'translation', sourceDocumentIds: ['s1'], createdAt: '2026-01-01T00:00:00Z' }
        }),
        // Source untouched since the output was made → fresh.
        doc({ id: 's2', title: 'memo.pdf', updatedAt: '2026-01-01T00:00:00Z' }),
        doc({
          id: 'freshGen',
          title: 'memo.de.md',
          origin: { kind: 'translation', sourceDocumentIds: ['s2'], createdAt: '2026-02-01T00:00:00Z' }
        })
      ])
    }))
    // The rail reads the remembered "More" state on mount — start closed so the click OPENS it.
    window.localStorage.clear()
    render(<DocumentsScreen />)

    // In the Generated view (a location behind "More", §11.16) both generated docs show; exactly
    // one is flagged stale.
    await user.click(await screen.findByRole('button', { name: 'More' }))
    await user.click(await screen.findByRole('button', { name: 'Generated' }))
    expect(screen.getByText('report.de.md')).toBeInTheDocument()
    expect(screen.getByText('memo.de.md')).toBeInTheDocument()
    expect(screen.getAllByText('Outdated')).toHaveLength(1)
    expect(screen.getByText(/re-run to update/i)).toBeInTheDocument()
  })

  // ---- Phase C: Temporary lifecycle actions (plan §14.1) ----------------------------
  function tempStubs(extra: Record<string, unknown> = {}): {
    addToCollection: ReturnType<typeof vi.fn>
    setDocumentLifecycle: ReturnType<typeof vi.fn>
    removeFromCollection: ReturnType<typeof vi.fn>
  } {
    const library = coll({ id: 'lib', name: 'Library', type: 'library', builtin: true })
    const temp = coll({ id: 'temp', name: 'Temporary', type: 'temporary', builtin: true })
    const tax = coll({ id: 'tax', name: 'Tax 2025' })
    const addToCollection = vi.fn(async () => {})
    const setDocumentLifecycle = vi.fn(async () => [])
    const removeFromCollection = vi.fn(async () => {})
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [library, temp, tax]),
      listDocuments: vi.fn(async () => [
        doc({
          id: 'd1',
          title: 'invoice.pdf',
          lifecycle: 'temporary',
          collections: [{ id: 'temp', name: 'Temporary', type: 'temporary', role: 'source' }]
        })
      ]),
      addToCollection,
      setDocumentLifecycle,
      removeFromCollection,
      ...extra
    }))
    return { addToCollection, setDocumentLifecycle, removeFromCollection }
  }

  it('"Keep in Library" adds Library, sets permanent, and drops Temporary', async () => {
    const user = userEvent.setup()
    const { addToCollection, setDocumentLifecycle, removeFromCollection } = tempStubs()
    render(<DocumentsScreen />)
    await screen.findByText('invoice.pdf')
    // Organize actions now live in the per-row "⋯" overflow (§11.6).
    await user.click(screen.getByRole('button', { name: 'More actions for invoice.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Keep in Library' }))
    await waitFor(() => expect(addToCollection).toHaveBeenCalledWith(['d1'], 'lib'))
    expect(setDocumentLifecycle).toHaveBeenCalledWith(['d1'], 'permanent')
    expect(removeFromCollection).toHaveBeenCalledWith(['d1'], 'temp')
  })

  it('"Move to project" on a Temporary doc adds the project, sets permanent, and drops Temporary', async () => {
    const user = userEvent.setup()
    const { addToCollection, setDocumentLifecycle, removeFromCollection } = tempStubs()
    render(<DocumentsScreen />)
    await screen.findByText('invoice.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for invoice.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Move to project…' }))
    await user.click(await screen.findByRole('button', { name: 'Tax 2025' }))
    await waitFor(() => expect(addToCollection).toHaveBeenCalledWith(['d1'], 'tax'))
    expect(setDocumentLifecycle).toHaveBeenCalledWith(['d1'], 'permanent')
    expect(removeFromCollection).toHaveBeenCalledWith(['d1'], 'temp')
  })
})

describe('DocumentsScreen', () => {
  it('lists documents with their status and chunk count', async () => {
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]) }))
    render(<DocumentsScreen />)
    expect(await screen.findByText('contract.pdf')).toBeInTheDocument()
    // Status reads as a Badge (icon + word), never a button (Task 2).
    expect(screen.getByText('Ready')).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Ready' })).not.toBeInTheDocument()
    // The muted meta strip shows the friendly type, size, and section count (Task 5).
    expect(screen.getByText('PDF · 2.0 KB · 7 sections')).toBeInTheDocument()
    // The raw MIME type is never shown.
    expect(screen.queryByText('application/pdf')).not.toBeInTheDocument()
  })

  it('shows the re-index banner for a document with stale embeddings (M7)', async () => {
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({ staleEmbeddings: true })]) }))
    render(<DocumentsScreen />)
    expect(await screen.findByText(/different search model/i)).toBeInTheDocument()
  })

  it('does NOT show the re-index banner when embeddings are current', async () => {
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({ staleEmbeddings: false })]) }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    expect(screen.queryByText(/different search model/i)).not.toBeInTheDocument()
  })

  it('surfaces a localized, softened error for a failed import; offers Remove not Preview (Task B/C)', async () => {
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        // The legacy raw literal is still recognized by the display map and re-rendered as the
        // friendly copy (no raw English leak), keeping the offending extension.
        doc({ status: 'failed', errorMessage: 'Unsupported file type: .xyz', chunkCount: 0 })
      ])
    }))
    render(<DocumentsScreen />)
    // Softened §7 copy — the raw "Unsupported file type" phrasing is gone, the extension shows.
    expect(await screen.findByText(/isn't supported/i)).toBeInTheDocument()
    expect(screen.getByText(/\.xyz/)).toBeInTheDocument()
    expect(screen.queryByText(/Unsupported file type/i)).not.toBeInTheDocument()
    expect(screen.getByText('Failed')).toBeInTheDocument()
    // Failed rows expose Remove, never Preview/overflow; an unsupported type is NOT retryable.
    expect(screen.getByRole('button', { name: 'Remove' })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Preview' })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Try again' })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /More actions/ })).not.toBeInTheDocument()
  })

  it('offers Try again + Remove on a RETRYABLE failure; Remove clears it via the delete handler (Task C)', async () => {
    const user = userEvent.setup()
    const listDocuments = vi
      .fn<() => Promise<DocumentInfo[]>>()
      .mockResolvedValueOnce([
        doc({ id: 'd9', title: 'broken.pdf', status: 'failed', errorMessage: 'EIO: i/o error, read', chunkCount: 0 })
      ])
      .mockResolvedValue([]) // after remove
    const deleteDocument = vi.fn(async () => {})
    stubApi(documentsScreenStubs({ listDocuments, deleteDocument }))
    render(<DocumentsScreen />)
    await screen.findByText('broken.pdf')
    // A transient read error IS retryable → Try again offered alongside Remove; never Preview.
    expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Preview' })).not.toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'Remove' }))
    await waitFor(() => expect(deleteDocument).toHaveBeenCalledWith('d9'))
  })

  it('deletes a document after the ConfirmDialog confirms, and refreshes the list', async () => {
    const user = userEvent.setup()
    const listDocuments = vi
      .fn<() => Promise<DocumentInfo[]>>()
      .mockResolvedValueOnce([doc({})]) // initial mount
      .mockResolvedValue([]) // after delete
    const deleteDocument = vi.fn(async () => {})
    stubApi(documentsScreenStubs({ listDocuments, deleteDocument }))
    render(<DocumentsScreen />)

    await screen.findByText('contract.pdf')
    // Delete is a destructive item inside the per-row "⋯" overflow (§11.6), and still goes
    // through a ConfirmDialog (Phase 24) — never an equal-weight surface button.
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: /delete/i }))
    expect(deleteDocument).not.toHaveBeenCalled()

    const dialog = await screen.findByRole('dialog')
    expect(dialog).toHaveTextContent(translate('en', 'docs.deleteConfirm.title', { title: 'contract.pdf' }))
    await user.click(within(dialog).getByRole('button', { name: /^delete$/i }))

    await waitFor(() => expect(deleteDocument).toHaveBeenCalledWith('d1'))
    await waitFor(() => expect(screen.queryByText('contract.pdf')).not.toBeInTheDocument())
  })

  it('does not delete when the ConfirmDialog is cancelled', async () => {
    const user = userEvent.setup()
    const deleteDocument = vi.fn(async () => {})
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), deleteDocument }))
    render(<DocumentsScreen />)

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: /delete/i }))
    await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: /cancel/i }))

    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
    expect(deleteDocument).not.toHaveBeenCalled()
    expect(screen.getByText('contract.pdf')).toBeInTheDocument()
  })

  it('opens the read-only preview modal with the extracted text and closes it', async () => {
    const user = userEvent.setup()
    const previewDocument = vi.fn(async () => ({
      id: 'd1',
      title: 'contract.pdf',
      mimeType: 'application/pdf',
      segments: [
        { text: 'Clause 7: severance terms apply.', pageNumber: 3, sectionLabel: null },
        { text: 'Appendix text.', pageNumber: null, sectionLabel: 'Appendix' }
      ]
    }))
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), previewDocument }))
    render(<DocumentsScreen />)

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: /preview/i }))

    expect(previewDocument).toHaveBeenCalledWith('d1')
    expect(await screen.findByText(/Clause 7: severance terms apply/)).toBeInTheDocument()
    expect(screen.getByText('Page 3')).toBeInTheDocument()
    expect(screen.getByText('Appendix')).toBeInTheDocument()
    expect(screen.getByRole('dialog')).toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: /close/i }))
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
  })

  it('paginates the preview: reveals the next page on "Show more" (FE-6)', async () => {
    const user = userEvent.setup()
    // First page carries a cursor (nextOffset) + the true total; page 2 exhausts it.
    const previewDocument = vi.fn(async () => ({
      id: 'd1',
      title: 'contract.pdf',
      mimeType: 'application/pdf',
      segments: [{ text: 'First page clause.', pageNumber: 1, sectionLabel: null }],
      totalSegments: 2,
      nextOffset: 1
    }))
    const previewDocumentPage = vi.fn(async () => ({
      id: 'd1',
      title: 'contract.pdf',
      mimeType: 'application/pdf',
      segments: [{ text: 'Second page clause.', pageNumber: 2, sectionLabel: null }],
      totalSegments: 2,
      nextOffset: null
    }))
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), previewDocument, previewDocumentPage }))
    render(<DocumentsScreen />)

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: /preview/i }))

    expect(await screen.findByText(/First page clause/)).toBeInTheDocument()
    // The second page is NOT mounted yet — that's the whole point of FE-6.
    expect(screen.queryByText(/Second page clause/)).not.toBeInTheDocument()
    expect(screen.getByText('Showing 1 of 2')).toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: /show more/i }))

    expect(previewDocumentPage).toHaveBeenCalledWith('d1', 1, 50)
    expect(await screen.findByText(/Second page clause/)).toBeInTheDocument()
    // The first page stays mounted (accumulated), and the exhausted cursor hides the button.
    expect(screen.getByText(/First page clause/)).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /show more/i })).not.toBeInTheDocument()
  })

  it('surfaces a preview failure as the screen error', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({})]),
      previewDocument: vi.fn(async () => {
        throw new Error('The document file is no longer on disk. Re-import it to preview.')
      })
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: /preview/i }))
    expect(await screen.findByText(/no longer on disk/)).toBeInTheDocument()
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
  })

  // ---- "Ask these documents" + Re-index all (Phase 17) ---------------------------

  it('selecting indexed documents enables "Ask these documents" with the selected ids', async () => {
    const user = userEvent.setup()
    const onAskSelected = vi.fn()
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({}),
        doc({ id: 'd2', title: 'terms.docx' }),
        doc({ id: 'd3', title: 'broken.xyz', status: 'failed', chunkCount: 0 })
      ])
    }))
    render(<DocumentsScreen onAskSelected={onAskSelected} />)
    await screen.findByText('contract.pdf')

    // Failed documents get no checkbox; nothing selected → no Ask button yet. The header
    // select-all checkbox (#214) is the third one, present whenever at least one indexed
    // document is visible.
    expect(screen.getAllByRole('checkbox')).toHaveLength(3)
    expect(screen.queryByRole('button', { name: /ask these documents/i })).not.toBeInTheDocument()

    await user.click(screen.getByRole('checkbox', { name: /select contract.pdf/i }))
    await user.click(screen.getByRole('checkbox', { name: /select terms.docx/i }))
    await user.click(screen.getByRole('button', { name: /ask these documents \(2\)/i }))
    expect(onAskSelected).toHaveBeenCalledWith(expect.arrayContaining(['d1', 'd2']))
  })

  // ---- Header "select all" checkbox (#214) ----------------------------------------

  it('the header select-all checkbox selects every visible indexed document, and clears on a second click', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({}),
        doc({ id: 'd2', title: 'terms.docx' }),
        // A failed document gets no per-row checkbox at all — select-all must not touch it.
        doc({ id: 'd3', title: 'broken.xyz', status: 'failed', chunkCount: 0 })
      ])
    }))
    render(<DocumentsScreen onAskSelected={() => {}} />)
    await screen.findByText('contract.pdf')

    const selectAll = screen.getByRole('checkbox', { name: 'Select all documents' })
    expect(selectAll).not.toBeChecked()
    expect(screen.queryByRole('group', { name: /actions for the selected documents/i })).not.toBeInTheDocument()

    await user.click(selectAll)
    expect(screen.getByRole('checkbox', { name: /select contract.pdf/i })).toBeChecked()
    expect(screen.getByRole('checkbox', { name: /select terms.docx/i })).toBeChecked()
    expect(selectAll).toBeChecked()
    const bar = await screen.findByRole('group', { name: /actions for the selected documents/i })
    expect(within(bar).getByText('2 selected')).toBeInTheDocument()

    // Second click clears the whole selection.
    await user.click(selectAll)
    expect(selectAll).not.toBeChecked()
    expect(screen.getByRole('checkbox', { name: /select contract.pdf/i })).not.toBeChecked()
    expect(screen.getByRole('checkbox', { name: /select terms.docx/i })).not.toBeChecked()
    expect(
      screen.queryByRole('group', { name: /actions for the selected documents/i })
    ).not.toBeInTheDocument()
  })

  it('the name filter narrows select-all to only the currently visible documents', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'Lease 2026.pdf' }),
        doc({ id: 'd2', title: 'Q3 audit notes.docx' })
      ])
    }))
    render(<DocumentsScreen onAskSelected={() => {}} />)
    await screen.findByText('Lease 2026.pdf')

    const box = screen.getByRole('searchbox', { name: 'Filter documents by name' })
    await user.type(box, 'lease')
    expect(screen.queryByText('Q3 audit notes.docx')).not.toBeInTheDocument()

    await user.click(screen.getByRole('checkbox', { name: 'Select all documents' }))
    const bar = await screen.findByRole('group', { name: /actions for the selected documents/i })
    // Only the one FILTERED-IN document was selected, not the whole (unfiltered) library.
    expect(within(bar).getByText('1 selected')).toBeInTheDocument()

    // Clearing the filter reveals the other document again, still unselected — select-all
    // acted on what was visible at click time, not a standing "select everything" intent.
    await user.clear(box)
    expect(await screen.findByText('Q3 audit notes.docx')).toBeInTheDocument()
    expect(within(bar).getByText('1 selected')).toBeInTheDocument()
    expect(screen.getByRole('checkbox', { name: /select q3 audit notes.docx/i })).not.toBeChecked()
  })

  // ---- Audio (Phase 36): formats line, Transcribing badge, D35 size confirm ------

  it('advertises the verified audio formats on the Supported line', async () => {
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => []) }))
    render(<DocumentsScreen />)
    expect(await screen.findByText(/WAV, MP3, FLAC,\s*OGG/)).toBeInTheDocument()
  })

  it('shows "Transcribing…" with the percent for an audio document being read', async () => {
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({
          title: 'meeting.mp3',
          mimeType: 'audio/mpeg',
          status: 'extracting',
          transcriptionProgress: 42,
          chunkCount: 0
        })
      ])
    }))
    render(<DocumentsScreen />)
    expect(await screen.findByText(/Transcribing… 42%/)).toBeInTheDocument()
    // A TEXT document in `extracting` keeps the plain "Reading" label.
    cleanup()
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({ status: 'extracting', chunkCount: 0 })]) }))
    render(<DocumentsScreen />)
    expect(await screen.findByText('Reading')).toBeInTheDocument()
  })

  it('asks before importing large audio (D35) and imports only on confirm', async () => {
    const user = userEvent.setup()
    const importDocuments = vi.fn(async () => ({ jobId: 'j1', documentIds: ['d9'] }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({})]),
      pickDocuments: vi.fn(async () => ({ token: 'tok1', paths: ['/u/long-meeting.wav'] })),
      importPreflight: vi.fn(async () => ({
        fileCount: 1,
        audioFileCount: 1,
        audioBytes: 600_000_000 // decimal (#768): in 1024 steps 572.2 MB
      })),
      importDocuments,
      getImportJob: vi.fn(async () => ({ jobId: 'j1', total: 1, completed: 1, failed: 0, done: true }))
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')

    await user.click(screen.getByRole('button', { name: /import files/i }))
    // The confirm came up FIRST — nothing imported yet.
    const dialog = await screen.findByRole('dialog')
    expect(dialog).toHaveTextContent(/Import large audio\?/)
    expect(dialog).toHaveTextContent(/600\.0 MB/)
    expect(importDocuments).not.toHaveBeenCalled()

    await user.click(within(dialog).getByRole('button', { name: /import and transcribe/i }))
    // D1: the picker capability token is carried through the confirm dialog into the import.
    await waitFor(() =>
      expect(importDocuments).toHaveBeenCalledWith(['/u/long-meeting.wav'], { pickerToken: 'tok1' })
    )
  })

  it('cancelling the large-audio confirm imports nothing', async () => {
    const user = userEvent.setup()
    const importDocuments = vi.fn(async () => ({ jobId: 'j1', documentIds: [] }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({})]),
      pickDocuments: vi.fn(async () => ({ token: 'tok1', paths: ['/u/long-meeting.wav'] })),
      importPreflight: vi.fn(async () => ({
        fileCount: 1,
        audioFileCount: 1,
        audioBytes: 600 * 1024 * 1024
      })),
      importDocuments
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: /import files/i }))
    await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: /cancel/i }))
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
    expect(importDocuments).not.toHaveBeenCalled()
  })

  it('small/text selections import directly with no confirm', async () => {
    const user = userEvent.setup()
    const importDocuments = vi.fn(async () => ({ jobId: 'j1', documentIds: ['d9'] }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({})]),
      pickDocuments: vi.fn(async () => ({ token: 'tok2', paths: ['/u/note.txt'] })),
      importPreflight: vi.fn(async () => ({ fileCount: 1, audioFileCount: 0, audioBytes: 0 })),
      importDocuments,
      getImportJob: vi.fn(async () => ({ jobId: 'j1', total: 1, completed: 1, failed: 0, done: true }))
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: /import files/i }))
    await waitFor(() =>
      expect(importDocuments).toHaveBeenCalledWith(['/u/note.txt'], { pickerToken: 'tok2' })
    )
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
  })

  // #274: a folder walk cut by its budget is reported on the preflight result — the screen says so
  // ONCE (the import's own walk is cut the same way, so the job's `exhausted` must not toast again)
  // and the import still proceeds with what was counted.
  it('a walk cut by its budget toasts "too large to scan completely" once and still imports (#274)', async () => {
    const user = userEvent.setup()
    const importDocuments = vi.fn(async () => ({ jobId: 'j1', documentIds: ['d9', 'd10', 'd11'], exhausted: 'entries' as const }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({})]),
      pickDocuments: vi.fn(async () => ({ token: 'tok3', paths: ['/u/huge-folder'] })),
      importPreflight: vi.fn(async () => ({ fileCount: 3, audioFileCount: 0, audioBytes: 0, exhausted: 'entries' as const })),
      importDocuments,
      getImportJob: vi.fn(async () => ({ jobId: 'j1', total: 3, completed: 3, failed: 0, done: true, exhausted: 'entries' as const }))
    }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )
    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: /import folder/i }))
    await screen.findByText('The folder was too large to scan completely — 3 items were counted.')
    await waitFor(() =>
      expect(importDocuments).toHaveBeenCalledWith(['/u/huge-folder'], { pickerToken: 'tok3' })
    )
    // The job completes with the same cut — one notice, not two.
    await waitFor(() => expect(screen.queryByText(/importing…/i)).not.toBeInTheDocument())
    expect(screen.getAllByText(/too large to scan completely/)).toHaveLength(1)
  })

  it('"Re-index all" confirms first, then starts the main-owned bulk job with every stale id (M-U6)', async () => {
    const user = userEvent.setup()
    const stale = [
      doc({ id: 'd1', staleEmbeddings: true }),
      doc({ id: 'd2', title: 'terms.docx', staleEmbeddings: true })
    ]
    const listDocuments = vi
      .fn<() => Promise<DocumentInfo[]>>()
      .mockResolvedValueOnce(stale)
      .mockResolvedValue(stale.map((d) => ({ ...d, staleEmbeddings: false })))
    // The per-document loop now lives in MAIN (tested in docs-ipc.test.ts). The renderer just
    // delegates to startReindexAll and polls getReindexAllJob; a `done` job clears the bar.
    const finished = { jobId: 'r1', total: 2, completed: 2, failed: 0, done: true, cancelled: false }
    const startReindexAll = vi.fn(async () => finished)
    const getReindexAllJob = vi.fn(async () => finished)
    stubApi(documentsScreenStubs({ listDocuments, startReindexAll, getReindexAllJob }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )

    // The toolbar button opens a ConfirmDialog — nothing runs until it is confirmed (M-U6).
    await user.click(await screen.findByRole('button', { name: /re-index all \(2\)/i }))
    const dialog = within(await screen.findByRole('dialog'))
    expect(dialog.getByText(/re-index 2 documents\?/i)).toBeInTheDocument()
    expect(startReindexAll).not.toHaveBeenCalled()

    await user.click(dialog.getByRole('button', { name: /^re-index all$/i }))
    await waitFor(() => expect(startReindexAll).toHaveBeenCalledWith(['d1', 'd2']))
    // The completion toast stays plural for 2 (the tCount .other side — CODE-8).
    expect(
      await screen.findByText('Re-indexed 2 documents.', {}, { timeout: hangBudgetMs(5000) })
    ).toBeInTheDocument()
    // The bar clears once the polled job reports done and the list refreshes (no more stale docs).
    await waitFor(() =>
      expect(screen.queryByRole('button', { name: /re-index all/i })).not.toBeInTheDocument()
    )
  })

  // full-audit 2026-07-11 CODE-8: the completion toast used to read "Re-indexed 1 documents."
  // The toolbar buttons are gated `length > 1`, so a count=1 CONFIRM title is not reachable
  // through the UI today (the ≥2 pins above cover the .other side; the .one side of both
  // titles is pinned at the unit level in i18n.test.ts) — but the toast renders whatever job
  // shape MAIN reports, exercised here through the real mount-adoption path.
  it('CODE-8: an adopted single-document job toasts the singular summary', async () => {
    const stale = [doc({ id: 'd1', staleEmbeddings: true })]
    const listDocuments = vi
      .fn<() => Promise<DocumentInfo[]>>()
      .mockResolvedValueOnce(stale)
      .mockResolvedValue(stale.map((d) => ({ ...d, staleEmbeddings: false })))
    // Mount-adoption: the screen finds a still-running single-document job in main and
    // watches it; the next poll reports it done.
    const getReindexAllJob = vi
      .fn<() => Promise<{ jobId: string; total: number; completed: number; failed: number; done: boolean; cancelled: boolean }>>()
      .mockResolvedValueOnce({ jobId: 'r1', total: 1, completed: 0, failed: 0, done: false, cancelled: false })
      .mockResolvedValue({ jobId: 'r1', total: 1, completed: 1, failed: 0, done: true, cancelled: false })
    stubApi(documentsScreenStubs({ listDocuments, getReindexAllJob }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )

    // Pre-fix: "Re-indexed 1 documents." (plain t() over the {done} key — CODE-8).
    expect(
      await screen.findByText('Re-indexed 1 document.', {}, { timeout: hangBudgetMs(5000) })
    ).toBeInTheDocument()
  })

  // #572: only the rows a retry can fix — an unsupported type and a detected scan fail the same
  // way again, so they are neither counted nor retried (their rows offer no "Try again" either).
  it('"Retry all" on the Failed tab confirms first, then starts the bulk job with every retryable failed id', async () => {
    const user = userEvent.setup()
    window.localStorage.clear()
    const failed = [
      doc({ id: 'd1', title: 'broken.xyz', status: 'failed', errorMessage: 'Unsupported file type: .xyz', chunkCount: 0 }),
      doc({ id: 'd2', title: 'corrupt.pdf', status: 'failed', errorMessage: 'EIO: i/o error, read', chunkCount: 0 }),
      doc({ id: 'd3', title: 'locked.docx', status: 'failed', errorMessage: 'EBUSY: resource busy', chunkCount: 0 }),
      doc({ id: 'd4', title: 'scan.pdf', status: 'failed', errorMessage: en['main.ingest.pdfScanDetected'], scanDetected: true, chunkCount: 0 })
    ]
    const listDocuments = vi.fn<() => Promise<DocumentInfo[]>>().mockResolvedValue(failed)
    const finished = { jobId: 'r1', total: 2, completed: 2, failed: 0, done: true, cancelled: false }
    const startReindexAll = vi.fn(async () => finished)
    const getReindexAllJob = vi.fn(async () => finished)
    stubApi(documentsScreenStubs({
      getOcrInstallStatus: vi.fn(async () => NO_OCR_SOURCES),
      getPolicy: vi.fn(async () => makePolicyStatus()),
      listDocuments,
      startReindexAll,
      getReindexAllJob
    }))
    render(<DocumentsScreen />)

    // The "Retry all" button lives ONLY in the "Needs attention" view (§11.16).
    await screen.findByRole('button', { name: 'All documents' })
    expect(screen.queryByRole('button', { name: /retry all/i })).not.toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'Needs attention' }))

    // Opens a ConfirmDialog — nothing runs until confirmed (M-U6).
    await user.click(await screen.findByRole('button', { name: /retry all \(2\)/i }))
    const dialog = within(await screen.findByRole('dialog'))
    expect(dialog.getByText(/retry 2 failed documents\?/i)).toBeInTheDocument()
    expect(startReindexAll).not.toHaveBeenCalled()

    await user.click(dialog.getByRole('button', { name: /^retry all$/i }))
    await waitFor(() => expect(startReindexAll).toHaveBeenCalledWith(['d2', 'd3']))
  })

  // ---- FE-7: poll job status only during import; refresh the list on a transition -------
  it('during import polls getImportJob each tick but refreshes the full list only on a file completion', async () => {
    vi.useFakeTimers()
    try {
      // fireEvent + advanceTimersByTimeAsync only — NO userEvent here (userEvent's internal real
      // delays fight fake timers and can hang, leaking fake timers into the rest of the file).
      const listDocuments = vi.fn(async () => [doc({})])
      let completed = 0
      const getImportJob = vi.fn(async () => ({
        jobId: 'j1',
        total: 2,
        completed,
        failed: 0,
        done: completed >= 2
      }))
      stubApi(documentsScreenStubs({
        listDocuments,
        pickDocuments: vi.fn(async () => ({ token: 'tok3', paths: ['/u/a.pdf', '/u/b.pdf'] })),
        importPreflight: vi.fn(async () => ({ fileCount: 2, audioFileCount: 0, audioBytes: 0 })),
        importDocuments: vi.fn(async () => ({ jobId: 'j1', documentIds: ['d1', 'd2'] })),
        getImportJob
      }))
      const flush = async (): Promise<void> => {
        await act(async () => {
          for (let i = 0; i < 8; i++) await vi.advanceTimersByTimeAsync(0)
        })
      }
      render(<DocumentsScreen />)
      await flush() // mount refresh + ocr status
      // Start the import (synchronous click; the async pick → preflight → import → watchJob chain
      // is flushed below).
      fireEvent.click(screen.getByRole('button', { name: /import files/i }))
      await flush()
      const listAfterStart = listDocuments.mock.calls.length
      const jobAfterStart = getImportJob.mock.calls.length

      // Three ticks with NO new completion: getImportJob keeps polling, but the heavy
      // listDocuments refresh runs only once (the first tick's -1 → 0 transition), not per tick.
      await act(async () => {
        await vi.advanceTimersByTimeAsync(1200)
      })
      expect(getImportJob.mock.calls.length).toBeGreaterThanOrEqual(jobAfterStart + 3)
      expect(listDocuments.mock.calls.length).toBe(listAfterStart + 1)

      // A file finishes (completed 0 → 2): the next tick transitions, so the list refreshes again
      // and, being done, the poll stops.
      completed = 2
      await act(async () => {
        await vi.advanceTimersByTimeAsync(400)
      })
      expect(listDocuments.mock.calls.length).toBe(listAfterStart + 2)
    } finally {
      vi.useRealTimers()
    }
  })

  // ---- F-31: coalesce rapid file-completion refreshes during a bulk import -------------
  it('coalesces rapid file-completion refreshes to the leading edge within the throttle window (F-31)', async () => {
    vi.useFakeTimers()
    try {
      const listDocuments = vi.fn(async () => [doc({})])
      // A NEW file finishes on every poll tick (0 → 1 → 2 …), so every tick is a completion
      // transition — the exact bulk-import shape. Old behavior refreshed the whole list per tick;
      // the F-31 throttle coalesces a burst inside REFRESH_THROTTLE_MS (1.5 s) to one leading refresh.
      let poll = 0
      const total = 10
      const getImportJob = vi.fn(async () => {
        const completed = Math.min(poll, total)
        poll += 1
        return { jobId: 'j1', total, completed, failed: 0, done: completed >= total }
      })
      stubApi(documentsScreenStubs({
        listDocuments,
        pickDocuments: vi.fn(async () => ({ token: 'tokF31', paths: ['/u/a.pdf', '/u/b.pdf'] })),
        importPreflight: vi.fn(async () => ({ fileCount: 2, audioFileCount: 0, audioBytes: 0 })),
        importDocuments: vi.fn(async () => ({ jobId: 'j1', documentIds: ['d1', 'd2'] })),
        getImportJob
      }))
      const flush = async (): Promise<void> => {
        await act(async () => {
          for (let i = 0; i < 8; i++) await vi.advanceTimersByTimeAsync(0)
        })
      }
      const { unmount } = render(<DocumentsScreen />)
      await flush() // mount refresh + ocr status
      fireEvent.click(screen.getByRole('button', { name: /import files/i }))
      await flush()
      const listAfterStart = listDocuments.mock.calls.length

      // Three 400 ms ticks, a NEW completion on EACH (three transitions in 1.2 s < 1.5 s window).
      // Without the throttle the full list would reload three times (+3); coalesced it reloads once.
      await act(async () => {
        await vi.advanceTimersByTimeAsync(1200)
      })
      expect(getImportJob.mock.calls.length).toBeGreaterThanOrEqual(3)
      expect(listDocuments.mock.calls.length).toBe(listAfterStart + 1)
      unmount() // stop the (still-running) poll before restoring real timers
    } finally {
      vi.useRealTimers()
    }
  })

  // ---- FE-4: a late import-poll tick after unmount must not refresh the list ----------
  it('drops an in-flight import-poll tick after unmount — no list refresh on a dead component', async () => {
    vi.useFakeTimers()
    try {
      const listDocuments = vi.fn(async () => [doc({})])
      // getImportJob parks on its FIRST poll call: it hands back a promise we resolve BY HAND, so
      // the tick goes in-flight, straddles the unmount, and THEN resolves with a transition
      // (completed -1 → 2) that would normally trigger refresh() — exercising the post-await guard.
      type Job = { jobId: string; total: number; completed: number; failed: number; done: boolean }
      let release: (() => void) | null = null
      const getImportJob = vi.fn(
        (): Promise<Job> =>
          new Promise<Job>((res) => {
            release = () => res({ jobId: 'j1', total: 2, completed: 2, failed: 0, done: false })
          })
      )
      stubApi(documentsScreenStubs({
        listDocuments,
        pickDocuments: vi.fn(async () => ({ token: 't', paths: ['/u/a.pdf', '/u/b.pdf'] })),
        importPreflight: vi.fn(async () => ({ fileCount: 2, audioFileCount: 0, audioBytes: 0 })),
        importDocuments: vi.fn(async () => ({ jobId: 'j1', documentIds: ['d1', 'd2'] })),
        getImportJob
      }))
      const flush = async (): Promise<void> => {
        await act(async () => {
          for (let i = 0; i < 8; i++) await vi.advanceTimersByTimeAsync(0)
        })
      }
      const { unmount } = render(<DocumentsScreen />)
      await flush() // mount refresh
      fireEvent.click(screen.getByRole('button', { name: /import files/i }))
      await flush() // pick → preflight → import → watchJob armed (no tick yet)

      // Fire the first poll tick → getImportJob parks mid-await (in-flight).
      await act(async () => {
        await vi.advanceTimersByTimeAsync(400)
      })
      expect(release).not.toBeNull()
      const listBefore = listDocuments.mock.calls.length

      // Unmount mid-poll (clears the interval), THEN resolve the parked tick. The post-await guard
      // drops it: no extra listDocuments refresh on the dead component (teeth: without the guard the
      // -1 → 2 transition would call refresh() → listDocuments again).
      unmount()
      await act(async () => {
        release!()
        await vi.advanceTimersByTimeAsync(0)
      })
      expect(listDocuments.mock.calls.length).toBe(listBefore)
    } finally {
      vi.useRealTimers()
    }
  })

  it('"Re-index all" can be cancelled without running anything (M-U6)', async () => {
    const user = userEvent.setup()
    const stale = [
      doc({ id: 'd1', staleEmbeddings: true }),
      doc({ id: 'd2', title: 'terms.docx', staleEmbeddings: true })
    ]
    const startReindexAll = vi.fn(async () => ({ jobId: 'r1', total: 2, completed: 0, failed: 0, done: false, cancelled: false }))
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => stale), startReindexAll }))
    render(<DocumentsScreen />)

    await user.click(await screen.findByRole('button', { name: /re-index all \(2\)/i }))
    const dialog = within(await screen.findByRole('dialog'))
    await user.click(dialog.getByRole('button', { name: /cancel/i }))
    expect(startReindexAll).not.toHaveBeenCalled()
  })

  it('recovers an in-flight bulk re-index on mount and its Cancel button calls cancelReindexAll', async () => {
    const user = userEvent.setup()
    // A job already running in MAIN — the mount effect re-attaches the determinate bar + Cancel
    // (this is the navigation-survival path). Clicking Cancel asks main to stop.
    const running = { jobId: 'r1', total: 5, completed: 1, failed: 0, done: false, cancelled: false }
    const getReindexAllJob = vi.fn(async () => running)
    const cancelReindexAll = vi.fn(async () => undefined)
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), getReindexAllJob, cancelReindexAll }))
    render(<DocumentsScreen />)

    const cancelBtn = await screen.findByRole('button', { name: 'Cancel' })
    await user.click(cancelBtn)
    expect(cancelReindexAll).toHaveBeenCalled()
  })

  // full-audit 2026-07-11 CODE-29: the bulk-re-index Cancel was fire-and-forget (`void
  // window.api.cancelReindexAll?.()`) — a rejected cancel left the bar running silently with
  // an unhandled rejection. It now routes through runAndSurface → the screen's error banner.
  it('surfaces a rejected bulk-re-index cancel on the error banner (no unhandled rejection)', async () => {
    const user = userEvent.setup()
    const running = { jobId: 'r1', total: 5, completed: 1, failed: 0, done: false, cancelled: false }
    const getReindexAllJob = vi.fn(async () => running)
    const cancelReindexAll = vi.fn(async () => {
      throw new Error("Error invoking remote method 'cancelReindexAll': Error: cancel exploded")
    })
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), getReindexAllJob, cancelReindexAll }))
    render(<DocumentsScreen />)

    await user.click(await screen.findByRole('button', { name: 'Cancel' }))
    expect(cancelReindexAll).toHaveBeenCalled()
    // The friendly message (transport prefix stripped) lands on the error banner; the bar
    // stays truthful — main still runs the job.
    expect(await screen.findByText('cancel exploded')).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument()
  })
})

// #807: a failed row whose stored message the display map does not know (a parser's or the OS's own
// words, stored as-is) says what happened in the interface language: the translated lead, ABOVE the
// raw text, which stays as the detail line. The app's own messages read as before, with no lead.
describe('DocumentsScreen — the lead above a failure message the app does not know (#807)', () => {
  afterEach(() => window.localStorage.clear())

  const RAW = 'Invalid PDF structure.'

  /** The failed row's banner text in `lang` (its text content is the lines in DOM order). */
  async function failedBanner(lang: UiLanguage, over: Partial<DocumentInfo>): Promise<HTMLElement> {
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({ id: 'd9', title: 'broken.pdf', status: 'failed', chunkCount: 0, ...over })
      ]),
      listCollections: vi.fn(async () => []),
      getAppStatus: vi.fn(async () => appStatusFixture({ ocrAvailable: true })),
      getReindexAllJob: vi.fn(async () => null),
      getActiveImportJob: vi.fn(async () => null)
    }))
    renderInLanguage(<DocumentsScreen />, lang)
    const row = (await screen.findByText('broken.pdf')).closest('.doc-row') as HTMLElement
    return row.querySelector('.banner-text') as HTMLElement
  }

  it.each(UI_LANGUAGE_CODES)('%s: an unknown message reads under the translated lead, the raw text kept', async (lang) => {
    const banner = await failedBanner(lang, { errorMessage: RAW })
    const lead = translate(lang, 'docs.failed.lead')
    // A block of its own, so it sits above the raw text rather than running into it.
    expect(within(banner).getByText(lead).tagName).toBe('P')
    expect(banner.textContent).toBe(`${lead}${RAW}`)
  })

  // One message of each display-map branch a document row can carry: the exact map and the five
  // interpolated families (the very same classifier serves the benchmark warnings).
  const tDe = (key: MessageKey, params?: MessageParams): string => translate('de', key, params)
  const tEn = (key: MessageKey, params?: MessageParams): string => translate('en', key, params)
  it.each([
    { family: 'a persisted constant', raw: en['main.ingest.parseTimeout'], shown: tDe('main.ingest.parseTimeout') },
    {
      family: 'unsupported type',
      raw: tEn('main.ingest.unsupportedType', { ext: '.xyz' }),
      shown: tDe('main.ingest.unsupportedType', { ext: '.xyz' })
    },
    {
      family: 'unsupported type, legacy wording',
      raw: 'Unsupported file type: .xyz',
      shown: tDe('main.ingest.unsupportedType', { ext: '.xyz' })
    },
    {
      family: 'very low tokens',
      raw: tEn('main.benchmark.warnVeryLowTokens', { model: 'qwen3-4b' }),
      shown: tDe('main.benchmark.warnVeryLowTokens', { model: 'qwen3-4b' })
    },
    {
      family: 'slow read',
      raw: tEn('main.benchmark.warnSlowRead', { mbps: '70' }),
      shown: tDe('main.benchmark.warnSlowRead', { mbps: '70' })
    },
    {
      family: 'recommendation lowered',
      raw: tEn('main.benchmark.warnRecommendationLowered', { tps: '2.2', model: 'qwen3-4b' }),
      shown: tDe('main.benchmark.warnRecommendationLowered', { tps: '2.2', model: 'qwen3-4b' })
    },
    {
      family: 'engine library missing',
      raw: tEn('main.ingest.engineLibraryMissing', { library: 'libgomp.so.1' }),
      shown: tDe('main.ingest.engineLibraryMissing', { library: 'libgomp.so.1' })
    }
  ])('de: $family reads as before, with no lead', async ({ raw, shown }) => {
    const banner = await failedBanner('de', { errorMessage: raw })
    expect(shown).not.toBe(raw) // genuinely translated, so the row proves the map read it
    expect(banner.textContent).toBe(shown)
  })

  it('de: a detected scan keeps its warning and OCR offer, with no lead', async () => {
    const banner = await failedBanner('de', {
      errorMessage: en['main.ingest.pdfScanDetected'],
      scanDetected: true
    })
    // The offer joins once the OCR verdict lands.
    await waitFor(() =>
      expect(banner.textContent).toBe(`${tDe('main.ingest.pdfScanDetected')} ${tDe('docs.scan.ocrOffer')}`)
    )
  })
})

// ---- §11.6 refinement: action overflow, MIME→label, selection toolbar, status badges ----
describe('DocumentsScreen — action overflow + selection toolbar (§11.6)', () => {
  it('the "⋯" overflow exposes Summarize/Translate/Re-index/Build deep index/Add to project + a destructive Delete that opens ConfirmDialog', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [coll({ id: 'tax', name: 'Tax 2025' })]),
      listDocuments: vi.fn(async () => [doc({ fullyChunked: true, treeStatus: null })])
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    // Only ONE inline action (Preview) sits on the row; everything else is behind "⋯".
    expect(screen.getByRole('button', { name: /^preview$/i })).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /^summarize$/i })).not.toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    expect(await screen.findByRole('menuitem', { name: 'Summarize' })).toBeInTheDocument()
    expect(screen.getByRole('menuitem', { name: 'Translate' })).toBeInTheDocument()
    expect(screen.getByRole('menuitem', { name: 'Re-index' })).toBeInTheDocument()
    expect(screen.getByRole('menuitem', { name: 'Build deep index' })).toBeInTheDocument()
    expect(screen.getByRole('menuitem', { name: 'Move to project…' })).toBeInTheDocument()

    const del = screen.getByRole('menuitem', { name: /delete/i })
    expect(del).toBeInTheDocument()
    await user.click(del)
    expect(await screen.findByRole('dialog')).toHaveTextContent(
      translate('en', 'docs.deleteConfirm.title', { title: 'contract.pdf' })
    )
  })

  it('the selection toolbar appears only on selection and its bulk Delete confirms then deletes', async () => {
    const user = userEvent.setup()
    const listDocuments = vi
      .fn<() => Promise<DocumentInfo[]>>()
      .mockResolvedValueOnce([doc({ id: 'd1' }), doc({ id: 'd2', title: 'terms.docx' })])
      .mockResolvedValue([doc({ id: 'd2', title: 'terms.docx' })])
    const deleteDocument = vi.fn(async () => {})
    stubApi(documentsScreenStubs({ listDocuments, deleteDocument }))
    render(<DocumentsScreen onAskSelected={() => {}} />)
    await screen.findByText('contract.pdf')

    expect(
      screen.queryByRole('group', { name: /actions for the selected documents/i })
    ).not.toBeInTheDocument()
    await user.click(screen.getByRole('checkbox', { name: /select contract.pdf/i }))
    const bar = await screen.findByRole('group', { name: /actions for the selected documents/i })
    expect(within(bar).getByText('1 selected')).toBeInTheDocument()

    await user.click(within(bar).getByRole('button', { name: /^delete$/i }))
    const dialog = await screen.findByRole('dialog')
    expect(dialog).toHaveTextContent(/Delete 1 document\?/)
    expect(deleteDocument).not.toHaveBeenCalled()
    await user.click(within(dialog).getByRole('button', { name: /^delete$/i }))
    await waitFor(() => expect(deleteDocument).toHaveBeenCalledWith('d1'))
  })

  it('a COMPLETE deep index (tree + extract, #38) reads as the "Deeply indexed" badge (not a button), and Build is gone from the overflow', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({ fullyChunked: true, treeStatus: 'ready', extractStatus: 'ready' })
      ])
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    expect(screen.getByText('Deeply indexed')).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Deeply indexed' })).not.toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await screen.findByRole('menuitem', { name: 'Summarize' })
    expect(screen.queryByRole('menuitem', { name: 'Build deep index' })).not.toBeInTheDocument()
  })

  // ---- §11.6 follow-up refinement: reading column, right-aligned cluster, quiet chips,
  //      one-green status hierarchy, keyboard-reachable "⋯" ----------------------------------

  it('lays the row out as a flex-filling name column + a right-aligned trailing cluster', async () => {
    const summary = { text: 's', modelId: 'm', createdAt: '2026-01-01T00:00:00Z', truncated: false }
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [coll({ id: 'lib', name: 'Library', type: 'library', builtin: true })]),
      listDocuments: vi.fn(async () => [
        doc({
          fullyChunked: true,
          treeStatus: 'ready',
          summary,
          collections: [{ id: 'lib', name: 'Library', type: 'library', role: 'source' }]
        })
      ])
    }))
    const { container } = render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')

    // The name column fills the flex space and the title line ellipsizes only on overflow.
    const main = container.querySelector('.doc-row-main')
    expect(main).toBeInTheDocument()
    const title = container.querySelector('.doc-row-title')
    expect(title).toHaveTextContent('contract.pdf')

    // One right-aligned trailing cluster holds chips, badges, then the actions — in that order.
    const trailing = container.querySelector('.doc-row-trailing')
    expect(trailing).toBeInTheDocument()
    const children = Array.from(trailing!.children)
    expect(children[0]).toHaveClass('doc-row-chips')
    expect(children[1]).toHaveClass('doc-row-badges')
    expect(children[2]).toHaveClass('doc-row-actions')
    // Preview + "⋯" are the rightmost group, so they align in a column down the list.
    const actions = trailing!.querySelector('.doc-row-actions')!
    expect(within(actions as HTMLElement).getByRole('button', { name: /^preview$/i })).toBeInTheDocument()
    expect(within(actions as HTMLElement).getByRole('button', { name: /more actions/i })).toBeInTheDocument()
  })

  it('renders tag chips as a distinct quieter element from the bordered Preview button', async () => {
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [coll({ id: 'lib', name: 'Library', type: 'library', builtin: true })]),
      listDocuments: vi.fn(async () => [
        doc({ collections: [{ id: 'lib', name: 'Library', type: 'library', role: 'source' }] })
      ])
    }))
    const { container } = render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    // The tag is a non-interactive Chip inside the chips group — not a button, not the Preview.
    const chipGroup = container.querySelector('.doc-row-chips')!
    const chip = within(chipGroup as HTMLElement).getByText('Library')
    expect(chip.closest('.chip')).toBeInTheDocument()
    expect(chip.closest('button')).toBeNull()
    // Preview is a separate <button>, so a tag can never read as that action.
    expect(screen.getByRole('button', { name: /^preview$/i })).toBeInTheDocument()
  })

  it('keeps readiness as the only green badge — Summary + Deeply indexed are neutral', async () => {
    const summary = { text: 's', modelId: 'm', createdAt: '2026-01-01T00:00:00Z', truncated: false }
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({ fullyChunked: true, treeStatus: 'ready', extractStatus: 'ready', summary })
      ])
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    // Readiness = success (green).
    expect(screen.getByText('Ready').closest('.pill')).toHaveClass('pill-success')
    // Capability badges = neutral (grey), each keeping icon + word (1.4.1).
    expect(screen.getByText('Summary').closest('.pill')).toHaveClass('pill-neutral')
    expect(screen.getByText('Deeply indexed').closest('.pill')).toHaveClass('pill-neutral')
    // Exactly one success badge on the row.
    expect(document.querySelectorAll('.doc-row .pill-success')).toHaveLength(1)
  })

  it('the "⋯" trigger is keyboard-focusable even though it is hover-revealed', async () => {
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]) }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    const trigger = screen.getByRole('button', { name: 'More actions for contract.pdf' })
    trigger.focus()
    expect(trigger).toHaveFocus()
    expect(trigger).not.toHaveAttribute('tabindex', '-1')
  })
})

// ---- §11.16 sub-nav declutter: mode switch, counts, "Needs attention", projects, locations
//      behind "More", the name filter, collapsible panel --------------------------------------
describe('DocumentsScreen — sub-nav (section rail) declutter', () => {
  // The Turkish-system row's `String.prototype.toLocaleLowerCase` patch, undone after every row,
  // so a row that fails or times out half-way cannot leave the faked system to the rows after it.
  let turkishSystem: { mockRestore: () => void } | null = null
  beforeEach(() => {
    try {
      window.localStorage.clear()
    } catch {
      /* jsdom */
    }
  })
  afterEach(() => {
    turkishSystem?.mockRestore()
    turkishSystem = null
    try {
      window.localStorage.clear()
    } catch {
      /* jsdom */
    }
  })

  it('renders the mode switch and the decluttered rail: All documents · Recently added · Projects · More; Unfiled lists only the unfiled documents', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [
        coll({ id: 'lib', name: 'Library', type: 'library', builtin: true }),
        coll({ id: 'tax', name: 'Tax 2025' })
      ]),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', collections: [{ id: 'tax', name: 'Tax 2025', type: 'project', role: 'source' }] }),
        doc({ id: 'd2', title: 'loose.pdf', collections: [{ id: 'lib', name: 'Library', type: 'library', role: 'source' }] })
      ])
    }))
    render(<DocumentsScreen />)
    // The header's segmented switch (the Chat header pattern): a radiogroup, My documents selected.
    const group = await screen.findByRole('radiogroup', { name: 'Documents view' })
    expect(within(group).getByRole('radio', { name: 'My documents' })).toHaveAttribute('aria-checked', 'true')
    expect(within(group).getByRole('radio', { name: 'Knowledge packs' })).toHaveAttribute('aria-checked', 'false')
    const all = screen.getByRole('button', { name: 'All documents' })
    const recent = screen.getByRole('button', { name: 'Recently added' })
    const projects = screen.getByText('Projects')
    const more = screen.getByRole('button', { name: 'More' })
    // DOM order: All documents → Recently added → Projects → More (Node.DOCUMENT_POSITION_FOLLOWING = 4).
    expect(all.compareDocumentPosition(recent) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
    expect(recent.compareDocumentPosition(projects) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
    expect(projects.compareDocumentPosition(more) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
    // Counts ride beside the entries (visual — aria-hidden, so the names stay the plain labels).
    expect(all).toHaveTextContent('2')
    expect(screen.getByRole('button', { name: 'Tax 2025' })).toHaveTextContent('1')
    expect(screen.getByRole('button', { name: 'Unfiled' })).toHaveTextContent('1')
    // No group headers other than Projects; nothing needs attention, so that entry is absent.
    expect(screen.queryByText('Locations')).not.toBeInTheDocument()
    expect(screen.queryByText('Views')).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Needs attention' })).not.toBeInTheDocument()
    // The lead paragraph teaches only in the empty state.
    expect(screen.queryByText(/Import documents to ask questions/)).not.toBeInTheDocument()
    // Unfiled lists the Library-only document, never the project-filed one (Library isn't "filed").
    await user.click(screen.getByRole('button', { name: 'Unfiled' }))
    expect(screen.getByText('loose.pdf')).toBeInTheDocument()
    expect(screen.queryByText('contract.pdf')).not.toBeInTheDocument()
  })

  it('the active item carries aria-current and uses the fill (not a ring); selection moves it', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [doc({})])
    }))
    render(<DocumentsScreen />)
    // Default landing = All documents, marked current.
    const all = await screen.findByRole('button', { name: 'All documents' })
    expect(all).toHaveAttribute('aria-current', 'true')
    expect(all).toHaveClass('active')
    // Selecting Recently added moves aria-current there; All documents drops it.
    await user.click(screen.getByRole('button', { name: 'Recently added' }))
    expect(screen.getByRole('button', { name: 'Recently added' })).toHaveAttribute('aria-current', 'true')
    expect(screen.getByRole('button', { name: 'All documents' })).not.toHaveAttribute('aria-current')
  })

  it('offers "Needs attention" only while something failed or is stale, with its count, and it filters to those', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'fine.pdf' }),
        doc({ id: 'd2', title: 'stale.pdf', staleEmbeddings: true }),
        doc({ id: 'd3', title: 'broken.xyz', status: 'failed', errorMessage: 'Unsupported file type: .xyz', chunkCount: 0 })
      ])
    }))
    render(<DocumentsScreen />)
    const attention = await screen.findByRole('button', { name: 'Needs attention' })
    expect(attention).toHaveTextContent('2')
    await user.click(attention)
    expect(screen.getByText('stale.pdf')).toBeInTheDocument()
    expect(screen.getByText('broken.xyz')).toBeInTheDocument()
    expect(screen.queryByText('fine.pdf')).not.toBeInTheDocument()
  })

  it('folds the locations behind a "More" disclosure (keyboard, aria-expanded, remembered); empty locations are hidden', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [coll({ id: 'lib', name: 'Library', type: 'library', builtin: true })]),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', collections: [{ id: 'lib', name: 'Library', type: 'library', role: 'source' }] }),
        doc({ id: 'd2', title: 'note.md', lifecycle: 'archived' })
      ])
    }))
    render(<DocumentsScreen />)
    const more = await screen.findByRole('button', { name: 'More' })
    expect(more).toHaveAttribute('aria-expanded', 'false')
    expect(screen.queryByRole('button', { name: 'Library' })).not.toBeInTheDocument()
    // Keyboard: focus + Enter expands.
    more.focus()
    await user.keyboard('{Enter}')
    expect(more).toHaveAttribute('aria-expanded', 'true')
    expect(screen.getByRole('button', { name: 'Library' })).toHaveTextContent('1')
    expect(screen.getByRole('button', { name: 'Archived' })).toHaveTextContent('1')
    // Nothing is temporary or generated ⇒ those locations are not even offered.
    expect(screen.queryByRole('button', { name: 'Temporary' })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Generated' })).not.toBeInTheDocument()
    // The expanded state persists across sessions.
    expect(window.localStorage.getItem(LOCATIONS_MORE_KEY)).toBe('1')
    // Space collapses it again.
    await user.keyboard(' ')
    expect(more).toHaveAttribute('aria-expanded', 'false')
    expect(window.localStorage.getItem(LOCATIONS_MORE_KEY)).toBe('0')
  })

  it('with no project the rail shows one "+ New project" row; with a project, the header "+" and an Unfiled row', async () => {
    const user = userEvent.setup()
    const createCollection = vi.fn(async () => coll({ id: 'new', name: 'Lawsuit' }))
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [doc({})]),
      createCollection
    }))
    const first = render(<DocumentsScreen />)
    // Exactly one affordance, and it opens the create dialog.
    const row = await screen.findByRole('button', { name: 'New project' })
    expect(screen.getAllByRole('button', { name: 'New project' })).toHaveLength(1)
    expect(screen.queryByText('Projects')).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Unfiled' })).not.toBeInTheDocument()
    await user.click(row)
    expect(await screen.findByLabelText('Project name')).toBeInTheDocument()
    first.unmount()

    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => [coll({ id: 'tax', name: 'Tax 2025' })]),
      listDocuments: vi.fn(async () => [doc({})])
    }))
    render(<DocumentsScreen />)
    expect(await screen.findByText('Projects')).toBeInTheDocument()
    expect(screen.getAllByRole('button', { name: 'New project' })).toHaveLength(1)
    expect(screen.getByRole('button', { name: 'Unfiled' })).toHaveTextContent('1')
  })

  it('the name filter narrows the visible section and says so when nothing matches', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'Lease 2026.pdf' }),
        doc({ id: 'd2', title: 'Q3 audit notes.docx' })
      ])
    }))
    render(<DocumentsScreen />)
    await screen.findByText('Lease 2026.pdf')
    const box = screen.getByRole('searchbox', { name: 'Filter documents by name' })
    await user.type(box, 'lease')
    expect(screen.getByText('Lease 2026.pdf')).toBeInTheDocument()
    expect(screen.queryByText('Q3 audit notes.docx')).not.toBeInTheDocument()
    // The rail counts are the section's, not the filter's.
    expect(screen.getByRole('button', { name: 'All documents' })).toHaveTextContent('2')
    await user.clear(box)
    await user.type(box, 'zzz')
    expect(screen.getByText('No documents match “zzz”.')).toBeInTheDocument()
  })

  // Second UI-languages wave owner call G-5 (2026-11-13): the filter folds with the shared `foldCase`
  // (`text-fold.test.ts` owns the letters). It used to lower with the runtime's default locale,
  // which in the app is Chromium's (the OS language): on a Turkish system "Invoice" became
  // "ınvoice" and a typed "inv" found nothing. The row runs on such a system: a toLocaleLowerCase()
  // without a locale lowers in Turkish, through the real ICU data.
  it('the name filter finds "Invoice" for a typed "inv" on a Turkish system', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'Invoice 2026-03.pdf' }),
        doc({ id: 'd2', title: 'Lease 2026.pdf' })
      ])
    }))
    render(<DocumentsScreen />)
    await screen.findByText('Invoice 2026-03.pdf')
    const lower = String.prototype.toLocaleLowerCase
    turkishSystem = vi
      .spyOn(String.prototype, 'toLocaleLowerCase')
      .mockImplementation(function (this: string, locales?: Intl.LocalesArgument) {
        return lower.call(this, locales ?? 'tr')
      })
    // The system is Turkish for real (a Node without the tr data would make this row vacuous).
    expect('Invoice'.toLocaleLowerCase().includes('inv')).toBe(false)
    await user.type(screen.getByRole('searchbox', { name: 'Filter documents by name' }), 'inv')
    expect(screen.getByText('Invoice 2026-03.pdf')).toBeInTheDocument()
    expect(screen.queryByText('Lease 2026.pdf')).not.toBeInTheDocument()
  })

  // Second UI-languages wave owner call G-5, on any system: both sides of the match go through
  // `foldCase`. Plain toLowerCase() keeps a typed "ı" dotless (the first search misses) and lowers
  // the title's "İ" to "i" + U+0307 (the second one misses), so this row goes red when either side
  // drops the fold.
  it('the name filter folds Turkish I letters on both sides: «ısı» finds «ISI raporu», «istanbul» finds «İSTANBUL kira»', async () => {
    const user = userEvent.setup()
    const dotless = String.fromCharCode(0x0131)
    const istanbul = `${String.fromCharCode(0x0130)}STANBUL kira.pdf`
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'ISI raporu.pdf' }),
        doc({ id: 'd2', title: istanbul })
      ])
    }))
    render(<DocumentsScreen />)
    await screen.findByText('ISI raporu.pdf')
    const box = screen.getByRole('searchbox', { name: 'Filter documents by name' })
    await user.type(box, `${dotless}s${dotless}`)
    expect(screen.getByText('ISI raporu.pdf')).toBeInTheDocument()
    expect(screen.queryByText(istanbul)).not.toBeInTheDocument()
    await user.clear(box)
    await user.type(box, 'istanbul')
    expect(screen.getByText(istanbul)).toBeInTheDocument()
    expect(screen.queryByText('ISI raporu.pdf')).not.toBeInTheDocument()
  })

  it('the Knowledge packs mode replaces the rail and list with the packs panel; the empty state links to it', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      onKnowledgePacksChanged: vi.fn(() => () => {}),
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => []),
      getKnowledgePackStatus: vi.fn(async () => ({ toolsInstalled: true, refreshing: false, revision: 0 })),
      listKnowledgePacks: vi.fn(async () => [])
    }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )
    // Empty state: the lead teaches, and the second line offers the other kind of source.
    expect(await screen.findByText('No documents yet')).toBeInTheDocument()
    expect(screen.getByText(/Import documents to ask questions/)).toBeInTheDocument()
    await user.click(screen.getByRole('button', { name: 'Knowledge packs' }))
    expect(screen.getByRole('radio', { name: 'Knowledge packs' })).toHaveAttribute('aria-checked', 'true')
    expect(await screen.findByText('No knowledge packs yet')).toBeInTheDocument()
    // No document rail, no document toolbar in this mode.
    expect(screen.queryByRole('button', { name: 'All documents' })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Import files' })).not.toBeInTheDocument()
    // …and back.
    await user.click(screen.getByRole('radio', { name: 'My documents' }))
    expect(await screen.findByText('No documents yet')).toBeInTheDocument()
  })

  it('initialMode="packs" opens the packs panel directly (the documents:packs deep link)', async () => {
    stubApi(documentsScreenStubs({
      onKnowledgePacksChanged: vi.fn(() => () => {}),
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [doc({})]),
      getKnowledgePackStatus: vi.fn(async () => ({ toolsInstalled: true, refreshing: false, revision: 0 })),
      listKnowledgePacks: vi.fn(async () => [])
    }))
    render(
      <ToastProvider>
        <DocumentsScreen initialMode="packs" />
      </ToastProvider>
    )
    expect(await screen.findByText('No knowledge packs yet')).toBeInTheDocument()
    expect(screen.getByRole('radio', { name: 'Knowledge packs' })).toHaveAttribute('aria-checked', 'true')
    expect(screen.queryByText('contract.pdf')).not.toBeInTheDocument()
  })

  it('collapses and expands the whole sub-nav, remembering the state; collapsed → no rail', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [doc({})])
    }))
    render(<DocumentsScreen />)
    // Expanded by default: the rail and its "All documents" row are present.
    expect(await screen.findByRole('button', { name: 'All documents' })).toBeInTheDocument()
    // Collapse via the "«" handle.
    await user.click(screen.getByRole('button', { name: 'Hide sections' }))
    expect(screen.queryByRole('button', { name: 'All documents' })).not.toBeInTheDocument()
    expect(window.localStorage.getItem(RAIL_COLLAPSED_KEY)).toBe('1')
    // A "»" handle re-opens it.
    const show = screen.getByRole('button', { name: 'Show sections' })
    expect(show).toBeInTheDocument()
    await user.click(show)
    expect(screen.getByRole('button', { name: 'All documents' })).toBeInTheDocument()
    expect(window.localStorage.getItem(RAIL_COLLAPSED_KEY)).toBe('0')
  })
})

// ---- PERF-5 (Part A): DocRow memoization -----------------------------------------------
// An unrelated parent re-render (toggling another row's selection / opening another row's ⋯ menu)
// must re-render ONLY the affected row, not every row. Each test asserts TWO things:
//   (1) the user-VISIBLE EFFECT of the interaction (the checkbox is now checked + the selection
//       toolbar counts it / the ⋯ menu actually opened and the sibling rows are intact) — so a
//       regression where the click stops producing its effect but an unrelated re-render still bumps
//       the count CANNOT pass green (T2, full-audit-2026-06-30); and
//   (2) the SECONDARY perf oracle — a test-side counter (`countMemoRenders`, tests/helpers/render-counter.ts)
//       wrapped around production's `DocRow` memo by the `vi.mock` above: only the affected row's delta
//       moves. Removing `memo(...)`, or passing the whole `selected` Set / `menuOpenId` string or an
//       inline handler instead of the per-row boolean / stable handler, re-renders the untouched rows
//       too → the delta assertions fail.
describe('DocumentsScreen — row memoization (PERF-5)', () => {
  it('re-renders ONLY the toggled row when another row’s selection changes', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'alpha.pdf' }),
        doc({ id: 'd2', title: 'beta.pdf' }),
        doc({ id: 'd3', title: 'gamma.pdf' })
      ])
    }))
    // onAskSelected makes the per-row select checkboxes appear (indexed rows only).
    render(<DocumentsScreen onAskSelected={() => {}} />)
    await screen.findByText('alpha.pdf')
    // Let the post-mount refresh's selection-pruning setState settle before snapshotting.
    await screen.findByText('gamma.pdf')

    // Snapshot render counts AFTER the list is stable, then toggle d2's selection only.
    const before = new Map(rowRenders)
    const beta = screen.getByRole('checkbox', { name: /select beta.pdf/i })
    expect(beta).not.toBeChecked()
    await user.click(beta)

    // (1) BEHAVIOR: the click actually toggled d2's selection — the checkbox reads checked, the
    // untouched rows read unchecked, and the selection toolbar counts exactly one. (This is what a
    // "click no longer toggles selection" regression breaks; the render-count delta alone would not.)
    expect(beta).toBeChecked()
    expect(screen.getByRole('checkbox', { name: /select alpha.pdf/i })).not.toBeChecked()
    expect(screen.getByRole('checkbox', { name: /select gamma.pdf/i })).not.toBeChecked()
    const bar = await screen.findByRole('group', { name: /actions for the selected documents/i })
    expect(within(bar).getByText('1 selected')).toBeInTheDocument()

    // (2) PERF (secondary): the toggled row re-rendered (its `selected` boolean flipped)…
    const delta = (id: string): number =>
      (rowRenders.get(id) ?? 0) - (before.get(id) ?? 0)
    expect(delta('d2')).toBeGreaterThan(0)
    // …while the untouched rows held their memo (their props are Object.is-unchanged). With
    // memo removed (or the whole Set passed), these would be > 0 and the test fails — the teeth.
    expect(delta('d1')).toBe(0)
    expect(delta('d3')).toBe(0)
  })

  it('re-renders ONLY the opened row when another row’s ⋯ menu opens', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => [
        doc({ id: 'd1', title: 'alpha.pdf' }),
        doc({ id: 'd2', title: 'beta.pdf' }),
        doc({ id: 'd3', title: 'gamma.pdf' })
      ])
    }))
    render(<DocumentsScreen />)
    await screen.findByText('alpha.pdf')
    await screen.findByText('gamma.pdf')

    const before = new Map(rowRenders)
    // Opening d2's overflow flips the parent's `menuOpenId` to 'd2'.
    await user.click(screen.getByRole('button', { name: 'More actions for beta.pdf' }))

    // (1) BEHAVIOR: the click actually OPENED d2's menu (its items are now reachable), and the
    // sibling rows are untouched — their titles still render exactly as before. A regression where
    // the ⋯ click no longer opens the menu (but some unrelated re-render bumps the count) reddens here.
    const menu = await screen.findByRole('menu')
    expect(within(menu).getByRole('menuitem', { name: 'Re-index' })).toBeInTheDocument()
    expect(screen.getByText('alpha.pdf')).toBeInTheDocument()
    expect(screen.getByText('gamma.pdf')).toBeInTheDocument()

    // (2) PERF (secondary): only d2 re-rendered; d1/d3 receive `menuOpen={false}` unchanged → their
    // memo holds. (Teeth: passing the whole menuOpenId string, or dropping memo, re-renders them too.)
    const delta = (id: string): number =>
      (rowRenders.get(id) ?? 0) - (before.get(id) ?? 0)
    expect(delta('d2')).toBeGreaterThan(0)
    expect(delta('d1')).toBe(0)
    expect(delta('d3')).toBe(0)
  })
})

// ---- PERF-2 (= PERF-5 Part B): documents-list windowing ---------------------------------
// At scale the un-windowed list mounted one live DocRow — each with a Radix DropdownMenu.Root —
// per document, so the DOM (and menu-root state machines) grew linearly with the library. The list
// now virtualizes against the screen's `.content` scroll container once a real, laid-out viewport
// is resolved. jsdom has no layout, so we mock the viewport rect + clientHeight and the measured row
// height; the virtualizer then mounts only the rows in/near the viewport. TEETH: with windowing
// removed (render every row), the mounted-row count equals the doc count and the bounded assertion
// (and the "far row absent" assertion) fail.
describe('DocumentsScreen — list windowing (PERF-2)', () => {
  const VIEWPORT = 600
  const ROW = 57
  let content: HTMLDivElement
  // @tanstack/react-virtual measures the scroll element via clientHeight (since virtual-core 3.19;
  // offsetHeight before) and each row via offsetHeight, NOT getBoundingClientRect: all 0 under
  // jsdom. Feed it a real viewport + row height so it can compute a bounded range:
  // the `.content` scroll element → VIEWPORT, each measured row (a `[data-index]` wrapper) → ROW.
  let offsetHeightDesc: PropertyDescriptor | undefined

  beforeEach(() => {
    content = document.createElement('div')
    content.className = 'content'
    document.body.appendChild(content)
    Object.defineProperty(content, 'clientHeight', { configurable: true, value: VIEWPORT })
    offsetHeightDesc = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')
    Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
      configurable: true,
      get(this: HTMLElement) {
        if (this.classList?.contains('content')) return VIEWPORT
        if (this.hasAttribute?.('data-index')) return ROW
        return 0
      }
    })
  })

  afterEach(() => {
    if (offsetHeightDesc) Object.defineProperty(HTMLElement.prototype, 'offsetHeight', offsetHeightDesc)
    else delete (HTMLElement.prototype as unknown as { offsetHeight?: unknown }).offsetHeight
    content.remove()
  })

  it('mounts only a bounded slice of rows for a 1000-document library', async () => {
    const docs = Array.from({ length: 1000 }, (_, i) =>
      doc({ id: `d${i}`, title: `doc-${String(i).padStart(4, '0')}.pdf` })
    )
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => docs)
    }))
    render(<DocumentsScreen />, { container: content })

    // The first rows render (the windowed path shows real content, not a blank list)…
    expect(await screen.findByText('doc-0000.pdf')).toBeInTheDocument()

    // …while the mounted DocRow count is bounded by the viewport+overscan, NOT the 1000-doc library.
    await waitFor(() => {
      const mounted = content.querySelectorAll('.doc-row').length
      expect(mounted).toBeGreaterThan(5)
      expect(mounted).toBeLessThan(60)
    })
    // One Radix DropdownMenu trigger per mounted indexed row — bounded for the same reason (the
    // "hundreds of mounted menu roots" the audit flagged are gone).
    expect(content.querySelectorAll('.doc-row-menu-btn').length).toBeLessThan(60)

    // A row far past the viewport is NOT in the DOM — the defining property of windowing (and the
    // inherent find-in-page tradeoff: Ctrl+F can't match an un-rendered row).
    expect(screen.queryByText('doc-0900.pdf')).not.toBeInTheDocument()
  })

  it('renders every row (un-windowed) when no laid-out scroll viewport exists', async () => {
    // Render standalone (the default RTL container, NOT inside `.content`), so `closest('.content')`
    // finds nothing → the fallback path renders all (the pre-PERF-2 / existing-corpus behavior).
    const docs = Array.from({ length: 40 }, (_, i) => doc({ id: `e${i}`, title: `ed-${i}.pdf` }))
    stubApi(documentsScreenStubs({
      listCollections: vi.fn(async () => []),
      listDocuments: vi.fn(async () => docs)
    }))
    render(<DocumentsScreen />)
    expect(await screen.findByText('ed-0.pdf')).toBeInTheDocument()
    // All 40 mounted — windowing stayed off without a viewport.
    expect(screen.getByText('ed-39.pdf')).toBeInTheDocument()
  })
})

// ---- OCR-R P1 (ocr-audit 2026-07-18): OCR initiation + honest progress ------------------
// FE-1: a scan-detected document is by definition a FAILED row, and failed rows have no "⋯"
// overflow (§11.6) — so the only "Make searchable (OCR)" entry point (a menu item in the
// overflow) was unreachable and the scan banner pointed at a control that never rendered.
// The action is now an inline button on the failed row. FE-2: an already-OCR'd indexed PDF
// offers the D33 explicit redo in its overflow. FE-4/FE-5: the OCR busy row switches to an
// honest "Finishing…" label through the final re-ingest step, and a cancel click acknowledges
// the GAP-7 duality ("Stopping if possible…"). The behavioral tests were watched fail on the
// pre-fix tree (the two controls characterize behavior that must NOT change).
describe('DocumentsScreen — OCR initiation + progress (OCR-R P1)', () => {
  const scanDoc = (over: Partial<DocumentInfo> = {}): DocumentInfo =>
    doc({
      id: 'scan1',
      title: 'scan.pdf',
      status: 'failed',
      errorMessage: en['main.ingest.pdfScanDetected'],
      scanDetected: true,
      chunkCount: 0,
      ...over
    })
  const appStatus = (over: Partial<AppStatus> = {}): AppStatus => appStatusFixture({ ocrAvailable: true, ...over })
  const ocrStatus = (over: Partial<DocTaskStatus> = {}): DocTaskStatus => ({
    jobId: 'j1',
    kind: 'ocr',
    documentIds: ['scan1'],
    state: 'running',
    progress: { stepsDone: 0, stepsTotal: 0 },
    error: null,
    resultRef: null,
    ...over
  })
  // FE-4/FE-5 rows: drain the mount refresh and the doc-task poll under fake timers.
  const flush = async (): Promise<void> => {
    await act(async () => {
      for (let i = 0; i < 8; i++) await vi.advanceTimersByTimeAsync(0)
    })
  }

  it('FE-1: a scan-detected row offers an inline "Make searchable (OCR)" button that starts the task', async () => {
    const user = userEvent.setup()
    const startDocTask = vi.fn(async () => ({ jobId: 'j1' }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [scanDoc()]),
      getAppStatus: vi.fn(async () => appStatus()),
      startDocTask,
      getDocTask: vi.fn(async () => ocrStatus())
    }))
    render(<DocumentsScreen />)
    await screen.findByText('scan.pdf')
    // The banner's promise and the control agree: the button renders on the failed row itself.
    const btn = await screen.findByRole('button', { name: 'Make searchable (OCR)' })
    expect(btn).toBeEnabled()
    // #572: no "Try again" beside it — a retry re-parses the same scan and fails the same way.
    const row = screen.getByText('scan.pdf').closest('.doc-row') as HTMLElement
    expect(within(row).queryByRole('button', { name: 'Try again' })).not.toBeInTheDocument()
    expect(within(row).getByRole('button', { name: 'Remove' })).toBeInTheDocument()
    await user.click(btn)
    await waitFor(() =>
      expect(startDocTask).toHaveBeenCalledWith({ kind: 'ocr', documentIds: ['scan1'], params: undefined })
    )
  })

  it('FE-1 control: an ordinary failed row gains NO OCR button (strictly showOcr-gated)', async () => {
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({ id: 'd9', title: 'broken.pdf', status: 'failed', errorMessage: 'EIO: i/o error, read', chunkCount: 0 }),
        scanDoc()
      ]),
      getAppStatus: vi.fn(async () => appStatus())
    }))
    render(<DocumentsScreen />)
    await screen.findByText('broken.pdf')
    // The scan row's button appearing proves ocrAvailable has landed — and it is the ONLY one:
    // the non-scan failed row keeps exactly Try again + Remove (and still no overflow).
    await screen.findByRole('button', { name: 'Make searchable (OCR)' })
    expect(screen.getAllByRole('button', { name: 'Make searchable (OCR)' })).toHaveLength(1)
    const brokenRow = screen.getByText('broken.pdf').closest('.doc-row') as HTMLElement
    expect(within(brokenRow).getByRole('button', { name: 'Try again' })).toBeInTheDocument()
    expect(within(brokenRow).getByRole('button', { name: 'Remove' })).toBeInTheDocument()
    expect(
      within(brokenRow).queryByRole('button', { name: 'Make searchable (OCR)' })
    ).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /More actions/ })).not.toBeInTheDocument()
  })

  it('FE-1: without the OCR files the scan row explains (ocrMissing) and offers no button', async () => {
    stubApi(documentsScreenStubs({
      getOcrInstallStatus: vi.fn(async () => NO_OCR_SOURCES),
      getPolicy: vi.fn(async () => makePolicyStatus()),
      listDocuments: vi.fn(async () => [scanDoc()]),
      getAppStatus: vi.fn(async () => appStatus({ ocrAvailable: false }))
    }))
    render(<DocumentsScreen />)
    await screen.findByText('scan.pdf')
    expect(await screen.findByText(/needs the OCR files/)).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Make searchable (OCR)' })).not.toBeInTheDocument()
    // #572: nor "Try again" — only the OCR files and then Make searchable can help this row.
    expect(screen.queryByRole('button', { name: 'Try again' })).not.toBeInTheDocument()
    // No files → no "could not start" banner: that copy is reserved for a recognizer that exists
    // and cannot run (#232), never for a drive that simply lacks the language files.
    expect(screen.queryByText(/could not start/)).not.toBeInTheDocument()
  })

  // #232 / #219: the OCR files are on the drive but the packaged recognizer could not start
  // (`ocrAvailable: false`, `ocrState: 'unavailable'`). The scan row must not claim the files are
  // missing, the offer stays hidden, and the screen says so in a banner.
  it('#232: a recognizer that cannot run in this build explains itself (ocrUnavailable + banner), no button, no "files missing" copy', async () => {
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [scanDoc()]),
      getAppStatus: vi.fn(async () => appStatus({ ocrAvailable: false, ocrState: 'unavailable' }))
    }))
    render(<DocumentsScreen />)
    await screen.findByText('scan.pdf')
    expect(await screen.findByText(/which could not start in this build/)).toBeInTheDocument()
    expect(screen.getByText(/is not available in this build/)).toBeInTheDocument()
    expect(screen.queryByText(/needs the OCR files/)).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Make searchable (OCR)' })).not.toBeInTheDocument()
  })

  it('#232: while the packaged probe is still running nothing is offered and nothing is claimed — and the verdict is re-read', async () => {
    // First read: probe pending. Second read (the screen re-polls while 'probing'): passed.
    const getAppStatus = vi
      .fn()
      .mockResolvedValueOnce(appStatus({ ocrAvailable: false, ocrState: 'probing' }))
      .mockResolvedValue(appStatus({ ocrAvailable: true, ocrState: 'available' }))
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [scanDoc()]), getAppStatus }))
    render(<DocumentsScreen />)
    await screen.findByText('scan.pdf')
    expect(screen.queryByRole('button', { name: 'Make searchable (OCR)' })).not.toBeInTheDocument()
    expect(screen.queryByText(/is not available in this build/)).not.toBeInTheDocument()
    // Pending ≠ missing: the "files are not on this drive" copy must not show either.
    expect(screen.queryByText(/needs the OCR files/)).not.toBeInTheDocument()
    // The re-read (1.5 s cadence) lands the verdict without a remount.
    expect(
      await screen.findByRole('button', { name: 'Make searchable (OCR)' }, { timeout: hangBudgetMs(6_000) })
    ).toBeInTheDocument()
    expect(getAppStatus.mock.calls.length).toBeGreaterThanOrEqual(2)
  })

  it('FE-1: the inline OCR button disables while another task is active', async () => {
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [scanDoc(), doc({ id: 'd2', title: 'other.pdf' })]),
      getAppStatus: vi.fn(async () => appStatus()),
      startDocTask: vi.fn(async () => ({ jobId: 'j-sum' })),
      getDocTask: vi.fn(async () => ocrStatus({ jobId: 'j-sum', kind: 'summary', documentIds: ['d2'] }))
    }))
    render(<DocumentsScreen />)
    const btn = await screen.findByRole('button', { name: 'Make searchable (OCR)' })
    expect(btn).toBeEnabled()
    await act(async () => {
      await startTask('summary', 'd2')
    })
    expect(screen.getByRole('button', { name: 'Make searchable (OCR)' })).toBeDisabled()
  })

  it('FE-2: an already-OCR\'d indexed PDF offers "Read again (OCR)" in its overflow, and it starts the task', async () => {
    const user = userEvent.setup()
    const startDocTask = vi.fn(async () => ({ jobId: 'j-redo' }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({
          ocr: { pageCount: 2, languages: ['deu', 'eng'], engineId: 'tesseract.js-7.0.0', createdAt: '2026-01-01T00:00:00Z' }
        })
      ]),
      getAppStatus: vi.fn(async () => appStatus()),
      startDocTask,
      getDocTask: vi.fn(async () => ocrStatus({ jobId: 'j-redo', documentIds: ['d1'] }))
    }))
    render(<DocumentsScreen />)
    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Read again (OCR)' }))
    await waitFor(() =>
      expect(startDocTask).toHaveBeenCalledWith({ kind: 'ocr', documentIds: ['d1'], params: undefined })
    )
  })

  it('FE-2 control: a plain indexed row (no stored recognition) offers no redo item', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({
          id: 'dOcr',
          title: 'recognized.pdf',
          ocr: { pageCount: 2, languages: ['deu'], engineId: 'tesseract.js-7.0.0', createdAt: '2026-01-01T00:00:00Z' }
        }),
        doc({ id: 'd2', title: 'plain.pdf' })
      ]),
      getAppStatus: vi.fn(async () => appStatus())
    }))
    render(<DocumentsScreen />)
    await screen.findByText('plain.pdf')
    // Seeing the redo item on the OCR'd row first proves ocrAvailable has landed…
    await user.click(screen.getByRole('button', { name: 'More actions for recognized.pdf' }))
    await screen.findByRole('menuitem', { name: 'Read again (OCR)' })
    await user.keyboard('{Escape}')
    // …so its absence from the plain row's menu is meaningful, not a race.
    await user.click(screen.getByRole('button', { name: 'More actions for plain.pdf' }))
    await screen.findByRole('menuitem', { name: 'Re-index' })
    expect(screen.queryByRole('menuitem', { name: 'Read again (OCR)' })).not.toBeInTheDocument()
  })

  // #576 + #538 — the OCR metadata in words. The preview counts the pages that produced text (a
  // blank page read by OCR is not "recognized"), and pages the recognizer was unsure of are named
  // quietly on the row and, with their causes and "Read again (OCR)", in the preview.
  it('#576/#538: the preview counts the pages with text; an unsure reading is named on the row and in the preview, with Read again', async () => {
    const user = userEvent.setup()
    const startDocTask = vi.fn(async () => ({ jobId: 'j-redo' }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({
          ocr: {
            pageCount: 3,
            textPageCount: 2,
            lowConfidencePageCount: 1,
            languages: ['deu'],
            engineId: 'tesseract.js-7.0.0',
            createdAt: '2026-01-01T00:00:00Z'
          }
        })
      ]),
      getAppStatus: vi.fn(async () => appStatus()),
      previewDocument: vi.fn(async () => ({
        id: 'd1',
        title: 'contract.pdf',
        mimeType: 'application/pdf',
        segments: [{ text: 'Erste Seite.', pageNumber: 1, sectionLabel: null }]
      })),
      startDocTask,
      getDocTask: vi.fn(async () => ocrStatus({ jobId: 'j-redo', documentIds: ['d1'] }))
    }))
    render(<DocumentsScreen />)
    const unsure = translate('en', 'docs.ocr.unsure.some', { count: 1, total: 2 })
    expect(await screen.findByText(unsure)).toBeInTheDocument() // the row caption

    await user.click(screen.getByRole('button', { name: /preview/i }))
    const dialog = await screen.findByRole('dialog')
    expect(
      within(dialog).getByText(translate('en', 'docs.previewModal.ocrInfoPartial', { count: 2, total: 3 }))
    ).toBeInTheDocument()
    expect(within(dialog).getByText(new RegExp(unsure.replace(/[.]/g, '\\.')))).toBeInTheDocument()
    await user.click(within(dialog).getByRole('button', { name: 'Read again (OCR)' }))
    await waitFor(() =>
      expect(startDocTask).toHaveBeenCalledWith({ kind: 'ocr', documentIds: ['d1'], params: undefined })
    )
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
  })

  // #574 — a photo read by OCR on import now carries OCR metadata: the preview says so, and its
  // "Read again (OCR)" re-reads the stored photo — a re-index; the OCR task is PDF-only and would
  // refuse it.
  it('#574: a photo read by OCR has the photo caveat, and Read again (OCR) re-indexes it', async () => {
    const user = userEvent.setup()
    const startDocTask = vi.fn(async () => ({ jobId: 'never' }))
    const photo = doc({
      id: 'p1',
      title: 'receipt.jpg',
      mimeType: 'image/jpeg',
      chunkCount: 1,
      ocr: {
        pageCount: 1,
        textPageCount: 1,
        lowConfidencePageCount: 0,
        languages: ['deu', 'eng'],
        engineId: 'tesseract.js-7.0.0',
        createdAt: '2026-10-05T00:00:00Z'
      }
    })
    const reindexDocument = vi.fn(async () => photo)
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [photo]),
      getAppStatus: vi.fn(async () => appStatus()),
      previewDocument: vi.fn(async () => ({
        id: 'p1',
        title: 'receipt.jpg',
        mimeType: 'image/jpeg',
        segments: [{ text: 'Quittung über 42 Euro.', pageNumber: null, sectionLabel: null }]
      })),
      startDocTask,
      reindexDocument
    }))
    render(<DocumentsScreen />)
    await screen.findByText('receipt.jpg')
    await user.click(screen.getByRole('button', { name: /preview/i }))
    const dialog = await screen.findByRole('dialog')
    expect(within(dialog).getByText(en['docs.previewModal.ocrInfoPhoto'])).toBeInTheDocument()
    await user.click(within(dialog).getByRole('button', { name: /close/i }))
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())

    await user.click(screen.getByRole('button', { name: 'More actions for receipt.jpg' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Read again (OCR)' }))
    await waitFor(() => expect(reindexDocument).toHaveBeenCalledWith('p1'))
    expect(startDocTask).not.toHaveBeenCalled()
  })

  // #575 — a text PDF with scanned pages: until OCR reads them, a quiet caption says how many and
  // the ⋯ menu offers "Make searchable (OCR)"; once read, the caption goes and the preview counts
  // the recognized pages against the whole document.
  it('#575: scanned pages in a text PDF are named on the row and offered OCR; once read, the preview counts them against the document', async () => {
    const user = userEvent.setup()
    const startDocTask = vi.fn(async () => ({ jobId: 'j-575' }))
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({ id: 'unread', title: 'letter.pdf', scannedPages: { count: 2, pageCount: 3 } }),
        doc({
          id: 'read',
          title: 'contract.pdf',
          scannedPages: { count: 2, pageCount: 3 },
          ocr: {
            pageCount: 2,
            textPageCount: 2,
            languages: ['deu'],
            engineId: 'tesseract.js-7.0.0',
            createdAt: '2026-10-05T00:00:00Z'
          }
        })
      ]),
      getAppStatus: vi.fn(async () => appStatus()),
      previewDocument: vi.fn(async () => ({
        id: 'read',
        title: 'contract.pdf',
        mimeType: 'application/pdf',
        segments: [{ text: 'Seite 1.', pageNumber: 1, sectionLabel: null }]
      })),
      startDocTask,
      getDocTask: vi.fn(async () => ocrStatus({ jobId: 'j-575', documentIds: ['unread'] }))
    }))
    render(<DocumentsScreen />)
    const caption = translate('en', 'docs.ocr.scannedPages', { count: 2, total: 3 })
    expect(await screen.findAllByText(caption)).toHaveLength(1) // the unread row only

    const readRow = screen.getByText('contract.pdf').closest('.doc-row') as HTMLElement
    await user.click(within(readRow).getByRole('button', { name: /preview/i }))
    const dialog = await screen.findByRole('dialog')
    expect(
      within(dialog).getByText(translate('en', 'docs.previewModal.ocrInfoPartial', { count: 2, total: 3 }))
    ).toBeInTheDocument()
    await user.click(within(dialog).getByRole('button', { name: /close/i }))
    await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())

    await user.click(screen.getByRole('button', { name: 'More actions for letter.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Make searchable (OCR)' }))
    await waitFor(() =>
      expect(startDocTask).toHaveBeenCalledWith({ kind: 'ocr', documentIds: ['unread'], params: undefined })
    )
  })

  // #575 review L5: only missing files earn "needs the OCR files" — files that are present but whose
  // recognizer cannot run (or is still being proven) are not "missing".
  it.each([
    ['missing', true],
    ['unavailable', false],
    ['probing', false]
  ] as const)('#575: with OCR %s, the scanned-pages caption names the OCR files: %s', async (ocrState, named) => {
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({ title: 'letter.pdf', scannedPages: { count: 2, pageCount: 3 } })]),
      getAppStatus: vi.fn(async () => appStatus({ ocrAvailable: false, ocrState }))
    }))
    render(<DocumentsScreen />)
    const caption = translate('en', 'docs.ocr.scannedPages', { count: 2, total: 3 })
    const row = (await screen.findByText(new RegExp(caption.replace(/[.]/g, '\\.')))).closest('p') as HTMLElement
    await waitFor(() =>
      expect(row.textContent?.includes(en['docs.ocr.scannedPagesNeedsOcr'])).toBe(named)
    )
  })

  it('FE-4: the OCR busy label switches to "Finishing…" on the final re-ingest step; Cancel stays enabled', async () => {
    vi.useFakeTimers()
    try {
      stubApi(documentsScreenStubs({
        listDocuments: vi.fn(async () => [scanDoc()]),
        getAppStatus: vi.fn(async () => appStatus()),
        startDocTask: vi.fn(async () => ({ jobId: 'j1' })),
        // stepsDone = pages (3) of stepsTotal = pages + 1 — the signal-less re-ingest step.
        getDocTask: vi.fn(async () => ocrStatus({ progress: { stepsDone: 3, stepsTotal: 4 } }))
      }))
      render(<DocumentsScreen />)
      await flush() // mount refresh + ocr status
      await act(async () => {
        await startTask('ocr', 'scan1')
      })
      await act(async () => {
        await vi.advanceTimersByTimeAsync(400) // first poll → the finishing-step status
      })
      await flush()
      expect(screen.getByText('Finishing — making the text searchable…')).toBeInTheDocument()
      expect(screen.queryByText(/Reading the scan/)).not.toBeInTheDocument()
      // A legitimately cancellable pre-persist instant shares this renderer-visible state
      // (handlers/ocr.ts) — Cancel must stay ENABLED, never hard-disabled.
      expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled()
    } finally {
      vi.useRealTimers()
    }
  })

  it('FE-5: a cancel click flips the button to a disabled "Stopping if possible…"', async () => {
    vi.useFakeTimers()
    try {
      const cancelDocTask = vi.fn(async () => undefined)
      stubApi(documentsScreenStubs({
        listDocuments: vi.fn(async () => [scanDoc()]),
        getAppStatus: vi.fn(async () => appStatus()),
        startDocTask: vi.fn(async () => ({ jobId: 'j1' })),
        getDocTask: vi.fn(async () => ocrStatus({ progress: { stepsDone: 3, stepsTotal: 4 } })),
        cancelDocTask
      }))
      render(<DocumentsScreen />)
      await flush()
      await act(async () => {
        await startTask('ocr', 'scan1')
      })
      await act(async () => {
        await vi.advanceTimersByTimeAsync(400)
      })
      await flush()
      fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
      await flush()
      // Honest about the GAP-7 duality: the cancel may or may not land (a cancel during the
      // final re-ingest is deliberately ignored) — say so, and stop offering the dead click.
      const stopping = screen.getByRole('button', { name: 'Stopping if possible…' })
      expect(stopping).toBeDisabled()
      expect(cancelDocTask).toHaveBeenCalled()
    } finally {
      vi.useRealTimers()
    }
  })

  it('FE-4 control: a mid-pages status still reads "Reading the scan… (k/n)"', async () => {
    vi.useFakeTimers()
    try {
      stubApi(documentsScreenStubs({
        listDocuments: vi.fn(async () => [scanDoc()]),
        getAppStatus: vi.fn(async () => appStatus()),
        startDocTask: vi.fn(async () => ({ jobId: 'j1' })),
        getDocTask: vi.fn(async () => ocrStatus({ progress: { stepsDone: 1, stepsTotal: 4 } }))
      }))
      render(<DocumentsScreen />)
      await flush()
      await act(async () => {
        await startTask('ocr', 'scan1')
      })
      await act(async () => {
        await vi.advanceTimersByTimeAsync(400)
      })
      await flush()
      expect(screen.getByText('Reading the scan… (1/4)')).toBeInTheDocument()
      expect(screen.queryByText(/Finishing/)).not.toBeInTheDocument()
    } finally {
      vi.useRealTimers()
    }
  })
})

// ---- Issue #90: "Export original file" for imported documents ------------------------------
// The old `d.origin && …` gate meant IMPORTED documents (the common case) had no export action
// at all — only generated docs saw the text "Export". Imported docs now get "Export original
// file" (any format, original bytes) behind the encryption-boundary warning ConfirmDialog;
// generated docs keep the text export unchanged (its Markdown semantics serve translations).
describe('DocumentsScreen — export original file (#90)', () => {
  it('offers "Export original file" on an imported doc, behind the encryption warning', async () => {
    const user = userEvent.setup()
    const exportDocumentOriginal = vi.fn(async () => 'C:/out/contract.pdf')
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), exportDocumentOriginal }))
    render(<DocumentsScreen />)

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Export original file' }))
    // The warning ConfirmDialog is the in-app voice of the encryption boundary (the
    // review.export.encryptionWarning precedent) — nothing exports before it is confirmed.
    expect(exportDocumentOriginal).not.toHaveBeenCalled()
    const dialog = await screen.findByRole('dialog')
    expect(dialog).toHaveTextContent(/not protected by your workspace password/)
    await user.click(within(dialog).getByRole('button', { name: 'Export original file' }))
    await waitFor(() => expect(exportDocumentOriginal).toHaveBeenCalledWith('d1'))
  })

  it('cancelling the warning dialog exports nothing', async () => {
    const user = userEvent.setup()
    const exportDocumentOriginal = vi.fn(async () => null)
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), exportDocumentOriginal }))
    render(<DocumentsScreen />)

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Export original file' }))
    const dialog = await screen.findByRole('dialog')
    await user.click(within(dialog).getByRole('button', { name: 'Cancel' }))
    expect(exportDocumentOriginal).not.toHaveBeenCalled()
    expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
  })

  it('a generated doc keeps the text "Export" and does NOT offer the original export', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [
        doc({
          id: 'g1',
          title: 'contract (Deutsch).md',
          origin: { kind: 'translation', sourceDocumentIds: ['d1'], createdAt: '2026-01-01T00:00:00Z' }
        })
      ])
    }))
    render(<DocumentsScreen />)

    await screen.findByText('contract (Deutsch).md')
    await user.click(
      screen.getByRole('button', { name: 'More actions for contract (Deutsch).md' })
    )
    expect(await screen.findByRole('menuitem', { name: 'Export' })).toBeInTheDocument()
    expect(
      screen.queryByRole('menuitem', { name: 'Export original file' })
    ).not.toBeInTheDocument()
  })
})

// ---- #194: feedback for the two blocking single-document actions -----------------------------
// Found on the real relocated drive during the #190 continuity check: the operator clicked
// "Neu aufbereiten" (Re-index) on one document and got nothing — no success signal, no progress,
// no error — while the re-index had in fact SUCCEEDED. All three channels are asserted here, on
// the shared `run()` helper (re-index AND delete), because a silent success is indistinguishable
// from a no-op and that is the whole defect.
describe('DocumentsScreen — single-document action feedback (#194)', () => {
  it('a successful single-document re-index toasts, naming the document', async () => {
    const user = userEvent.setup()
    const reindexDocument = vi.fn(async () => doc({}))
    stubApi(documentsScreenStubs({ listDocuments: vi.fn(async () => [doc({})]), reindexDocument }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Re-index' }))
    await waitFor(() => expect(reindexDocument).toHaveBeenCalledWith('d1'))
    // The guard: an already-healthy document redraws an IDENTICAL list, so this toast is the
    // only thing distinguishing "it worked" from "nothing happened". Deleting the showToast
    // call in `run()` turns exactly this line red.
    expect(
      await screen.findByText('“contract.pdf” re-indexed.', {}, { timeout: hangBudgetMs(5000) })
    ).toBeInTheDocument()
  })

  it('a successful single-document delete toasts too (the shared helper, not a re-index special case)', async () => {
    const user = userEvent.setup()
    const deleteDocument = vi.fn(async () => {})
    const listDocuments = vi
      .fn<() => Promise<DocumentInfo[]>>()
      .mockResolvedValueOnce([doc({})])
      .mockResolvedValue([])
    stubApi(documentsScreenStubs({ listDocuments, deleteDocument }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: /delete/i }))
    const dialog = await screen.findByRole('dialog')
    await user.click(within(dialog).getByRole('button', { name: /^delete$/i }))
    await waitFor(() => expect(deleteDocument).toHaveBeenCalledWith('d1'))
    expect(
      await screen.findByText('“contract.pdf” deleted.', {}, { timeout: hangBudgetMs(5000) })
    ).toBeInTheDocument()
  })

  it('while a re-index runs, ONLY that row shows the spinner — not the whole list (gap 2)', async () => {
    const user = userEvent.setup()
    // Hold the invoke open so the in-flight state is observable: pre-fix the ONLY signal was
    // `disabled={busy !== null}` on every row, i.e. nothing said which row was working, or that
    // anything was working at all.
    let release: (() => void) | null = null
    const reindexDocument = vi.fn(
      () => new Promise<DocumentInfo>((resolve) => { release = () => resolve(doc({})) })
    )
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({}), doc({ id: 'd2', title: 'terms.docx' })]),
      reindexDocument
    }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Re-index' }))

    // The clicked row says what is happening; the sibling row keeps its ordinary actions.
    const busyRow = (await screen.findByText('contract.pdf')).closest('.doc-row') as HTMLElement
    const otherRow = screen.getByText('terms.docx').closest('.doc-row') as HTMLElement
    expect(await within(busyRow).findByText('Re-indexing…')).toBeInTheDocument()
    expect(within(otherRow).queryByText('Re-indexing…')).not.toBeInTheDocument()
    expect(within(otherRow).getByRole('button', { name: /^preview$/i })).toBeInTheDocument()

    await act(async () => { release?.() })
    await waitFor(() => expect(screen.queryByText('Re-indexing…')).not.toBeInTheDocument())
  })

  it('a failed single-document re-index names the document on the banner (#188 D-3, recurring)', async () => {
    const user = userEvent.setup()
    const reindexDocument = vi.fn(async () => {
      throw new Error("Error invoking remote method 'reindexDocument': Error: The document file is no longer present.")
    })
    stubApi(documentsScreenStubs({
      listDocuments: vi.fn(async () => [doc({}), doc({ id: 'd2', title: 'terms.docx' })]),
      reindexDocument
    }))
    render(
      <ToastProvider>
        <DocumentsScreen />
      </ToastProvider>
    )

    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: 'More actions for contract.pdf' }))
    await user.click(await screen.findByRole('menuitem', { name: 'Re-index' }))
    // The screen-level banner sits above a list the user may have scrolled away from, so the
    // message has to carry the document itself — the fix #188 made for "Export original file"
    // and did not sweep onto its neighbours. No success toast on a failure.
    expect(
      await screen.findByText('contract.pdf: The document file is no longer present.')
    ).toBeInTheDocument()
    expect(screen.queryByText('“contract.pdf” re-indexed.')).not.toBeInTheDocument()
  })
})

// #828: every project list follows the interface language's collation, not the code-point order
// main returns. The fixtures are handed over in code-point order, as `listCollections` returns them.
describe.each(PROJECT_ORDER_CASES)('DocumentsScreen project order (%s)', (lang, sqlOrder) => {
  const expected = inLanguageOrder(lang, sqlOrder)
  // The screen's mount-time reads, answered with nothing in flight.
  const quiet = {
    getAppStatus: vi.fn(async () => appStatusFixture()),
    getReindexAllJob: vi.fn(async () => null),
    getActiveImportJob: vi.fn(async () => null)
  }

  afterEach(() => {
    cleanup()
    clearDocTaskSession()
  })

  it('the fixture order differs from the code-point order and from the en order', () => {
    expect(expected).not.toEqual(sqlOrder)
    expect(expected).not.toEqual(inLanguageOrder('en', sqlOrder))
  })

  it('lists the rail projects in the language order', async () => {
    stubApi(documentsScreenStubs({
      ...quiet,
      listCollections: vi.fn(async () => sqlOrder.map((n, i) => coll({ id: `a${i}`, name: n }))),
      listDocuments: vi.fn(async () => [doc({})])
    }))
    const { container } = renderInLanguage(<DocumentsScreen />, lang)
    await screen.findByRole('button', { name: new RegExp(sqlOrder[0]!) })
    const names = [...container.querySelectorAll('.docs-rail-project:not(.archived) .docs-rail-item')].map((b) =>
      (b.textContent ?? '').replace(/\d+$/, '').trim()
    )
    expect(names).toEqual(expected)
  })

  it('lists the archived rail projects in the language order', async () => {
    stubApi(documentsScreenStubs({
      ...quiet,
      listCollections: vi.fn(async () =>
        sqlOrder.map((n, i) => coll({ id: `r${i}`, name: n, archivedAt: '2026-02-01T00:00:00Z' }))
      ),
      listDocuments: vi.fn(async () => [doc({})])
    }))
    const { container } = renderInLanguage(<DocumentsScreen />, lang)
    await screen.findByRole('button', { name: new RegExp(sqlOrder[0]!) })
    const names = [...container.querySelectorAll('.docs-rail-project.archived .docs-rail-item')].map((b) =>
      (b.textContent ?? '').replace(/\d+$/, '').trim()
    )
    expect(names).toEqual(expected)
  })

  it('lists the projects of the "Choose a project" window in the language order', async () => {
    const user = userEvent.setup()
    stubApi(documentsScreenStubs({
      ...quiet,
      listCollections: vi.fn(async () => sqlOrder.map((n, i) => coll({ id: `m${i}`, name: n }))),
      listDocuments: vi.fn(async () => [doc({})])
    }))
    renderInLanguage(<DocumentsScreen />, lang)
    await screen.findByText('contract.pdf')
    await user.click(screen.getByRole('button', { name: translate(lang, 'docs.moreActions', { title: 'contract.pdf' }) }))
    await user.click(await screen.findByRole('menuitem', { name: translate(lang, 'docs.action.moveToProject') }))
    const dialog = await screen.findByRole('dialog')
    const names = within(dialog)
      .getAllByRole('button')
      .map((b) => (b.textContent ?? '').trim())
      .filter((n) => sqlOrder.includes(n))
    expect(names).toEqual(expected)
  })
})