Files
faunosteo/apps/app/tests/unit/routes.coreStopped.test.tsx
bchanot e659924ec0 feat(app): R4.3a the page reads the file chunk by chunk and streams it to the worker's sink
Measured at R4.3a (RUST.md §10.5): reading a file inside a WebKit worker costs about
180 MiB of content RSS whatever the method (arrayBuffer, stream, BYOB), 14 MiB on the
page; a page-side BYOB read feeding the worker's FileBytes gives 106 MiB on a 50 MiB file
against 272 in the worker and 76 for the TypeScript. Protocol v1 gains chunk / ack / end:
one 1 MiB buffer travels (transferred) and comes back after each push, so the page holds
one chunk and the worker's sink the only whole copy; no byte is parsed on the page. The
worker refuses an oversize announced before any chunk and a size that changes while
reading. Tests adapted (handler, client with a scripted ack, read failure on the page).
2026-10-18 18:57:55 +02:00

348 lines
12 KiB
TypeScript

/**
* 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). 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 { 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'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import { coreRuntime } from '@/core/runtime'
import { exportReportToPdf } from '@/pdf/export'
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('@/sheets/useSheet', async (importOriginal) => ({
...(await importOriginal<typeof import('@/sheets/useSheet')>()),
loadSheetIndex: vi.fn(
(await importOriginal<typeof import('@/sheets/useSheet')>()).loadSheetIndex,
),
}))
let sheet: SheetIndex
let setStopped: (next: boolean) => void
const blobs: Blob[] = []
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
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)
setStopped = controlStopped(coreRuntime(), true)
blobs.length = 0
URL.createObjectURL = vi.fn((blob: Blob | MediaSource) => {
blobs.push(blob as Blob)
return 'blob:faunosteo-test'
})
URL.revokeObjectURL = vi.fn()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(
() => undefined,
)
})
afterEach(() => {
setStopped(false)
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
useReportStore.setState({ report: null, saveFailed: false })
})
/** The tab's storage is full from now on: the next change of the report is not saved. */
function fillStorage() {
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.getState().setConclusion('edited after the quota'))
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'] })
function expectSavedVariant() {
expect(screen.getByText(fr['core.stopped']!)).toBeInTheDocument()
expect(reloadButton()).toBeInTheDocument()
expect(copyButton()).toBeNull()
expect(retryButton()).toBeNull()
}
async function expectUnsavedVariant() {
expect(screen.getByText(fr['core.stopped_unsaved']!)).toBeInTheDocument()
expect(reloadButton()).toBeNull()
expect(retryButton()).toBeNull()
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),
)
}
const inRouter = (node: React.ReactNode) =>
render(<MemoryRouter initialEntries={['/']}>{node}</MemoryRouter>)
describe('the stopped notice on the pages that run the core', () => {
it('Home, New report and the full-page notice: reload when the save is fine', async () => {
inRouter(<HomeRoute />)
expectSavedVariant()
cleanup()
inRouter(<NewReportRoute />)
expectSavedVariant()
cleanup()
render(<CoreUnavailable onRetry={() => undefined} />)
expectSavedVariant()
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
})
it('Home, New report and the full-page notice: a copy of the in-memory report when storage is full', async () => {
fillStorage()
inRouter(<HomeRoute />)
await expectUnsavedVariant()
cleanup()
blobs.length = 0
inRouter(<NewReportRoute />)
await expectUnsavedVariant()
cleanup()
blobs.length = 0
render(<CoreUnavailable onRetry={() => undefined} />)
await expectUnsavedVariant()
})
it('is absent while the engine runs, and appears when it stops', async () => {
setStopped(false)
inRouter(<HomeRoute />)
expect(screen.queryByText(fr['core.stopped']!)).toBeNull()
act(() => setStopped(true))
await screen.findByText(fr['core.stopped']!)
})
it('keeps the full-page retry while the engine is not stopped', () => {
setStopped(false)
render(<CoreUnavailable onRetry={() => undefined} />)
expect(screen.getByText(fr['sheet.core_unavailable']!)).toBeInTheDocument()
expect(retryButton()).toBeInTheDocument()
})
})
describe('EditorRoute', () => {
const mountEditor = () => inRouter(<EditorRoute />)
it('puts the stopped notice in the banner slot, in place of the storage-full text', async () => {
mountEditor()
await screen.findByText(fr['core.stopped']!)
expectSavedVariant()
fillStorage()
await screen.findByText(fr['core.stopped_unsaved']!)
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
expect(screen.getAllByText(fr['core.stopped_unsaved']!)).toHaveLength(1)
await expectUnsavedVariant()
})
it('keeps the storage-full text and adds the copy button when the engine runs', async () => {
setStopped(false)
mountEditor()
await screen.findByTestId('sheet-status')
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
fillStorage()
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),
)
})
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'),
)
mountEditor()
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'),
)
mountEditor()
const button = await screen.findByRole('button', {
name: fr['editor.export']!,
})
fillStorage()
await userEvent.setup().click(button)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped_unsaved']),
)
})
it('keeps the export message while the engine is not stopped', async () => {
setStopped(false)
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 waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['editor.export_failed']),
)
})
})
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)
;({ workers, restore: restoreSpawn } = useInProcessImportWorker())
})
afterEach(() => {
restoreSpawn()
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 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] },
})
}
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.animal.name']!), 'Rex')
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
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']!,
}),
)
}
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(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',
})
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]!.sequence()).toEqual(['ready', 'result'])
})
it('New report: the alert says the stopped text', async () => {
await submitNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']),
)
})
it('New report: the unsaved stopped text when storage is full', async () => {
fillStorage()
await submitNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped_unsaved']),
)
})
it('New report: keeps the sheet alert while the engine is not stopped', async () => {
setStopped(false)
await submitNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['sheet.core_unavailable']),
)
})
})