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

+108 -32
View File
@@ -2,10 +2,30 @@
* The engine stopped for good (three recoveries spent, owner decision 2026-10-15): the
* stopped notice on every core page, its two variants (tab copy saved: reload; tab storage
* full: download a copy), no retry anywhere, the editor's save banner with its copy button,
* and the stopped alerts (the beforeunload guard has its own hook test).
* and the stopped alerts (the beforeunload guard has its own hook test). The Home import
* refuses up front once the engine stopped (no import worker spawned); while it runs, the
* worker reads the file (in-process, R4.3) and the page's own index failing after it
* accepted gives the engine line.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
@@ -14,23 +34,25 @@ import NewReportRoute from '@/app/routes/NewReportRoute'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import { coreRuntime } from '@/core/runtime'
import { exportReportToPdf } from '@/pdf/export'
import { readAttachment } from '@/pdf/import'
import { loadSheetIndex } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { controlStopped } from '../helpers/core'
import { FIXTURES_DIR } from '../helpers/goldens'
import {
useInProcessImportWorker,
type FakeWorker,
} from '../helpers/importWorker'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
readAttachment: vi.fn(),
}))
vi.mock('@/sheets/useSheet', async (importOriginal) => ({
...(await importOriginal<typeof import('@/sheets/useSheet')>()),
loadSheetIndex: vi.fn((await importOriginal<typeof import('@/sheets/useSheet')>()).loadSheetIndex),
loadSheetIndex: vi.fn(
(await importOriginal<typeof import('@/sheets/useSheet')>()).loadSheetIndex,
),
}))
let sheet: SheetIndex
@@ -46,8 +68,14 @@ beforeEach(() => {
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
useReportStore.getState().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
setStopped = controlStopped(coreRuntime(), true)
blobs.length = 0
URL.createObjectURL = vi.fn((blob: Blob | MediaSource) => {
@@ -55,7 +83,9 @@ beforeEach(() => {
return 'blob:faunosteo-test'
})
URL.revokeObjectURL = vi.fn()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(
() => undefined,
)
})
afterEach(() => {
setStopped(false)
@@ -74,9 +104,12 @@ function fillStorage() {
expect(useReportStore.getState().saveFailed).toBe(true)
}
const retryButton = () => screen.queryByRole('button', { name: fr['sheet.core_retry'] })
const reloadButton = () => screen.queryByRole('button', { name: fr['core.reload'] })
const copyButton = () => screen.queryByRole('button', { name: fr['session.held.download'] })
const retryButton = () =>
screen.queryByRole('button', { name: fr['sheet.core_retry'] })
const reloadButton = () =>
screen.queryByRole('button', { name: fr['core.reload'] })
const copyButton = () =>
screen.queryByRole('button', { name: fr['session.held.download'] })
function expectSavedVariant() {
expect(screen.getByText(fr['core.stopped']!)).toBeInTheDocument()
@@ -92,7 +125,9 @@ async function expectUnsavedVariant() {
await userEvent.setup().click(copyButton()!)
expect(blobs).toHaveLength(1)
expect(blobs[0]!.type).toBe('application/json')
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
expect(await blobs[0]!.text()).toBe(
JSON.stringify(useReportStore.getState().report),
)
}
const inRouter = (node: React.ReactNode) =>
@@ -164,22 +199,34 @@ describe('EditorRoute', () => {
await screen.findByText(fr['editor.save_failed']!)
expect(screen.queryByText(fr['core.stopped_unsaved']!)).toBeNull()
await userEvent.setup().click(copyButton()!)
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
expect(await blobs[0]!.text()).toBe(
JSON.stringify(useReportStore.getState().report),
)
})
it('says the stopped text when the export fails once the engine stopped', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
vi.mocked(exportReportToPdf).mockRejectedValue(
new Error('core_unavailable'),
)
mountEditor()
await userEvent.setup().click(await screen.findByRole('button', { name: fr['editor.export']! }))
await waitFor(() => expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']))
await userEvent
.setup()
.click(await screen.findByRole('button', { name: fr['editor.export']! }))
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']),
)
})
it('says the unsaved stopped text for an export that fails with a full storage', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
vi.mocked(exportReportToPdf).mockRejectedValue(
new Error('core_unavailable'),
)
mountEditor()
const button = await screen.findByRole('button', { name: fr['editor.export']! })
const button = await screen.findByRole('button', {
name: fr['editor.export']!,
})
fillStorage()
await userEvent.setup().click(button)
await waitFor(() =>
@@ -192,7 +239,9 @@ describe('EditorRoute', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('render exploded'))
mountEditor()
await userEvent.setup().click(await screen.findByRole('button', { name: fr['editor.export']! }))
await userEvent
.setup()
.click(await screen.findByRole('button', { name: fr['editor.export']! }))
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['editor.export_failed']),
)
@@ -201,17 +250,25 @@ describe('EditorRoute', () => {
describe('the stopped text on the Home import line and the New report alert', () => {
const realLoad = vi.mocked(loadSheetIndex).getMockImplementation()!
let workers: FakeWorker[]
let restoreSpawn: () => void
beforeEach(() => {
// The page's own index fails: reached only once the worker accepted the file.
vi.mocked(loadSheetIndex).mockResolvedValue(null)
vi.mocked(readAttachment).mockResolvedValue({ version: 3 })
;({ workers, restore: restoreSpawn } = useInProcessImportWorker())
})
afterEach(() => {
restoreSpawn()
vi.mocked(loadSheetIndex).mockImplementation(realLoad)
})
afterEach(() => vi.mocked(loadSheetIndex).mockImplementation(realLoad))
/** Picks a valid Faunosteo PDF: a refusal is never the file's. */
async function pickPdf() {
inRouter(<HomeRoute />)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf')
const bytes = readFileSync(resolve(FIXTURES_DIR, 'report-v3.bare.pdf'))
const file = new File([bytes], 'bilan.pdf', { type: 'application/pdf' })
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
@@ -220,37 +277,56 @@ describe('the stopped text on the Home import line and the New report alert', ()
async function submitNewReport() {
const user = userEvent.setup()
inRouter(<NewReportRoute />)
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
await user.type(
screen.getByLabelText(fr['form.practitioner.name']!),
'Dr X',
)
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
const submit = screen.getByRole('button', {
name: fr['new_report.submit']!,
})
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
// A report is in progress (beforeEach): replacing it is confirmed first.
await user.click(await screen.findByRole('button', { name: fr['session.replace.confirm']! }))
await user.click(
await screen.findByRole('button', {
name: fr['session.replace.confirm']!,
}),
)
}
it('Home import: the engine error line says the stopped text', async () => {
await pickPdf()
await screen.findByText(fr['core.stopped']!, { selector: 'p.text-red-700' })
expect(screen.queryByText(fr['home.import.error_core_unavailable']!)).toBeNull()
expect(
screen.queryByText(fr['home.import.error_core_unavailable']!),
).toBeNull()
expect(workers).toHaveLength(0)
})
it('Home import: the unsaved stopped text when storage is full', async () => {
fillStorage()
await pickPdf()
await screen.findByText(fr['core.stopped_unsaved']!, { selector: 'p.text-red-700' })
await screen.findByText(fr['core.stopped_unsaved']!, {
selector: 'p.text-red-700',
})
expect(workers).toHaveLength(0)
})
it('Home import: keeps the engine error line while the engine is not stopped', async () => {
setStopped(false)
await pickPdf()
await screen.findByText(fr['home.import.error_core_unavailable']!)
// The worker read the file: the line is the page's index failing after it.
expect(workers[0]!.posted.map((m) => m.type)).toEqual(['ready', 'result'])
})
it('New report: the alert says the stopped text', async () => {
await submitNewReport()
await waitFor(() => expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']))
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']),
)
})
it('New report: the unsaved stopped text when storage is full', async () => {