fix(editor): honest stopped state when the draft is unsaved; no dead retry

0279953 chose the stopped message from CoreRuntime.stopped alone: it
promised the report was kept even when the tab's storage refused the
draft (export, the banner's advice, needs the core), four surfaces still
offered a retry that could not work, and a failed recovery below the cap
was a dead end since nothing called retry().

The runtime restarts a failed recovery on the next call (compiled module
reused, cap still counts traps) and notifies status listeners. One
CoreStoppedNotice on the editor, Home, New report and the full-page
notice: reload when saved, else core.stopped_unsaved with a core-free
copy download (also on the storage-full banner) and a beforeunload
guard. Export, import and new report say the stopped message; a core
failure reading an unread draft is FAILED, not held. ESLint census of
the failure keys; core.stopped says "plusieurs erreurs".
This commit is contained in:
bchanot committed 2026-10-16 18:26:10 +02:00
1 parent 0279953e9e
commit 6371523f8c
24 files changed
+839 -83

No files matched your search

+13
View File
@@ -6,6 +6,19 @@ export function testCoreRuntime(): Promise<CoreRuntime> {
return nodeCoreRuntime('pkg')
}
/**
* Makes `runtime.stopped` follow a flag the test controls; the returned setter flips it and
* notifies the subscribers, as the runtime does on its own transition to stopped.
*/
export function controlStopped(runtime: CoreRuntime, initial: boolean) {
let stopped = initial
Object.defineProperty(runtime, 'stopped', { get: () => stopped, configurable: true })
return (next: boolean) => {
stopped = next
;(runtime as unknown as { notify(): void }).notify()
}
}
/** A runtime whose module never loads (CSP refusal, network failure). */
export function unavailableCoreRuntime(): CoreRuntime {
return new CoreRuntime({
@@ -1,16 +1,17 @@
import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import type { CoreRuntime } from '@faunosteo/core-wasm'
import { coreRuntime, setCoreRuntime } from '@/core/runtime'
import { coreRuntime } from '@/core/runtime'
import { coreFailureMessage } from '@/core/failure'
import { useReportStore } from '@/state/reportStore'
import { buildViewSvg } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { bundledSheet, loadTestSheet, sheetFromBundle } from '../helpers/sheet'
import { controlStopped } from '../helpers/core'
import { bundledSheet, loadTestSheet, minimalReport, sheetFromBundle } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
@@ -141,15 +142,18 @@ describe('AnatomyCanvas', () => {
await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.queryByText(fr['canvas.view_unavailable']!)).toBeNull()
engineDown = false
const retry = vi.spyOn(coreRuntime(), 'retry')
await user.click(screen.getByRole('button', { name: fr['sheet.core_retry'] }))
// The engine is restarted first, then the view is built again.
expect(retry).toHaveBeenCalledTimes(1)
await waitFor(() => expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull())
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
retry.mockRestore()
})
it('after the recoveries are spent, shows the final state with no retry; alerts say the same', async () => {
useLocaleStore.setState({ locale: 'fr' })
const live = coreRuntime()
setCoreRuntime({ stopped: true } as unknown as CoreRuntime)
const setStopped = controlStopped(coreRuntime(), true)
try {
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'internal' })
@@ -158,9 +162,42 @@ describe('AnatomyCanvas', () => {
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.stopped'])
} finally {
setCoreRuntime(live)
setStopped(false)
}
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.action_failed'])
expect(coreFailureMessage((k: string) => fr[k]!, 'editor.export_failed')).toBe(
fr['editor.export_failed'],
)
})
it('switches a shown engine failure to the stopped text when the engine stops, per save state', async () => {
useLocaleStore.setState({ locale: 'fr' })
const setStopped = controlStopped(coreRuntime(), false)
try {
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'core_unavailable' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
act(() => setStopped(true))
await screen.findByText(fr['core.stopped']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
// The draft mirror hits a full storage: the report only lives in memory.
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.setState({ report: minimalReport(sheet) }))
expect(useReportStore.getState().saveFailed).toBe(true)
await screen.findByText(fr['core.stopped_unsaved']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(
coreFailureMessage((k: string) => fr[k]!, 'editor.export_failed'),
).toBe(fr['core.stopped_unsaved'])
} finally {
setStopped(false)
vi.restoreAllMocks()
useReportStore.setState({ report: null, saveFailed: false })
}
})
it('words both failures in English too', async () => {
@@ -211,3 +211,32 @@ describe('HomeRoute import: size gate', () => {
expect(useReportStore.getState().report).toBeNull()
})
})
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']!)
expect(alertMock()).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
} finally {
useReportStore.setState({ hydrateImport: real })
}
})
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' }) })
try {
await mountAndPickPdf()
await screen.findByTestId('editor-route')
expect(alertMock()).toHaveBeenCalledWith(fr['session.held_blocked'])
} finally {
useReportStore.setState({ hydrateImport: real })
}
})
})
@@ -0,0 +1,287 @@
/**
* 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,
* the beforeunload guard while the report is unsaved, and the stopped alerts.
*/
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 { 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 { 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),
}))
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('guards the page with beforeunload exactly while the report is unsaved', async () => {
setStopped(false)
mountEditor()
await screen.findByTestId('sheet-status')
const leave = () => {
const event = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(event)
return event.defaultPrevented
}
expect(leave()).toBe(false)
fillStorage()
await waitFor(() => expect(leave()).toBe(true))
vi.restoreAllMocks()
act(() => useReportStore.getState().setConclusion('saved again'))
expect(useReportStore.getState().saveFailed).toBe(false)
await waitFor(() => expect(leave()).toBe(false))
})
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()!
beforeEach(() => {
vi.mocked(loadSheetIndex).mockResolvedValue(null)
vi.mocked(readAttachment).mockResolvedValue({ version: 3 })
})
afterEach(() => vi.mocked(loadSheetIndex).mockImplementation(realLoad))
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')
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)
}
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()
})
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' })
})
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']!)
})
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']),
)
})
})
@@ -265,18 +265,21 @@ describe('a new session over texts this page never read (after a reload)', () =>
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
it('is refused when the core cannot read the draft at all', () => {
it('fails (not held) when the core cannot read the draft at all, touching nothing', () => {
const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft)
const broken = {
...sheet,
ops: { restoreDraft: () => ({ ok: false, kind: 'core_unavailable' }) },
} as unknown as SheetIndex
expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({
ok: false,
reason: 'held',
})
const before = snapshotStorage()
expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({ ok: false })
expect(
store().hydrateImport({ report: minimalReport(sheet), archive: null }, broken),
).toEqual({ ok: false })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(snapshotStorage()).toEqual(before)
expect(store().report).toBeNull()
})
})