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

+1 -1
View File
@@ -12,7 +12,7 @@ Versions follow [Semantic Versioning](https://semver.org/).
- **No visible change**, proven first with the TypeScript: canvas trees of both views and 28 selection states, layer trees with attribute order, 36 PDF highlight compositions, 36 hostile SVGs and 10 generated floods, the 4 product SVGs untouched; in Chromium 156 the live canvas trees equal the frozen ones and 30 screenshots (desktop and phone) are pixel-identical before and after. The Step 6 goldens are untouched. - **No visible change**, proven first with the TypeScript: canvas trees of both views and 28 selection states, layer trees with attribute order, 36 PDF highlight compositions, 36 hostile SVGs and 10 generated floods, the 4 product SVGs untouched; in Chromium 156 the live canvas trees equal the frozen ones and 30 screenshots (desktop and phone) are pixel-identical before and after. The Step 6 goldens are untouched.
- Declared differences, none on a product drawing: elements outside the SVG namespace removed, comments dropped, no `class`/`style` on the inline root, stricter ids, text only in `title`/`desc` (4 KiB each), floods and reference cycles refused, a product drawing the allowlist would alter refused at load instead of silently cut, a canvas that cannot be composed shows the existing degraded notice with a retry (`docs/development/RUST.md` §9.4). - Declared differences, none on a product drawing: elements outside the SVG namespace removed, comments dropped, no `class`/`style` on the inline root, stricter ids, text only in `title`/`desc` (4 KiB each), floods and reference cycles refused, a product drawing the allowlist would alter refused at load instead of silently cut, a canvas that cannot be composed shows the existing degraded notice with a retry (`docs/development/RUST.md` §9.4).
- `docs/ANNOTATION-RENDERING.md` rewritten to describe the code exactly (no rendering change). Module 396 KB gzip (+56 KB, budget 600 KB). - `docs/ANNOTATION-RENDERING.md` rewritten to describe the code exactly (no rendering change). Module 396 KB gzip (+56 KB, budget 600 KB).
- Owner decisions after the R3 review: a detail-view trigger without its own name now carries the opened view's name in each language (the English attribute and the tooltip title used to repeat the French name); the canvas tells an engine that did not load ("Réessayer") from a view whose drawing is refused or cannot be composed (its own message, no retry); after its three recoveries the engine shows a clear final state (reload the page, the report is kept in the tab) in the canvas and in the action alerts, never a retry that cannot work. - Owner decisions after the R3 review: a detail-view trigger without its own name now carries the opened view's name in each language (the English attribute and the tooltip title used to repeat the French name); the canvas tells an engine that did not load ("Réessayer") from a view whose drawing is refused or cannot be composed (its own message, no retry); after its three recoveries the engine shows a clear final state, never a retry that cannot work: in the canvas, the editor banner slot, the top of Home and New report and the full-page notice, and in the action, export, import and new-report alerts. Two variants: report saved in the tab ("Recharger la page"), or tab storage full ("Télécharger une copie" of the in-memory report, no reload button, native confirmation before leaving). A recovery that fails below the cap is restarted by the next call (the canvas "Réessayer" now restarts the engine), and a core failure reading the tab draft no longer reports a held session.
### Security (maintenance after R2, 2026-10-14) ### Security (maintenance after R2, 2026-10-14)
+39
View File
@@ -3,6 +3,21 @@ import tseslint from 'typescript-eslint'
import pluginReact from 'eslint-plugin-react' import pluginReact from 'eslint-plugin-react'
import pluginReactHooks from 'eslint-plugin-react-hooks' import pluginReactHooks from 'eslint-plugin-react-hooks'
/**
* Census of the call sites of the keys that must go through `coreFailureMessage`: once the
* engine stopped, a direct `t('<key>')` would tell the practitioner to retry (owner
* decision 2026-10-15). Dictionaries and key strings passed as arguments are not call sites.
*/
const failureKeySelector = (key) => ({
selector: `CallExpression[callee.name='t'][arguments.0.value='${key}']`,
message: `Use coreFailureMessage(t, '${key}') (src/core/failure.ts), not a direct t() call.`,
})
const FAILURE_KEYS = [
'core.action_failed',
'editor.export_failed',
'home.import.error_core_unavailable',
]
export default tseslint.config( export default tseslint.config(
{ ignores: ['dist/**', 'node_modules/**', 'coverage/**'] }, { ignores: ['dist/**', 'node_modules/**', 'coverage/**'] },
{ {
@@ -58,4 +73,28 @@ export default tseslint.config(
], ],
}, },
}, },
{
files: ['src/**/*.{ts,tsx}'],
ignores: [
'src/core/failure.ts',
'src/components/report/CoreUnavailable.tsx',
'src/components/canvas/AnatomyCanvas.tsx',
],
rules: {
'no-restricted-syntax': [
'error',
...[...FAILURE_KEYS, 'sheet.core_unavailable'].map(failureKeySelector),
],
},
},
{
// These two own the degraded engine notice, which names `sheet.core_unavailable`.
files: [
'src/components/report/CoreUnavailable.tsx',
'src/components/canvas/AnatomyCanvas.tsx',
],
rules: {
'no-restricted-syntax': ['error', ...FAILURE_KEYS.map(failureKeySelector)],
},
},
) )
+28 -5
View File
@@ -14,11 +14,13 @@ import EditInfosDialog, {
type Identity, type Identity,
} from '@/components/report/EditInfosDialog' } from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog' import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import CoreStoppedNotice, { CopyReportButton } from '@/components/report/CoreStoppedNotice'
import CoreUnavailable from '@/components/report/CoreUnavailable' import CoreUnavailable from '@/components/report/CoreUnavailable'
import HeldSessionPanel from '@/components/report/HeldSessionPanel' import HeldSessionPanel from '@/components/report/HeldSessionPanel'
import Notice from '@/components/ui/Notice' import Notice from '@/components/ui/Notice'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { import {
isUnsaved,
useReportStore, useReportStore,
type ActionResult, type ActionResult,
type HeldText, type HeldText,
@@ -37,6 +39,7 @@ import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { coreFailureMessage } from '@/core/failure' import { coreFailureMessage } from '@/core/failure'
import { useCoreStopped } from '@/core/runtime'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
@@ -72,6 +75,8 @@ export default function EditorRoute() {
const { report, activeObservationIndex: activeIndex } = store const { report, activeObservationIndex: activeIndex } = store
// Without a report yet (draft restore), the default species' sheet carries the migration map. // Without a report yet (draft restore), the default species' sheet carries the migration map.
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID) const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
const stopped = useCoreStopped()
const unsaved = isUnsaved(store)
const [detailViewId, setDetailViewId] = useState<string | null>(null) const [detailViewId, setDetailViewId] = useState<string | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>( const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
@@ -132,6 +137,17 @@ export default function EditorRoute() {
navigate('/') navigate('/')
}, [report, sheet, store, navigate, t, restoreAttempt]) }, [report, sheet, store, navigate, t, restoreAttempt])
// The report lives only in this tab's memory: the browser asks before a reload or a close.
useEffect(() => {
if (!unsaved) return
const guard = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
window.addEventListener('beforeunload', guard)
return () => window.removeEventListener('beforeunload', guard)
}, [unsaved])
const retryRestore = useCallback(() => setRestoreAttempt((n) => n + 1), []) const retryRestore = useCallback(() => setRestoreAttempt((n) => n + 1), [])
useEffect(() => { useEffect(() => {
@@ -248,7 +264,7 @@ export default function EditorRoute() {
} }
} catch (err) { } catch (err) {
console.error('PDF export failed', err) console.error('PDF export failed', err)
window.alert(t('editor.export_failed')) window.alert(coreFailureMessage(t, 'editor.export_failed'))
} finally { } finally {
setExporting(false) setExporting(false)
} }
@@ -300,10 +316,17 @@ export default function EditorRoute() {
}) })
} }
/> />
{store.saveFailed && ( {stopped ? (
<Notice tone="error" className="mx-4 sm:mx-6 mt-4"> <CoreStoppedNotice className="mx-4 sm:mx-6 mt-4" />
{t('editor.save_failed')} ) : (
</Notice> store.saveFailed && (
<Notice tone="error" className="mx-4 sm:mx-6 mt-4">
<p>{t('editor.save_failed')}</p>
<div className="mt-2">
<CopyReportButton />
</div>
</Notice>
)
)} )}
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6"> <div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col"> <section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
+6 -1
View File
@@ -6,6 +6,7 @@ import type {
} from '@faunosteo/core-wasm/types' } from '@faunosteo/core-wasm/types'
import AppHeader from '@/components/brand/AppHeader' import AppHeader from '@/components/brand/AppHeader'
import HomeSpaceLink from '@/components/brand/HomeSpaceLink' import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card' import Card from '@/components/ui/Card'
import { import {
@@ -18,6 +19,7 @@ import { useReportStore } from '@/state/reportStore'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet' import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { coreFailureMessage } from '@/core/failure'
type Translate = ReturnType<typeof useT> type Translate = ReturnType<typeof useT>
@@ -106,7 +108,7 @@ function importErrorMessage(err: unknown, t: Translate): string {
case 'lone_surrogate': case 'lone_surrogate':
return t('home.import.error_lone_surrogate') return t('home.import.error_lone_surrogate')
case 'core_unavailable': case 'core_unavailable':
return t('home.import.error_core_unavailable') return coreFailureMessage(t, 'home.import.error_core_unavailable')
} }
} }
@@ -135,6 +137,8 @@ export default function HomeRoute() {
) )
// A tab text that could not be set aside would be overwritten: resolve it first. // A tab text that could not be set aside would be overwritten: resolve it first.
if (!opened.ok) { if (!opened.ok) {
// A core failure reading the tab's draft is an engine error, not a held text.
if (opened.reason !== 'held') throw new ImportError('core_unavailable')
window.alert(t('session.held_blocked')) window.alert(t('session.held_blocked'))
navigate('/editor') navigate('/editor')
return return
@@ -166,6 +170,7 @@ export default function HomeRoute() {
<AppHeader> <AppHeader>
<HomeSpaceLink /> <HomeSpaceLink />
</AppHeader> </AppHeader>
<CoreStoppedBanner className="mx-4 sm:mx-6 mt-4" />
<section className="flex-1 grid place-items-center px-4 sm:px-6"> <section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full"> <div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
{noSheet && ( {noSheet && (
+3 -1
View File
@@ -4,6 +4,7 @@ import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
import PractitionerForm from '@/components/report/PractitionerForm' import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm' import AnimalForm from '@/components/report/AnimalForm'
import AppHeader from '@/components/brand/AppHeader' import AppHeader from '@/components/brand/AppHeader'
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
@@ -52,7 +53,7 @@ export default function NewReportRoute() {
// The loaded sheet lets the store read a draft this page never opened before replacing it. // The loaded sheet lets the store read a draft this page never opened before replacing it.
const index = await loadSheetIndex(DEFAULT_SPECIES_ID) const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) { if (!index) {
window.alert(t('sheet.core_unavailable')) window.alert(coreFailureMessage(t, 'sheet.core_unavailable'))
return return
} }
const created = initReport( const created = initReport(
@@ -79,6 +80,7 @@ export default function NewReportRoute() {
<main className="min-h-screen"> <main className="min-h-screen">
<AppHeader /> <AppHeader />
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8"> <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
<CoreStoppedBanner />
<h1 className="font-serif text-2xl sm:text-3xl"> <h1 className="font-serif text-2xl sm:text-3xl">
{t('new_report.title')} {t('new_report.title')}
</h1> </h1>
@@ -1,7 +1,10 @@
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { buildViewSvg, type ViewFailure, type ViewStates } from '@/anatomy/drawing' import { buildViewSvg, type ViewFailure, type ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex' import type { SheetIndex } from '@/services/sheetIndex'
import { coreRuntime, useCoreStopped } from '@/core/runtime'
import { stoppedMessageKey } from '@/core/failure'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice' import Notice from '@/components/ui/Notice'
@@ -17,7 +20,7 @@ export interface AnatomyCanvasProps {
const ANNOTATED = '[data-anno-id]' const ANNOTATED = '[data-anno-id]'
/** Only an engine that can still recover offers a retry. */ /** `engine_stopped` is replaced at render by the stopped text that fits the save state. */
const FAILURE_MESSAGE: Record<ViewFailure, string> = { const FAILURE_MESSAGE: Record<ViewFailure, string> = {
engine: 'sheet.core_unavailable', engine: 'sheet.core_unavailable',
engine_stopped: 'core.stopped', engine_stopped: 'core.stopped',
@@ -34,7 +37,8 @@ function annotatedTarget(event: Event): Element | null {
* the core (R3), rebuilt when the view changes and restyled in place when the * the core (R3), rebuilt when the view changes and restyled in place when the
* selection changes (the restyle runs right after every build). Clicks are * selection changes (the restyle runs right after every build). Clicks are
* delegated on `data-anno-id`. When the engine cannot run, the canvas shows the * delegated on `data-anno-id`. When the engine cannot run, the canvas shows the
* degraded notice with a retry; when the view itself cannot be drawn (a drawing * degraded notice with a retry (none once the engine stopped for good: the page's stopped
* notice holds the buttons); when the view itself cannot be drawn (a drawing
* refused or impossible to compose), a notice without retry: nothing would change. * refused or impossible to compose), a notice without retry: nothing would change.
*/ */
export default function AnatomyCanvas({ export default function AnatomyCanvas({
@@ -52,6 +56,17 @@ export default function AnatomyCanvas({
// Each retry builds again; a failed build leaves the canvas empty behind the notice. // Each retry builds again; a failed build leaves the canvas empty behind the notice.
const [attempt, setAttempt] = useState(0) const [attempt, setAttempt] = useState(0)
const [failure, setFailure] = useState<ViewFailure | null>(null) const [failure, setFailure] = useState<ViewFailure | null>(null)
// Derived at render: an engine failure shown while the engine stops becomes the stopped text.
const stopped = useCoreStopped()
const unsaved = useReportStore(isUnsaved)
const engineStopped = failure === 'engine_stopped' || (failure === 'engine' && stopped)
// A failed recovery below the cap needs the runtime restarted before the view is built again.
const retryEngine = useCallback(() => {
void coreRuntime()
.retry()
.finally(() => setAttempt((n) => n + 1))
}, [])
useEffect(() => { useEffect(() => {
const host = svgRef.current const host = svgRef.current
@@ -140,11 +155,11 @@ export default function AnatomyCanvas({
{failure && ( {failure && (
<div className="absolute inset-0 grid place-items-center p-4"> <div className="absolute inset-0 grid place-items-center p-4">
<div className="space-y-3 max-w-sm"> <div className="space-y-3 max-w-sm">
<Notice tone="error">{t(FAILURE_MESSAGE[failure])}</Notice> <Notice tone="error">
{failure === 'engine' && ( {t(engineStopped ? stoppedMessageKey(unsaved) : FAILURE_MESSAGE[failure])}
<Button onClick={() => setAttempt((n) => n + 1)}> </Notice>
{t('sheet.core_retry')} {failure === 'engine' && !engineStopped && (
</Button> <Button onClick={retryEngine}>{t('sheet.core_retry')}</Button>
)} )}
</div> </div>
</div> </div>
@@ -0,0 +1,57 @@
import { useCoreStopped } from '@/core/runtime'
import { downloadJson } from '@/lib/download'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { useT } from '@/i18n/useT'
/**
* Saves the in-memory report as JSON. It needs no engine: this is the rescue copy when the
* tab's storage refused the last write and the PDF export cannot run.
*/
export function CopyReportButton() {
const t = useT()
const report = useReportStore((s) => s.report)
if (!report) return null
return (
<Button
variant="secondary"
onClick={() => downloadJson(JSON.stringify(report), 'faunosteo-brouillon')}
>
{t('session.held.download')}
</Button>
)
}
export interface CoreStoppedNoticeProps {
className?: string
}
/**
* The final state of the engine (three recoveries spent), never a retry: reload the page
* when the tab's copy of the report is saved; when it is not, the text says so and offers
* the copy instead of the reload (a reload would lose the latest edits).
*/
export default function CoreStoppedNotice({ className = '' }: CoreStoppedNoticeProps) {
const t = useT()
const unsaved = useReportStore(isUnsaved)
return (
<Notice tone="error" className={className}>
<p>{t(unsaved ? 'core.stopped_unsaved' : 'core.stopped')}</p>
<div className="mt-2">
{unsaved ? (
<CopyReportButton />
) : (
<Button variant="secondary" onClick={() => window.location.reload()}>
{t('core.reload')}
</Button>
)}
</div>
</Notice>
)
}
/** The notice on the pages that run the core, shown only once the engine stopped. */
export function CoreStoppedBanner({ className = '' }: CoreStoppedNoticeProps) {
return useCoreStopped() ? <CoreStoppedNotice className={className} /> : null
}
@@ -1,5 +1,7 @@
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice' import Notice from '@/components/ui/Notice'
import CoreStoppedNotice from '@/components/report/CoreStoppedNotice'
import { useCoreStopped } from '@/core/runtime'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
export interface CoreUnavailableProps { export interface CoreUnavailableProps {
@@ -8,10 +10,19 @@ export interface CoreUnavailableProps {
/** /**
* Degraded state of the sheet pages when the core module cannot run (CSP, network, an old * Degraded state of the sheet pages when the core module cannot run (CSP, network, an old
* browser, a refused sheet): the session data stays where it is, the practitioner retries. * browser, a refused sheet): the session data stays where it is, the practitioner retries. Once the engine
* stopped for good, the stopped notice replaces the retry, which could not work.
*/ */
export default function CoreUnavailable({ onRetry }: CoreUnavailableProps) { export default function CoreUnavailable({ onRetry }: CoreUnavailableProps) {
const t = useT() const t = useT()
const stopped = useCoreStopped()
if (stopped) {
return (
<main className="p-6 max-w-xl">
<CoreStoppedNotice />
</main>
)
}
return ( return (
<main className="p-6 space-y-3 max-w-xl"> <main className="p-6 space-y-3 max-w-xl">
<Notice tone="error">{t('sheet.core_unavailable')}</Notice> <Notice tone="error">{t('sheet.core_unavailable')}</Notice>
@@ -2,7 +2,7 @@ import { useState } from 'react'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog' import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice' import Notice from '@/components/ui/Notice'
import { todayIso } from '@/lib/dates' import { downloadJson } from '@/lib/download'
import { readSessionText, type SessionText } from '@/state/persistence' import { readSessionText, type SessionText } from '@/state/persistence'
import type { HeldText } from '@/state/reportStore' import type { HeldText } from '@/state/reportStore'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
@@ -18,30 +18,15 @@ export interface HeldSessionPanelProps {
type Pending = { action: 'discard'; text: SessionText } | { action: 'open' } type Pending = { action: 'discard'; text: SessionText } | { action: 'open' }
const REVOKE_DELAY_MS = 30_000
const FILE_STEM: Record<SessionText, string> = { const FILE_STEM: Record<SessionText, string> = {
draft: 'faunosteo-brouillon', draft: 'faunosteo-brouillon',
archive: 'faunosteo-archive', archive: 'faunosteo-archive',
} }
/** /** Saves the stored text verbatim (it is JSON.stringify output). */
* Saves the stored text verbatim. It is JSON.stringify output, whose lone surrogates are
* `\uXXXX` escapes, so the UTF-8 Blob is lossless. This copy may be the last one before
* a deletion: the anchor is attached while clicked and the URL revoked later, since some
* engines (WebKit) cancel a download whose URL is revoked at once.
*/
function downloadCopy(text: SessionText): void { function downloadCopy(text: SessionText): void {
const raw = readSessionText(text) const raw = readSessionText(text)
if (raw === null) return if (raw !== null) downloadJson(raw, FILE_STEM[text])
const url = URL.createObjectURL(new Blob([raw], { type: 'application/json' }))
const a = document.createElement('a')
a.href = url
a.download = `${FILE_STEM[text]}-${todayIso()}.json`
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS)
} }
function rowLabelKey(item: HeldText): string { function rowLabelKey(item: HeldText): string {
+16 -5
View File
@@ -1,11 +1,22 @@
import type { useT } from '@/i18n/useT' import type { useT } from '@/i18n/useT'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import { coreStopped } from './runtime' import { coreStopped } from './runtime'
/** The stopped text: the unsaved variant when the tab's copy of the report is stale. */
export function stoppedMessageKey(unsaved: boolean): string {
return unsaved ? 'core.stopped_unsaved' : 'core.stopped'
}
/** /**
* The alert after a core action failed: "try again" while a retry can work; once the engine * The alert after a core action failed: the fallback ("try again") while a retry can work;
* stopped after its three recoveries, the clear final state (reload the page, the report is * once the engine stopped after its three recoveries, the clear final state instead of a
* kept in the tab) instead of a retry that cannot succeed (owner decision 2026-10-15). * retry that cannot succeed (owner decision 2026-10-15). Callers with their own fallback
* key pass it; this file is the only place that names these keys in a `t()` call.
*/ */
export function coreFailureMessage(t: ReturnType<typeof useT>): string { export function coreFailureMessage(
return t(coreStopped() ? 'core.stopped' : 'core.action_failed') t: ReturnType<typeof useT>,
fallbackKey = 'core.action_failed',
): string {
if (!coreStopped()) return t(fallbackKey)
return t(stoppedMessageKey(isUnsaved(useReportStore.getState())))
} }
+11
View File
@@ -1,3 +1,4 @@
import { useSyncExternalStore } from 'react'
import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url' import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url'
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url' import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
import { import {
@@ -39,6 +40,16 @@ export function coreStopped(): boolean {
return runtime?.stopped ?? false return runtime?.stopped ?? false
} }
/** Subscribes to the runtime's status changes (stable identity for `useSyncExternalStore`). */
export function subscribeCore(listener: () => void): () => void {
return coreRuntime().subscribe(listener)
}
/** Whether the engine stopped for good on this page; re-renders when it does. */
export function useCoreStopped(): boolean {
return useSyncExternalStore(subscribeCore, coreStopped)
}
/** The page's runtime, created on first use. */ /** The page's runtime, created on first use. */
export function coreRuntime(): CoreRuntime { export function coreRuntime(): CoreRuntime {
runtime ??= new CoreRuntime(browserSource) runtime ??= new CoreRuntime(browserSource)
+1 -1
View File
@@ -14,7 +14,7 @@ import type {
/** /**
* The sheet-bound rules of the editor, run by the core on the session's sheet (R2): one * The sheet-bound rules of the editor, run by the core on the session's sheet (R2): one
* call per user action or load, never in a render. Each returns the core's outcome; the * call per user action or load, never in a render. Each returns the core's outcome; the
* caller stops on `ok: false` (nothing is written, the action shows `core.action_failed`). * caller stops on `ok: false` (nothing is written, the action shows `coreFailureMessage`).
*/ */
export interface FindingToggle { export interface FindingToggle {
+4 -1
View File
@@ -202,7 +202,10 @@ export const en: Dict = {
"Faunosteo's computation engine could not be loaded. Your session data is kept.", "Faunosteo's computation engine could not be loaded. Your session data is kept.",
'sheet.core_retry': 'Retry', 'sheet.core_retry': 'Retry',
'core.stopped': 'core.stopped':
"Faunosteo's computation engine stopped after several successive errors. Reload the page to start it again: your report is kept in this tab.", "Faunosteo's computation engine stopped after several errors. Reload the page to start it again: your report is kept in this tab.",
'core.stopped_unsaved':
"Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest changes are not saved and would be lost if you reload the page. Download a copy before reloading.",
'core.reload': 'Reload the page',
'canvas.view_unavailable': 'canvas.view_unavailable':
"This anatomical view cannot be displayed: its drawing was refused by the safety checks or could not be composed. Your report is not changed.", "This anatomical view cannot be displayed: its drawing was refused by the safety checks or could not be composed. Your report is not changed.",
'core.action_failed': 'core.action_failed':
+4 -1
View File
@@ -216,7 +216,10 @@ export const fr: Dict = {
"Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.", "Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.",
'sheet.core_retry': 'Réessayer', 'sheet.core_retry': 'Réessayer',
'core.stopped': 'core.stopped':
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs successives. Rechargez la page pour le relancer : votre bilan est conservé dans cet onglet.", "Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs. Rechargez la page pour le relancer : votre bilan est conservé dans cet onglet.",
'core.stopped_unsaved':
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la page. Téléchargez une copie avant de recharger.",
'core.reload': 'Recharger la page',
'canvas.view_unavailable': 'canvas.view_unavailable':
"Cette vue anatomique ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé. Votre bilan n'est pas modifié.", "Cette vue anatomique ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé. Votre bilan n'est pas modifié.",
'core.action_failed': 'core.action_failed':
+20
View File
@@ -0,0 +1,20 @@
import { todayIso } from '@/lib/dates'
const REVOKE_DELAY_MS = 30_000
/**
* Saves `raw` as `<stem>-<date>.json`. A lone surrogate in a JSON.stringify output is a
* `\uXXXX` escape, so the UTF-8 Blob is lossless. This copy may be the last one before a
* deletion: the anchor is attached while clicked and the URL revoked later, since some
* engines (WebKit) cancel a download whose URL is revoked at once.
*/
export function downloadJson(raw: string, stem: string): void {
const url = URL.createObjectURL(new Blob([raw], { type: 'application/json' }))
const a = document.createElement('a')
a.href = url
a.download = `${stem}-${todayIso()}.json`
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS)
}
+20 -12
View File
@@ -141,6 +141,10 @@ const OK: ActionResult = { ok: true }
const FAILED: ActionResult = { ok: false } const FAILED: ActionResult = { ok: false }
const HELD: ActionResult = { ok: false, reason: 'held' } const HELD: ActionResult = { ok: false, reason: 'held' }
/** The tab's storage refused the last write: the in-memory report is the only copy. */
export const isUnsaved = (s: Pick<ReportStore, 'saveFailed' | 'report'>): boolean =>
s.saveFailed && s.report !== null
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) { function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s)) set((s) => (s.report ? update(s.report, s) : s))
} }
@@ -243,23 +247,24 @@ function restore(
/** /**
* Before a new session replaces texts this page never read: an unreadable draft (and its * Before a new session replaces texts this page never read: an unreadable draft (and its
* archive) or an unreadable archive is set aside first; a readable draft is replaced as * archive) or an unreadable archive is set aside first; a readable draft is replaced as
* before. False when something could not be set aside, or could not even be read. * before. HELD when something could not be set aside; FAILED when the core could not even
* read the draft (not a held text: nothing is set aside, nothing is written).
*/ */
function releaseUnreadSession( function releaseUnreadSession(
index: SheetIndex, index: SheetIndex,
persistence: ReportPersistence, persistence: ReportPersistence,
archives: ArchivePersistence, archives: ArchivePersistence,
): boolean { ): ActionResult {
const draft = persistence.loadText() const draft = persistence.loadText()
const archiveText = archives.loadText() const archiveText = archives.loadText()
if (draft === null) return restoreOrphanArchive(archiveText) === null if (draft === null) return restoreOrphanArchive(archiveText) === null ? OK : HELD
const outcome = index.ops.restoreDraft(draft, archiveText) const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) { if (!outcome.ok) {
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return false if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return FAILED
return quarantineSession(draft, archiveText) return quarantineSession(draft, archiveText) ? OK : HELD
} }
if (!outcome.value.archiveRejected || archiveText === null) return true if (!outcome.value.archiveRejected || archiveText === null) return OK
return quarantine('archive', archiveText, ARCHIVE_KEY) return quarantine('archive', archiveText, ARCHIVE_KEY) ? OK : HELD
} }
export function createReportStore( export function createReportStore(
@@ -278,9 +283,10 @@ export function createReportStore(
} }
/** A new session may start: either one is open (its texts are this store's), or none is left unread. */ /** A new session may start: either one is open (its texts are this store's), or none is left unread. */
const mayStartSession = (index: SheetIndex) => const mayStartSession = (index: SheetIndex): ActionResult =>
store.getState().report !== null || store.getState().report !== null
releaseUnreadSession(index, persistence, archives) ? OK
: releaseUnreadSession(index, persistence, archives)
const store = create<ReportStore>((set, get) => ({ const store = create<ReportStore>((set, get) => ({
report: null, report: null,
@@ -289,7 +295,8 @@ export function createReportStore(
saveFailed: false, saveFailed: false,
initReport: (draft, sheet, index) => { initReport: (draft, sheet, index) => {
if (!mayStartSession(index)) return HELD const may = mayStartSession(index)
if (!may.ok) return may
const outcome = reportOps.newReport({ const outcome = reportOps.newReport({
draft, draft,
sheet, sheet,
@@ -303,7 +310,8 @@ export function createReportStore(
}, },
hydrateImport: ({ report, archive }, index) => { hydrateImport: ({ report, archive }, index) => {
if (!mayStartSession(index)) return HELD const may = mayStartSession(index)
if (!may.ok) return may
set(withArchive({ report, activeObservationIndex: 0 }, archive)) set(withArchive({ report, activeObservationIndex: 0 }, archive))
return OK return OK
}, },
+13
View File
@@ -6,6 +6,19 @@ export function testCoreRuntime(): Promise<CoreRuntime> {
return nodeCoreRuntime('pkg') 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). */ /** A runtime whose module never loads (CSP refusal, network failure). */
export function unavailableCoreRuntime(): CoreRuntime { export function unavailableCoreRuntime(): CoreRuntime {
return new CoreRuntime({ return new CoreRuntime({
@@ -1,16 +1,17 @@
import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest' 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 userEvent from '@testing-library/user-event'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import type { CoreRuntime } from '@faunosteo/core-wasm' import { coreRuntime } from '@/core/runtime'
import { coreRuntime, setCoreRuntime } from '@/core/runtime'
import { coreFailureMessage } from '@/core/failure' import { coreFailureMessage } from '@/core/failure'
import { useReportStore } from '@/state/reportStore'
import { buildViewSvg } from '@/anatomy/drawing' import { buildViewSvg } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex' import type { SheetIndex } from '@/services/sheetIndex'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr' import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en' 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 let sheet: SheetIndex
beforeAll(async () => { beforeAll(async () => {
@@ -141,15 +142,18 @@ describe('AnatomyCanvas', () => {
await screen.findByText(fr['sheet.core_unavailable']!) await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.queryByText(fr['canvas.view_unavailable']!)).toBeNull() expect(screen.queryByText(fr['canvas.view_unavailable']!)).toBeNull()
engineDown = false engineDown = false
const retry = vi.spyOn(coreRuntime(), 'retry')
await user.click(screen.getByRole('button', { name: fr['sheet.core_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()) await waitFor(() => expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull())
expect(screen.queryByText(fr['sheet.core_unavailable']!)).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 () => { it('after the recoveries are spent, shows the final state with no retry; alerts say the same', async () => {
useLocaleStore.setState({ locale: 'fr' }) useLocaleStore.setState({ locale: 'fr' })
const live = coreRuntime() const setStopped = controlStopped(coreRuntime(), true)
setCoreRuntime({ stopped: true } as unknown as CoreRuntime)
try { try {
const down = Object.create(sheet) as SheetIndex const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'internal' }) down.canvasSvg = () => ({ ok: false, kind: 'internal' })
@@ -158,9 +162,42 @@ describe('AnatomyCanvas', () => {
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull() expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.stopped']) expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.stopped'])
} finally { } finally {
setCoreRuntime(live) setStopped(false)
} }
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.action_failed']) 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 () => { it('words both failures in English too', async () => {
@@ -211,3 +211,32 @@ describe('HomeRoute import: size gate', () => {
expect(useReportStore.getState().report).toBeNull() 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() 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)) const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft) sessionStorage.setItem(DRAFT_KEY, draft)
const broken = { const broken = {
...sheet, ...sheet,
ops: { restoreDraft: () => ({ ok: false, kind: 'core_unavailable' }) }, ops: { restoreDraft: () => ({ ok: false, kind: 'core_unavailable' }) },
} as unknown as SheetIndex } as unknown as SheetIndex
expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({ const before = snapshotStorage()
ok: false, expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({ ok: false })
reason: 'held', expect(
}) store().hydrateImport({ report: minimalReport(sheet), archive: null }, broken),
).toEqual({ ok: false })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft) expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(snapshotStorage()).toEqual(before)
expect(store().report).toBeNull()
}) })
}) })
+21 -5
View File
@@ -505,11 +505,20 @@ Closed failure kinds: `invalid_json`, `invalid_shape`, `unknown_op`,
imported in advance (no network needed), at most 3 times per page; calls imported in advance (no network needed), at most 3 times per page; calls
made meanwhile answer `core_unavailable`. Sheet handles carry the instance made meanwhile answer `core_unavailable`. Sheet handles carry the instance
generation and are rebuilt from the retained payload, never called on a generation and are rebuilt from the retained payload, never called on a
dropped instance. dropped instance. A recovery that fails below the cap (network lost, spare
record missing) is not final: the next call or `ready()` restarts the
runtime, reusing the compiled module; a restart is not a recovery and does
not touch the counter. A failed first load is restarted by `retry()` only.
`subscribe(listener)` reports status changes after a microtask (a throwing
listener changes nothing); the pages follow `stopped` through it.
- A load failure (CSP, network, old browser) gives `core_unavailable`; the - A load failure (CSP, network, old browser) gives `core_unavailable`; the
editor and the new-report page show the notice with "Réessayer" (the retry editor and the new-report page show the notice with "Réessayer" (the retry
clears the runtime, `useSheet` and provider caches), never redirect, never clears the runtime, `useSheet` and provider caches), never redirect, never
read or write the draft. read or write the draft. Once the engine stopped, the notice is the stopped
one (§9.4 item 7), without a retry.
- Editor, storage full while the engine runs: the `editor.save_failed` banner
gains the engine-free "Télécharger une copie" button, and a `beforeunload`
guard asks before a reload or close while the report is only in memory.
- Two builds: `pkg/` ships (no trap export, checked by `scripts/wasm-build.sh` - Two builds: `pkg/` ships (no trap export, checked by `scripts/wasm-build.sh`
and a test), `pkg-proofs/` carries the trap exports for the tests. Both and a test), `pkg-proofs/` carries the trap exports for the tests. Both
carry `BUILD_STAMP` (hash of the Rust sources); the vitest global setup of carry `BUILD_STAMP` (hash of the Rust sources); the vitest global setup of
@@ -810,9 +819,16 @@ imports it and restyles `data-state` in place as before.
decision 2026-10-15): the engine did not run (`core_unavailable`, decision 2026-10-15): the engine did not run (`core_unavailable`,
`internal`: the existing `sheet.core_unavailable` notice with "Réessayer", `internal`: the existing `sheet.core_unavailable` notice with "Réessayer",
the retry builds again on a fresh instance), the engine stopped after its the retry builds again on a fresh instance), the engine stopped after its
three recoveries (`CoreRuntime.stopped`: the `core.stopped` notice, "reload three recoveries (`CoreRuntime.stopped`: no retry anywhere; the canvas shows
the page, your report is kept in this tab", no retry; the editor's action the stopped text, and `CoreStoppedNotice` sits in the editor's banner slot
alerts say the same instead of "try again") or the view itself cannot be in place of the storage-full text, at the top of Home and New report, and
replaces the full-page `CoreUnavailable` retry. Two variants: the tab's
copy of the report is saved, `core.stopped` with "Recharger la page"; the
tab's storage refused the last write (`saveFailed`), `core.stopped_unsaved`
with "Télécharger une copie" (the in-memory report as JSON, no engine
needed), never the reload button. Action, export, import and new-report
alerts say the same text instead of "try again"; "Réessayer" on the canvas
restarts the engine before building again) or the view itself cannot be
drawn (`svg_rejected`, drawn (`svg_rejected`,
`no_asset`, `unknown_view`, `invalid_character`, a parse failure: the `no_asset`, `unknown_view`, `invalid_character`, a parse failure: the
`canvas.view_unavailable` notice, no retry since nothing would change). The `canvas.view_unavailable` notice, no retry since nothing would change). The
+61 -12
View File
@@ -13,6 +13,8 @@ import {
* a fresh one is created from the compiled module kept in memory and a glue module record * a fresh one is created from the compiled module kept in memory and a glue module record
* imported in advance (a trap needs no network). Calls made while it is re-created answer * imported in advance (a trap needs no network). Calls made while it is re-created answer
* `core_unavailable`; after `maxRecoveries` traps the page stays unavailable until reload. * `core_unavailable`; after `maxRecoveries` traps the page stays unavailable until reload.
* A recovery or restart that fails below the cap is not final: the next call or `ready()`
* restarts the runtime (a restart is not a recovery and does not touch the counter).
*/ */
/** What the wasm-bindgen glue (`--target web`) exports. */ /** What the wasm-bindgen glue (`--target web`) exports. */
@@ -60,6 +62,7 @@ export class CoreRuntime {
private imports = 0 private imports = 0
private recoveries = 0 private recoveries = 0
private readonly maxRecoveries: number private readonly maxRecoveries: number
private readonly listeners = new Set<() => void>()
/** Increments with every instance; sheet handles of an older generation are dropped. */ /** Increments with every instance; sheet handles of an older generation are dropped. */
generation = 0 generation = 0
@@ -82,9 +85,30 @@ export class CoreRuntime {
return this.state === 'unavailable' && this.recoveries >= this.maxRecoveries return this.state === 'unavailable' && this.recoveries >= this.maxRecoveries
} }
/**
* Unavailable after an instance already ran (a failed recovery or restart) with
* recoveries left: the next call may bring it back. A failed FIRST load is not restarted
* implicitly, only by `retry()`.
*/
private get restartable(): boolean {
return this.state === 'unavailable' && !this.stopped && this.generation > 0
}
/**
* Calls `listener` (after a microtask, never inside a load or recovery) each time the
* status changes; returns the unsubscribe function.
*/
subscribe(listener: () => void): () => void {
this.listeners.add(listener)
return () => {
this.listeners.delete(listener)
}
}
/** Loads the module on first use; true when calls can be made. */ /** Loads the module on first use; true when calls can be made. */
ready(): Promise<boolean> { ready(): Promise<boolean> {
if (this.state === 'ready') return Promise.resolve(true) if (this.state === 'ready') return Promise.resolve(true)
if (this.restartable) return this.retry()
if (this.state === 'unavailable') return Promise.resolve(false) if (this.state === 'unavailable') return Promise.resolve(false)
this.pending ??= this.load() this.pending ??= this.load()
return this.pending return this.pending
@@ -94,12 +118,18 @@ export class CoreRuntime {
retry(): Promise<boolean> { retry(): Promise<boolean> {
if (this.state !== 'unavailable') return this.ready() if (this.state !== 'unavailable') return this.ready()
if (this.recoveries >= this.maxRecoveries) return Promise.resolve(false) if (this.recoveries >= this.maxRecoveries) return Promise.resolve(false)
this.state = 'idle' this.setState('idle')
this.compiled = null // Only a failed first load clears the compiled module: once an instance ran, it is sound.
if (this.generation === 0) this.compiled = null
this.pending = null this.pending = null
return this.ready() return this.ready()
} }
/** Starts a restart when the next call may succeed (the current call still answers). */
kickRestart(): void {
if (this.restartable) void this.retry()
}
/** Runs a free operation. */ /** Runs a free operation. */
call<T>(op: string, input: string): CoreOutcome<T> { call<T>(op: string, input: string): CoreOutcome<T> {
return this.invoke((glue) => parseOutcome<T>(glue.call(op, input))) return this.invoke((glue) => parseOutcome<T>(glue.call(op, input)))
@@ -116,7 +146,10 @@ export class CoreRuntime {
*/ */
invoke<T>(fn: (glue: GlueModule) => CoreOutcome<T>): CoreOutcome<T> { invoke<T>(fn: (glue: GlueModule) => CoreOutcome<T>): CoreOutcome<T> {
const glue = this.glue const glue = this.glue
if (this.state !== 'ready' || !glue) return CORE_UNAVAILABLE if (this.state !== 'ready' || !glue) {
this.kickRestart()
return CORE_UNAVAILABLE
}
try { try {
return fn(glue) return fn(glue)
} catch (error) { } catch (error) {
@@ -126,12 +159,12 @@ export class CoreRuntime {
} }
private async load(): Promise<boolean> { private async load(): Promise<boolean> {
this.state = 'loading' this.setState('loading')
try { try {
await this.instantiate(await this.source.importGlue(this.nextImport())) await this.instantiate(await this.source.importGlue(this.nextImport()))
return true return true
} catch { } catch {
this.state = 'unavailable' this.setState('unavailable')
this.pending = null this.pending = null
return false return false
} }
@@ -142,12 +175,28 @@ export class CoreRuntime {
await glue.default({ module_or_path: await this.compiled }) await glue.default({ module_or_path: await this.compiled })
this.glue = glue this.glue = glue
this.generation += 1 this.generation += 1
this.state = 'ready' this.setState('ready')
this.spare = this.source this.spare = this.source
.importGlue(this.nextImport()) .importGlue(this.nextImport())
.catch(() => null) .catch(() => null)
} }
private setState(next: CoreStatus): void {
if (next === this.state) return
this.state = next
queueMicrotask(() => this.notify())
}
private notify(): void {
for (const listener of [...this.listeners]) {
try {
listener()
} catch {
// A listener never changes the state machine.
}
}
}
private nextImport(): number { private nextImport(): number {
this.imports += 1 this.imports += 1
return this.imports return this.imports
@@ -156,11 +205,11 @@ export class CoreRuntime {
private poison(): void { private poison(): void {
this.glue = null this.glue = null
if (this.recoveries >= this.maxRecoveries) { if (this.recoveries >= this.maxRecoveries) {
this.state = 'unavailable' this.setState('unavailable')
return return
} }
this.recoveries += 1 this.recoveries += 1
this.state = 'recovering' this.setState('recovering')
this.pending = this.recover() this.pending = this.recover()
} }
@@ -172,7 +221,7 @@ export class CoreRuntime {
) )
return true return true
} catch { } catch {
this.state = 'unavailable' this.setState('unavailable')
return false return false
} finally { } finally {
this.pending = null this.pending = null
@@ -220,9 +269,9 @@ export class SheetSession {
/** The handle of the live instance; a handle of a dropped instance is never called. */ /** The handle of the live instance; a handle of a dropped instance is never called. */
private current(): CoreOutcome<GlueSheetHandle> { private current(): CoreOutcome<GlueSheetHandle> {
if (this.handle && this.handleGeneration === this.runtime.generation) { if (this.handle && this.handleGeneration === this.runtime.generation) {
return this.runtime.status === 'ready' if (this.runtime.status === 'ready') return { ok: true, value: this.handle }
? { ok: true, value: this.handle } this.runtime.kickRestart()
: CORE_UNAVAILABLE return CORE_UNAVAILABLE
} }
this.handle = null this.handle = null
return this.runtime.invoke((glue) => { return this.runtime.invoke((glue) => {
+129
View File
@@ -47,6 +47,38 @@ function countingSource(offlineAfter = Infinity) {
return source return source
} }
/**
* Counts compiles and imports; the numbered glue imports in `failing` are refused like a
* lost network (import 1 is the first instance, 2 its spare, 3 the recovery's fallback).
*/
function flakySource(failing: number[]) {
const inner = nodeCoreSource('pkg-proofs')
const source = {
compiles: 0,
imports: 0,
compile: () => {
source.compiles += 1
return inner.compile()
},
importGlue: async (n: number): Promise<GlueModule> => {
source.imports += 1
if (failing.includes(source.imports)) throw new TypeError('offline')
return inner.importGlue(n)
},
}
return source
}
/**
* A handle of a trapped instance is freed by the glue's finalizer inside the dead module,
* which throws out of the garbage collector at a random later time. Tests that trap with a
* live handle keep it reachable until the process ends.
*/
const retainedHandles: unknown[] = []
function retainHandle(sheet: object): void {
retainedHandles.push((sheet as { handle: unknown }).handle)
}
/** Traps the live instance through the proofs build (stack exhaustion). */ /** Traps the live instance through the proofs build (stack exhaustion). */
function trap(runtime: CoreRuntime) { function trap(runtime: CoreRuntime) {
return runtime.invoke((glue) => { return runtime.invoke((glue) => {
@@ -91,6 +123,7 @@ describe('core runtime', () => {
ok: true, ok: true,
value: { ref: { sheetId: 'sheet', versionId: null } }, value: { ref: { sheetId: 'sheet', versionId: null } },
}) })
retainHandle(sheet)
trap(runtime) trap(runtime)
expect(sheet.call('index_data', '')).toMatchObject({ expect(sheet.call('index_data', '')).toMatchObject({
kind: 'core_unavailable', kind: 'core_unavailable',
@@ -180,4 +213,100 @@ describe('core runtime', () => {
expect(runtime.sheet(BUNDLE).open()).toMatchObject({ ok: false, kind: 'internal' }) expect(runtime.sheet(BUNDLE).open()).toMatchObject({ ok: false, kind: 'internal' })
expect(runtime.status).not.toBe('ready') expect(runtime.status).not.toBe('ready')
}) })
it('allows three recoveries by default, then stops on the fourth trap', async () => {
const runtime = new CoreRuntime(countingSource())
await runtime.ready()
for (let i = 0; i < 3; i += 1) {
trap(runtime)
expect(await runtime.ready()).toBe(true)
expect(runtime.stopped).toBe(false)
}
trap(runtime)
expect(runtime.stopped).toBe(true)
expect(await runtime.retry()).toBe(false)
})
it('restarts on the next call after a failed recovery below the cap', async () => {
const source = flakySource([2, 3])
const runtime = new CoreRuntime(source)
await runtime.ready()
trap(runtime)
expect(await runtime.ready()).toBe(false)
expect(runtime.stopped).toBe(false)
expect(runtime.ready()).toBeInstanceOf(Promise)
expect(await runtime.ready()).toBe(true)
expect(runtime.call('core_version', '')).toMatchObject({ ok: true })
// A restart is not a recovery, and it reuses the compiled module.
expect(source.compiles).toBe(1)
})
it('kicks the restart from a call and answers the next one', async () => {
const runtime = new CoreRuntime(flakySource([2, 3]))
await runtime.ready()
const sheet = runtime.sheet(BUNDLE)
trap(runtime)
expect(await runtime.ready()).toBe(false)
expect(runtime.call('core_version', '')).toMatchObject({ kind: 'core_unavailable' })
expect(runtime.status).toBe('loading')
expect(await runtime.ready()).toBe(true)
expect(sheet.call('index_data', '')).toMatchObject({ ok: true })
})
it('restarts from a sheet call as well', async () => {
const runtime = new CoreRuntime(flakySource([2, 3]))
await runtime.ready()
const sheet = runtime.sheet(BUNDLE)
expect(sheet.open()).toEqual({ ok: true, value: null })
retainHandle(sheet)
trap(runtime)
await runtime.ready()
expect(sheet.call('index_data', '')).toMatchObject({ kind: 'core_unavailable' })
expect(runtime.status).toBe('loading')
await runtime.ready()
expect(sheet.call('index_data', '')).toMatchObject({ ok: true })
})
it('does not restart once the cap is spent', async () => {
const source = flakySource([2, 3])
const runtime = new CoreRuntime(source, { maxRecoveries: 1 })
await runtime.ready()
trap(runtime)
expect(await runtime.ready()).toBe(false)
expect(runtime.stopped).toBe(true)
const imports = source.imports
expect(runtime.call('core_version', '')).toMatchObject({ kind: 'core_unavailable' })
expect(await runtime.ready()).toBe(false)
expect(runtime.status).toBe('unavailable')
expect(source.imports).toBe(imports)
})
it('does not restart a failed first load from a call', async () => {
const source = flakySource([1])
const runtime = new CoreRuntime(source)
expect(await runtime.ready()).toBe(false)
expect(runtime.call('core_version', '')).toMatchObject({ kind: 'core_unavailable' })
expect(await runtime.ready()).toBe(false)
expect(source.imports).toBe(1)
expect(await runtime.retry()).toBe(true)
})
it('notifies listeners after a microtask and survives a throwing one', async () => {
const runtime = new CoreRuntime(countingSource(), { maxRecoveries: 0 })
await runtime.ready()
const calls: boolean[] = []
runtime.subscribe(() => {
throw new Error('listener bug')
})
const unsubscribe = runtime.subscribe(() => calls.push(runtime.stopped))
trap(runtime)
expect(calls).toEqual([])
await Promise.resolve()
expect(calls).toEqual([true])
expect(runtime.stopped).toBe(true)
unsubscribe()
await runtime.retry()
await Promise.resolve()
expect(calls).toEqual([true])
})
}) })