feat(app): R4.3b/c import worker, client, controller; HomeRoute on the disposable worker

Protocol v1 (task → ready → result | failed with phase and kind), the worker entry with
the glue bundled statically and the page's compiled Module posted, the file streamed into
the module's memory; client with start and task timers (paused while hidden), settle-once,
terminate always, error events never masked; module-level controller (one import at a
time, cancel on leaving Home, worker chunk prefetched once the engine is loaded); the
settlement mapped to the B.1.8 messages (OD-5: a trap, a timeout or an unreadable file is
« Erreur de lecture du PDF. », never a corrupt PDF). HomeRoute keeps its routing and size
pre-checks, loads its own index after acceptance, drops a result when the session changed.
Tests: handler and client in-process, the corpus message test (O8 51, O7 stored inputs,
O2/O3/Step 5), the six existing suites migrated to the real worker logic.
This commit is contained in:
bchanot committed 2026-10-18 18:10:42 +02:00
1 parent 52471dbbc0
commit 6d1cce6e06
26 files changed
+2164 -247

No files matched your search

@@ -1,11 +1,15 @@
/**
* Step 6 Phase 0 characterisation of the import flow on the home route, with
* the two import steps mocked (R2: `readAttachment`, the engine's byte scan,
* then `importAttachment`, the core's layered read and rebase on the loaded
* sheet): the migration alert (degraded headline, then the count), the three
* ImportError kinds plus the generic error mapped to the FR messages, and the
* navigation to /editor on success; `lone_surrogate` (L1) has its own message.
* Step 6 Phase 0 characterisation of the import flow on the home route, through the
* import worker (R4.3: the real worker logic in-process on the shipped module, the
* files real fixtures or minimal PDFs from `helpers/pdfBytes`): the picked file reaches
* the worker unread by the page, with the page's sheet and module, and the core's
* result hydrates the store on the loaded sheet; the migration alert (degraded
* headline, then the count), the core's refusal kinds plus a worker trap mapped to the
* FR messages, and the navigation to /editor on success; `lone_surrogate` (L1) has its
* own message.
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
describe,
it,
@@ -25,82 +29,89 @@ import {
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
import HomeRoute from '@/app/routes/HomeRoute'
import {
ImportError,
importAttachment,
MAX_PDF_BYTES,
readAttachment,
} from '@/pdf/import'
import { MAX_PDF_BYTES, type EngineLoader } from '@/core/worker/handler'
import type { ImportTaskMessage } from '@/core/worker/protocol'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
readAttachment: vi.fn(),
importAttachment: vi.fn(),
}))
const readMock = vi.mocked(readAttachment)
const importMock = vi.mocked(importAttachment)
const ATTACHMENT = { version: 3 }
import { FIXTURES_DIR } from '../helpers/goldens'
import {
throwingEngineLoader,
useInProcessImportWorker,
type FakeWorker,
} from '../helpers/importWorker'
import { archivePdf, foreignPdf, pdfFile } from '../helpers/pdfBytes'
import { bundledSheet, loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
let workers: FakeWorker[]
let restoreSpawn: () => void
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
// A fresh tab: the previous import's draft would be a held text.
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
vi.stubGlobal('alert', vi.fn())
readMock.mockReset()
readMock.mockResolvedValue(ATTACHMENT)
importMock.mockReset()
;({ workers, restore: restoreSpawn } = useInProcessImportWorker())
})
afterEach(() => {
restoreSpawn()
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
/** What the import resolves with: the read (bare report, no archive) and no rebase. */
function outcome(patch: {
migrated: boolean
unresolvedZones?: number
unresolvedFindings?: number
}): ArchiveImport {
const report = minimalReport(sheet)
return {
read: {
report,
origin: patch.migrated ? 'v2' : 'bare_v3',
archive: null,
unresolvedZones: 0,
unresolvedFindings: 0,
...patch,
},
rebase: {
report,
unresolvedZones: 0,
unresolvedFindings: 0,
rebased: false,
},
const fixture = (name: string) =>
new Uint8Array(readFileSync(resolve(FIXTURES_DIR, name)))
/** The demo report exported bare by the Step 6 code: same sheet, no archive. */
const barePdf = () => pdfFile(fixture('report-v3.bare.pdf'))
/** A Report v2 holding one zone and one finding the migration map does not know. */
function lossyV2Pdf(): File {
const v2 = JSON.parse(
readFileSync(resolve(FIXTURES_DIR, 'report-v2.minimal.json'), 'utf8'),
)
const observation = {
id: 'obs-lost',
zones: [{ boneId: 'point-gone' }],
findings: [
{
zoneId: 'zone-gone',
path: ['zone-gone-dysfunctions', 'gone'],
labelFrSnapshot: 'Constat disparu',
labelEnSnapshot: 'Gone finding',
},
],
freeTextFindings: [],
comment: '',
}
const report = { ...v2, observations: [observation] }
return pdfFile(archivePdf(JSON.stringify(report)))
}
/** A 4-byte "%PDF" file; the import is mocked, the bytes only travel. */
function pdfFile(): File {
return new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf', {
type: 'application/pdf',
})
/** The core's import outcome the worker answered (the result message, parsed). */
function resultOf(worker: FakeWorker): ArchiveImport {
const result = worker.posted.find((m) => m.type === 'result')
if (result?.type !== 'result') throw new Error('the worker gave no result')
const envelope = JSON.parse(result.out) as {
ok: boolean
value: ArchiveImport
}
if (!envelope.ok) throw new Error(`the core refused: ${result.out}`)
return envelope.value
}
async function mountAndPickPdf(file: File = pdfFile()): Promise<void> {
async function mountAndPickPdf(file: File = barePdf()): Promise<void> {
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
@@ -120,25 +131,44 @@ const errorText = () => screen.queryByText(/./, { selector: 'p.text-red-700' })
describe('HomeRoute import: success paths', () => {
it('passes the file bytes to the scan and the attachment to the loaded sheet, hydrates, navigates to /editor', async () => {
importMock.mockReturnValue(outcome({ migrated: false }))
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(readMock).toHaveBeenCalledTimes(1)
expect(readMock.mock.calls[0]![0]).toBeInstanceOf(Uint8Array)
expect(importMock).toHaveBeenCalledTimes(1)
const [attachment, index] = importMock.mock.calls[0]!
expect(attachment).toBe(ATTACHMENT)
// Since R4.3 the scan runs in the worker: the page hands it the file unread.
const file = barePdf()
const read = vi.spyOn(file, 'arrayBuffer')
const text = vi.spyOn(file, 'text')
const real = useReportStore.getState().hydrateImport
const hydrate = vi.fn(real)
useReportStore.setState({ hydrateImport: hydrate })
try {
await mountAndPickPdf(file)
await screen.findByTestId('editor-route')
} finally {
useReportStore.setState({ hydrateImport: real })
}
expect(workers).toHaveLength(1)
const task = workers[0]!.received[0] as ImportTaskMessage
expect(task).toMatchObject({ type: 'task', task: 'pdf' })
expect(task.file).toBe(file)
expect(task.sheet).toBe(JSON.stringify(await bundledSheet()))
expect(task.module).toBeInstanceOf(WebAssembly.Module)
expect(read).not.toHaveBeenCalled()
expect(text).not.toHaveBeenCalled()
const imported = resultOf(workers[0]!)
expect(hydrate).toHaveBeenCalledTimes(1)
const [session, index] = hydrate.mock.calls[0]!
expect(session).toEqual({ report: imported.rebase.report, archive: null })
expect(index).toBe(sheet)
expect(useReportStore.getState().report?.id).toBe('r1')
expect(useReportStore.getState().report?.id).toBe('fixture-demo-v3')
expect(alertMock()).not.toHaveBeenCalled()
})
it('alerts "degraded" then the unresolved count (zones + findings) after a lossy migration', async () => {
importMock.mockReturnValue(
outcome({ migrated: true, unresolvedZones: 1, unresolvedFindings: 1 }),
)
await mountAndPickPdf()
await mountAndPickPdf(lossyV2Pdf())
await screen.findByTestId('editor-route')
expect(resultOf(workers[0]!).read).toMatchObject({
migrated: true,
unresolvedZones: 1,
unresolvedFindings: 1,
})
expect(alertMock()).toHaveBeenCalledTimes(1)
const message = alertMock().mock.calls[0]![0] as string
const [headline, ...lines] = message.split('\n\n')
@@ -147,49 +177,66 @@ describe('HomeRoute import: success paths', () => {
})
it('stays silent on a migration that lost nothing', async () => {
importMock.mockReturnValue(outcome({ migrated: true }))
await mountAndPickPdf()
// The Step 5 v2 export: every zone and finding has its place on the draft.
await mountAndPickPdf(pdfFile(fixture('report-v2.full.pdf')))
await screen.findByTestId('editor-route')
expect(resultOf(workers[0]!).read).toMatchObject({
migrated: true,
unresolvedZones: 0,
unresolvedFindings: 0,
})
expect(alertMock()).not.toHaveBeenCalled()
})
})
describe('HomeRoute import: error paths', () => {
const cases: Array<[string, Error, string]> = [
const cases: Array<[string, () => File, string, EngineLoader?]> = [
[
'incompatible_version → message with the found version',
new ImportError('incompatible_version', 7),
() =>
pdfFile(
archivePdf(JSON.stringify({ ...minimalReport(sheet), version: 7 })),
),
fr['home.import.error_incompatible_version']!.replace('{version}', '7'),
],
[
'invalid_pdf → unreadable PDF message',
new ImportError('invalid_pdf'),
() => pdfFile(new TextEncoder().encode('not a PDF at all')),
fr['home.import.error_invalid_pdf']!,
],
[
'no_attachment → not a Faunosteo PDF message',
new ImportError('no_attachment'),
() => pdfFile(foreignPdf()),
fr['home.import.error_no_attachment']!,
],
[
'lone_surrogate → malformed text message, file untouched',
new ImportError('lone_surrogate'),
() =>
pdfFile(
archivePdf(
JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' })),
),
),
fr['home.import.error_lone_surrogate']!,
],
[
'generic Error → generic message',
new Error('disk on fire'),
// A trap of the worker's engine: never shown as a corrupt PDF (OD-5).
barePdf,
fr['home.import.error_generic']!,
throwingEngineLoader(new WebAssembly.RuntimeError('unreachable')),
],
]
it.each(cases)('%s', async (_label, error, expected) => {
importMock.mockImplementation(() => {
throw error
})
await mountAndPickPdf()
it.each(cases)('%s', async (_label, file, expected, load) => {
// Another engine replaces the seam; afterEach restores the default.
if (load) {
;({ workers, restore: restoreSpawn } = useInProcessImportWorker(load))
}
await mountAndPickPdf(file())
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(expected)
expect(workers).toHaveLength(1)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
expect(alertMock()).not.toHaveBeenCalled()
@@ -198,15 +245,16 @@ describe('HomeRoute import: error paths', () => {
describe('HomeRoute import: size gate', () => {
it('refuses a file over MAX_PDF_BYTES before reading it: unreadable PDF message', async () => {
const file = pdfFile()
const file = barePdf()
Object.defineProperty(file, 'size', { value: MAX_PDF_BYTES + 1 })
const read = vi.spyOn(file, 'arrayBuffer')
const stream = vi.spyOn(file, 'stream')
await mountAndPickPdf(file)
await waitFor(() => expect(errorText()).not.toBeNull())
expect(errorText()!.textContent).toBe(fr['home.import.error_invalid_pdf'])
expect(read).not.toHaveBeenCalled()
expect(readMock).not.toHaveBeenCalled()
expect(importMock).not.toHaveBeenCalled()
expect(stream).not.toHaveBeenCalled()
expect(workers).toHaveLength(0)
expect(screen.queryByTestId('editor-route')).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
@@ -214,12 +262,13 @@ describe('HomeRoute import: size gate', () => {
describe('HomeRoute import: a core failure reading the tab draft', () => {
it('shows the engine error line, not the held-session alert', async () => {
importMock.mockReturnValue(outcome({ migrated: false }))
const real = useReportStore.getState().hydrateImport
useReportStore.setState({ hydrateImport: () => ({ ok: false }) })
try {
await mountAndPickPdf()
await screen.findByText(fr['home.import.error_core_unavailable']!)
// The worker read the file: the failure is the store's, after the result.
expect(workers[0]!.posted.map((m) => m.type)).toEqual(['ready', 'result'])
expect(alertMock()).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
} finally {
@@ -228,12 +277,14 @@ describe('HomeRoute import: a core failure reading the tab draft', () => {
})
it('still alerts and opens the editor for a held session text', async () => {
importMock.mockReturnValue(outcome({ migrated: false }))
const real = useReportStore.getState().hydrateImport
useReportStore.setState({ hydrateImport: () => ({ ok: false, reason: 'held' }) })
useReportStore.setState({
hydrateImport: () => ({ ok: false, reason: 'held' }),
})
try {
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(workers[0]!.posted.map((m) => m.type)).toEqual(['ready', 'result'])
expect(alertMock()).toHaveBeenCalledWith(fr['session.held_blocked'])
} finally {
useReportStore.setState({ hydrateImport: real })