AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
// @vitest-environment jsdom
import { describe, it, expect, vi, afterEach } from 'vitest'
import { render, screen, cleanup, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { CoverageMeter } from '../../src/renderer/components'
import { DocumentsScreen } from '../../src/renderer/screens/DocumentsScreen'
import { I18nProvider } from '../../src/renderer/i18n'
import { clearDocTaskSession } from '../../src/renderer/lib/doctasks'
import { t } from '../../src/shared/i18n'
import type { CoverageInfo, DocTaskStatus, DocumentCoverage, DocumentInfo } from '../../src/shared/types'
import { makeCitations, makeMessage } from '../helpers/chat-fixtures'
import { renderInLanguage } from '../helpers/render-language'
import { stubApi, assertNoUnexpectedApiCalls } from '../helpers/renderer'
import { documentsScreenStubs } from '../helpers/documents-screen'
import { renderTranscript } from '../helpers/transcript'
// Whole-document-analysis Phase 2 renderer tests: the coverage meter's HONESTY (breadth ≠
// fidelity, never "100%" unless a deep index is ready), the "Build deep index" / "Re-index
// first" row action (C4 gate), and the relevance label on a grounded chat answer.
afterEach(() => {
cleanup()
clearDocTaskSession()
vi.restoreAllMocks()
// Keep the UI-language / rail keys from leaking between rows.
window.localStorage.clear()
assertNoUnexpectedApiCalls()
})
function meter(coverage: CoverageInfo): JSX.Element {
return (
<I18nProvider>
<CoverageMeter coverage={coverage} />
</I18nProvider>
)
}
describe('CoverageMeter — breadth ≠ fidelity honesty (C1/L2)', () => {
// D72 (#24): a relevance answer that stamped real section counts shows the fraction line,
// NOT the flat honesty label. Multi-doc scopes stay honest via wording (never "whole document").
it('a counted relevance answer shows the "based on N of M sections" fraction', () => {
render(meter({ mode: 'relevance', chunksCovered: 3, chunksTotal: 12, fullyChunked: true }))
expect(
screen.getByText(t('en', 'coverage.relevance.counted', { covered: 3, total: 12 }))
).toBeInTheDocument()
// The flat legacy label is NOT shown once counts are present.
expect(screen.queryByText(t('en', 'coverage.relevance'))).not.toBeInTheDocument()
})
// The NULL/legacy fallback (Transcript.tsx passes chunksTotal:0) keeps the flat label
// byte-identical — no fraction line.
it('a NULL/legacy relevance turn (chunksTotal===0) keeps the flat honesty label byte-identically', () => {
render(meter({ mode: 'relevance', chunksCovered: 0, chunksTotal: 0 }))
expect(screen.getByText(t('en', 'coverage.relevance'))).toBeInTheDocument()
expect(
screen.queryByText(t('en', 'coverage.relevance.counted', { covered: 0, total: 0 }))
).not.toBeInTheDocument()
})
it('a ready deep index shows "whole document (deeply indexed)" PLUS the tier depth', () => {
render(
meter({ mode: 'tree', treeStatus: 'ready', chunksCovered: 10, chunksTotal: 10, tier: 1, treeLevels: 2 })
)
expect(screen.getByText(t('en', 'coverage.tree.whole'))).toBeInTheDocument()
expect(
screen.getByText(t('en', 'coverage.depth', { label: t('en', 'coverage.tier.1') }))
).toBeInTheDocument()
})
it('a READY deep index that was TRUNCATED covers "the beginning", never the whole document (§2.2)', () => {
// The tree rescue hit its map-call ceiling / clamped its notes: every leaf is reachable
// (chunksCovered == chunksTotal) but the answer only covers the beginning, so the badge must NOT
// claim whole-document coverage on the leaf-fraction alone.
render(
meter({ mode: 'tree', treeStatus: 'ready', chunksCovered: 10, chunksTotal: 10, truncated: true })
)
expect(screen.getByText(t('en', 'coverage.tree.beginning'))).toBeInTheDocument()
expect(screen.queryByText(t('en', 'coverage.tree.whole'))).not.toBeInTheDocument()
})
it('a BUILDING deep index shows the partial fraction, NEVER the whole-document claim', () => {
render(meter({ mode: 'tree', treeStatus: 'building', chunksCovered: 3, chunksTotal: 10, truncated: true }))
expect(
screen.getByText(t('en', 'coverage.tree.partial', { covered: 3, total: 10 }))
).toBeInTheDocument()
expect(screen.queryByText(t('en', 'coverage.tree.whole'))).not.toBeInTheDocument()
})
it('a capped summary never renders as complete (covers the beginning when truncated)', () => {
render(meter({ mode: 'capped', chunksCovered: 7, chunksTotal: 7, truncated: true }))
expect(screen.getByText(t('en', 'coverage.capped.beginning'))).toBeInTheDocument()
expect(screen.queryByText(t('en', 'coverage.tree.whole'))).not.toBeInTheDocument()
})
// Phase 3 — structured-extract listing honesty (H7): "sections scanned (k unparsed)",
// gated whole-document wording, NEVER "complete".
it('an extract listing over a fully-indexed doc says "whole document", never "complete"', () => {
render(meter({ mode: 'extract', chunksCovered: 213, chunksTotal: 213, fullyChunked: true }))
expect(
screen.getByText(t('en', 'coverage.extract.whole', { scanned: 213 }))
).toBeInTheDocument()
expect(screen.queryByText(/complete/i)).not.toBeInTheDocument()
})
it('an extract listing surfaces unparsed sections and never claims the whole document when not fully chunked', () => {
render(
meter({ mode: 'extract', chunksCovered: 50, chunksTotal: 50, unparsedChunks: 3, fullyChunked: false })
)
expect(
screen.getByText(t('en', 'coverage.extract.sectionsUnparsed', { scanned: 50, unparsed: 3 }))
).toBeInTheDocument()
expect(screen.queryByText(t('en', 'coverage.extract.whole', { scanned: 50 }))).not.toBeInTheDocument()
})
// #806: each counted badge reads right at 1 and at 2, in English and German ("Based on 1 of 1
// sections", "Read across 1 sections scanned" before).
const BADGES: Array<[string, (n: number) => CoverageInfo, Record<'en' | 'de', (n: number) => string>]> = [
[
'a counted relevance answer',
(n) => ({ mode: 'relevance', chunksCovered: 1, chunksTotal: n, fullyChunked: true }),
{ en: (n) => `Based on sections: 1 of ${n}`, de: (n) => `Basiert auf Abschnitten: 1 von ${n}` }
],
[
'an extract over the whole document',
(n) => ({ mode: 'extract', chunksCovered: n, chunksTotal: n, fullyChunked: true }),
{
en: (n) => `Read across the whole document — sections scanned: ${n}`,
de: (n) => `Im ganzen Dokument gelesen — durchsuchte Abschnitte: ${n}`
}
],
[
'an extract over the whole document with an unreadable section',
(n) => ({ mode: 'extract', chunksCovered: n, chunksTotal: n, unparsedChunks: 1, fullyChunked: true }),
{
en: (n) => `Read across the whole document — sections scanned: ${n}, could not be read: 1`,
de: (n) => `Im ganzen Dokument gelesen — durchsuchte Abschnitte: ${n}, nicht lesbar: 1`
}
],
[
'an extract over some sections',
(n) => ({ mode: 'extract', chunksCovered: n, chunksTotal: n, fullyChunked: false }),
{ en: (n) => `Sections scanned: ${n}`, de: (n) => `Durchsuchte Abschnitte: ${n}` }
],
[
'an extract over some sections with an unreadable one',
(n) => ({ mode: 'extract', chunksCovered: n, chunksTotal: n, unparsedChunks: 1, fullyChunked: false }),
{
en: (n) => `Sections scanned: ${n}, could not be read: 1`,
de: (n) => `Durchsuchte Abschnitte: ${n}, nicht lesbar: 1`
}
]
]
it.each(
(['en', 'de'] as const).flatMap((code) =>
BADGES.flatMap(([title, coverage, text]) => [1, 2].map((n) => [code, title, n, coverage, text] as const))
)
)('%s: %s at %i shows the count label-first (#806)', (code, _title, n, coverage, text) => {
renderInLanguage(<CoverageMeter coverage={coverage(n)} />, code)
expect(screen.getByText(text[code](n))).toBeInTheDocument()
})
})
describe('Transcript — a grounded answer is labelled relevance-based', () => {
it('renders the "most relevant passages — not the whole document" label under the answer', () => {
renderTranscript({
messages: [makeMessage({ content: 'The payment is due in 30 days [S1].', citations: makeCitations(1) })]
})
expect(screen.getByText(t('en', 'coverage.relevance'))).toBeInTheDocument()
})
// Full-doc-skills Phase 1 (D48): the meter is data-driven. A message carrying a PERSISTED
// coverage renders THAT breadth; a citation-bearing message with no coverage (NULL / pre-migration)
// still falls back to the relevance label — byte-identical to the pre-Phase-1 hardcoded behaviour.
it('renders the PERSISTED coverage when a message carries one (extract → whole document)', () => {
const answer = makeMessage({
content: 'There are 213 transactions [S1].',
citations: makeCitations(1),
coverage: { mode: 'extract', chunksCovered: 213, chunksTotal: 213, fullyChunked: true }
})
renderTranscript({ messages: [answer] })
expect(screen.getByText(t('en', 'coverage.extract.whole', { scanned: 213 }))).toBeInTheDocument()
expect(screen.queryByText(t('en', 'coverage.relevance'))).not.toBeInTheDocument()
})
it('does not label a plain (citation-free) answer', () => {
renderTranscript({ messages: [makeMessage({ content: 'Hello there.' })] })
expect(screen.queryByText(t('en', 'coverage.relevance'))).not.toBeInTheDocument()
})
})
describe('DocumentsScreen — Build deep index + C4 gate', () => {
function doc(over: Partial<DocumentInfo> = {}): DocumentInfo {
return {
id: 'd1',
title: 'report.pdf',
originalPath: null,
mimeType: 'application/pdf',
sizeBytes: 4096,
status: 'indexed',
errorMessage: null,
chunkCount: 40,
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-01T00:00:00Z',
...over
}
}
function task(over: Partial<DocTaskStatus> = {}): DocTaskStatus {
return {
jobId: 'j1',
kind: 'tree',
documentIds: ['d1'],
state: 'running',
progress: { stepsDone: 0, stepsTotal: 0 },
error: null,
resultRef: null,
...over
}
}
it('offers "Build deep index" on a fully-chunked doc with no tree, and starts a tree task that chains the extract pass (#38)', async () => {
const user = userEvent.setup()
const startDocTask = vi.fn(async () => ({ jobId: 'j1' }))
stubApi(documentsScreenStubs({
listDocuments: vi.fn(async () => [doc({ fullyChunked: true, treeStatus: null })]),
startDocTask,
getDocTask: vi.fn(async () => task({ state: 'running' }))
}))
render(<DocumentsScreen />)
await screen.findByText('report.pdf')
// "Build deep index" now lives in the per-row "⋯" overflow (§11.6).
await user.click(screen.getByRole('button', { name: t('en', 'docs.moreActions', { title: 'report.pdf' }) }))
await user.click(await screen.findByRole('menuitem', { name: t('en', 'docs.deepIndex.build') }))
// #38: one user concept, two passes — the backend chains the extract after the tree.
expect(startDocTask).toHaveBeenCalledWith({
kind: 'tree',
documentIds: ['d1'],
params: { withExtract: true }
})
})
it('a tree-ready doc whose extract pass is missing re-offers the action and starts JUST the extract (#38)', async () => {
const user = userEvent.setup()
const startDocTask = vi.fn(async () => ({ jobId: 'j2' }))
stubApi(documentsScreenStubs({
listDocuments: vi.fn(async () => [
doc({ fullyChunked: true, treeStatus: 'ready', extractStatus: null })
]),
startDocTask,
getDocTask: vi.fn(async () => task({ jobId: 'j2', kind: 'extract', state: 'running' }))
}))
render(<DocumentsScreen />)
await screen.findByText('report.pdf')
// The deep index is INCOMPLETE (tree ready, extract missing) — no "Deeply indexed" badge yet.
expect(screen.queryByText(t('en', 'docs.deepIndex.ready'))).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: t('en', 'docs.moreActions', { title: 'report.pdf' }) }))
await user.click(await screen.findByRole('menuitem', { name: t('en', 'docs.deepIndex.build') }))
expect(startDocTask).toHaveBeenCalledWith({ kind: 'extract', documentIds: ['d1'], params: undefined })
})
it('C4: a legacy (not fully-chunked) doc offers "Re-index first" and re-indexes, not a dead build', async () => {
const user = userEvent.setup()
const reindexDocument = vi.fn(async () => doc({ fullyChunked: true }))
const startDocTask = vi.fn(async () => ({ jobId: 'j1' }))
stubApi(documentsScreenStubs({
listDocuments: vi.fn(async () => [doc({ fullyChunked: false, treeStatus: null })]),
reindexDocument,
startDocTask
}))
render(<DocumentsScreen />)
await screen.findByText('report.pdf')
await user.click(screen.getByRole('button', { name: t('en', 'docs.moreActions', { title: 'report.pdf' }) }))
// The C4 gate surfaces "Re-index for deep index", NOT a "Build deep index" item.
expect(screen.queryByRole('menuitem', { name: t('en', 'docs.deepIndex.build') })).not.toBeInTheDocument()
await user.click(await screen.findByRole('menuitem', { name: t('en', 'docs.deepIndex.reindexFirst') }))
expect(reindexDocument).toHaveBeenCalledWith('d1')
expect(startDocTask).not.toHaveBeenCalled()
})
it('the preview meter renders the coverage from analysis:coverage', async () => {
const user = userEvent.setup()
const coverage: DocumentCoverage = {
coverage: { mode: 'tree', treeStatus: 'ready', chunksCovered: 40, chunksTotal: 40, tier: 1, treeLevels: 2 },
provenance: [{ label: 'S1', sourceTitle: 'report.pdf', pageNumber: 1, snippet: 'intro' }]
}
stubApi(documentsScreenStubs({
listDocuments: vi.fn(async () => [
doc({
fullyChunked: true,
treeStatus: 'ready',
summary: { text: 'A whole-document overview.', modelId: 'm', createdAt: '2026-01-01T00:00:00Z', truncated: false, tier: 1 }
})
]),
previewDocument: vi.fn(async () => ({
id: 'd1',
title: 'report.pdf',
mimeType: 'application/pdf',
segments: [{ text: 'body', pageNumber: 1, sectionLabel: null }]
})),
documentCoverage: vi.fn(async () => coverage)
}))
render(<DocumentsScreen />)
await screen.findByText('report.pdf')
await user.click(screen.getByRole('button', { name: /^preview$/i }))
await waitFor(() =>
expect(screen.getByText(t('en', 'coverage.tree.whole'))).toBeInTheDocument()
)
// The tier selector is offered (ready deep index).
expect(
screen.getByRole('button', { name: new RegExp(t('en', 'coverage.tier.1'), 'i') })
).toBeInTheDocument()
})
})