diff --git a/CHANGELOG.md b/CHANGELOG.md index 80addde8..0ca474f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. - 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). -- 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) diff --git a/apps/app/eslint.config.js b/apps/app/eslint.config.js index 12964c78..8eb229f0 100644 --- a/apps/app/eslint.config.js +++ b/apps/app/eslint.config.js @@ -3,6 +3,21 @@ import tseslint from 'typescript-eslint' import pluginReact from 'eslint-plugin-react' 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('')` 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( { 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)], + }, + }, ) diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index 4e70e053..8c748874 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -14,11 +14,13 @@ import EditInfosDialog, { type Identity, } from '@/components/report/EditInfosDialog' import DisclaimerDialog from '@/components/report/DisclaimerDialog' +import CoreStoppedNotice, { CopyReportButton } from '@/components/report/CoreStoppedNotice' import CoreUnavailable from '@/components/report/CoreUnavailable' import HeldSessionPanel from '@/components/report/HeldSessionPanel' import Notice from '@/components/ui/Notice' import Button from '@/components/ui/Button' import { + isUnsaved, useReportStore, type ActionResult, type HeldText, @@ -37,6 +39,7 @@ import type { RebaseOutcome } from '@faunosteo/core-wasm/types' import { useT } from '@/i18n/useT' import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { coreFailureMessage } from '@/core/failure' +import { useCoreStopped } from '@/core/runtime' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' @@ -72,6 +75,8 @@ export default function EditorRoute() { const { report, activeObservationIndex: activeIndex } = store // Without a report yet (draft restore), the default species' sheet carries the migration map. const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID) + const stopped = useCoreStopped() + const unsaved = isUnsaved(store) const [detailViewId, setDetailViewId] = useState(null) const [vertebraTarget, setVertebraTarget] = useState( @@ -132,6 +137,17 @@ export default function EditorRoute() { navigate('/') }, [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), []) useEffect(() => { @@ -248,7 +264,7 @@ export default function EditorRoute() { } } catch (err) { console.error('PDF export failed', err) - window.alert(t('editor.export_failed')) + window.alert(coreFailureMessage(t, 'editor.export_failed')) } finally { setExporting(false) } @@ -300,10 +316,17 @@ export default function EditorRoute() { }) } /> - {store.saveFailed && ( - - {t('editor.save_failed')} - + {stopped ? ( + + ) : ( + store.saveFailed && ( + +

{t('editor.save_failed')}

+
+ +
+
+ ) )}
diff --git a/apps/app/src/app/routes/HomeRoute.tsx b/apps/app/src/app/routes/HomeRoute.tsx index 50ce3020..04bb0787 100644 --- a/apps/app/src/app/routes/HomeRoute.tsx +++ b/apps/app/src/app/routes/HomeRoute.tsx @@ -6,6 +6,7 @@ import type { } from '@faunosteo/core-wasm/types' import AppHeader from '@/components/brand/AppHeader' import HomeSpaceLink from '@/components/brand/HomeSpaceLink' +import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice' import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' import { @@ -18,6 +19,7 @@ import { useReportStore } from '@/state/reportStore' import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet' import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { useT } from '@/i18n/useT' +import { coreFailureMessage } from '@/core/failure' type Translate = ReturnType @@ -106,7 +108,7 @@ function importErrorMessage(err: unknown, t: Translate): string { case 'lone_surrogate': return t('home.import.error_lone_surrogate') 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. 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')) navigate('/editor') return @@ -166,6 +170,7 @@ export default function HomeRoute() { +
{noSheet && ( diff --git a/apps/app/src/app/routes/NewReportRoute.tsx b/apps/app/src/app/routes/NewReportRoute.tsx index c3cf55ea..0b3601da 100644 --- a/apps/app/src/app/routes/NewReportRoute.tsx +++ b/apps/app/src/app/routes/NewReportRoute.tsx @@ -4,6 +4,7 @@ import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types' import PractitionerForm from '@/components/report/PractitionerForm' import AnimalForm from '@/components/report/AnimalForm' import AppHeader from '@/components/brand/AppHeader' +import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice' import Button from '@/components/ui/Button' import Input from '@/components/ui/Input' 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. const index = await loadSheetIndex(DEFAULT_SPECIES_ID) if (!index) { - window.alert(t('sheet.core_unavailable')) + window.alert(coreFailureMessage(t, 'sheet.core_unavailable')) return } const created = initReport( @@ -79,6 +80,7 @@ export default function NewReportRoute() {
+

{t('new_report.title')}

diff --git a/apps/app/src/components/canvas/AnatomyCanvas.tsx b/apps/app/src/components/canvas/AnatomyCanvas.tsx index 527eed4c..abef59d5 100644 --- a/apps/app/src/components/canvas/AnatomyCanvas.tsx +++ b/apps/app/src/components/canvas/AnatomyCanvas.tsx @@ -1,7 +1,10 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { buildViewSvg, type ViewFailure, type ViewStates } from '@/anatomy/drawing' import type { SheetIndex } from '@/services/sheetIndex' +import { coreRuntime, useCoreStopped } from '@/core/runtime' +import { stoppedMessageKey } from '@/core/failure' import { useLocaleStore } from '@/state/localeStore' +import { isUnsaved, useReportStore } from '@/state/reportStore' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' import Button from '@/components/ui/Button' import Notice from '@/components/ui/Notice' @@ -17,7 +20,7 @@ export interface AnatomyCanvasProps { 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 = { engine: 'sheet.core_unavailable', 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 * 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 - * 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. */ 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. const [attempt, setAttempt] = useState(0) const [failure, setFailure] = useState(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(() => { const host = svgRef.current @@ -140,11 +155,11 @@ export default function AnatomyCanvas({ {failure && (
- {t(FAILURE_MESSAGE[failure])} - {failure === 'engine' && ( - + + {t(engineStopped ? stoppedMessageKey(unsaved) : FAILURE_MESSAGE[failure])} + + {failure === 'engine' && !engineStopped && ( + )}
diff --git a/apps/app/src/components/report/CoreStoppedNotice.tsx b/apps/app/src/components/report/CoreStoppedNotice.tsx new file mode 100644 index 00000000..dc45ca41 --- /dev/null +++ b/apps/app/src/components/report/CoreStoppedNotice.tsx @@ -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 ( + + ) +} + +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 ( + +

{t(unsaved ? 'core.stopped_unsaved' : 'core.stopped')}

+
+ {unsaved ? ( + + ) : ( + + )} +
+
+ ) +} + +/** The notice on the pages that run the core, shown only once the engine stopped. */ +export function CoreStoppedBanner({ className = '' }: CoreStoppedNoticeProps) { + return useCoreStopped() ? : null +} diff --git a/apps/app/src/components/report/CoreUnavailable.tsx b/apps/app/src/components/report/CoreUnavailable.tsx index a353b422..f495574f 100644 --- a/apps/app/src/components/report/CoreUnavailable.tsx +++ b/apps/app/src/components/report/CoreUnavailable.tsx @@ -1,5 +1,7 @@ import Button from '@/components/ui/Button' import Notice from '@/components/ui/Notice' +import CoreStoppedNotice from '@/components/report/CoreStoppedNotice' +import { useCoreStopped } from '@/core/runtime' import { useT } from '@/i18n/useT' 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 - * 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) { const t = useT() + const stopped = useCoreStopped() + if (stopped) { + return ( +
+ +
+ ) + } return (
{t('sheet.core_unavailable')} diff --git a/apps/app/src/components/report/HeldSessionPanel.tsx b/apps/app/src/components/report/HeldSessionPanel.tsx index e9afc392..dddce818 100644 --- a/apps/app/src/components/report/HeldSessionPanel.tsx +++ b/apps/app/src/components/report/HeldSessionPanel.tsx @@ -2,7 +2,7 @@ import { useState } from 'react' import Button from '@/components/ui/Button' import Dialog from '@/components/ui/Dialog' import Notice from '@/components/ui/Notice' -import { todayIso } from '@/lib/dates' +import { downloadJson } from '@/lib/download' import { readSessionText, type SessionText } from '@/state/persistence' import type { HeldText } from '@/state/reportStore' import { useT } from '@/i18n/useT' @@ -18,30 +18,15 @@ export interface HeldSessionPanelProps { type Pending = { action: 'discard'; text: SessionText } | { action: 'open' } -const REVOKE_DELAY_MS = 30_000 - const FILE_STEM: Record = { draft: 'faunosteo-brouillon', archive: 'faunosteo-archive', } -/** - * 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. - */ +/** Saves the stored text verbatim (it is JSON.stringify output). */ function downloadCopy(text: SessionText): void { const raw = readSessionText(text) - if (raw === null) return - 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) + if (raw !== null) downloadJson(raw, FILE_STEM[text]) } function rowLabelKey(item: HeldText): string { diff --git a/apps/app/src/core/failure.ts b/apps/app/src/core/failure.ts index 739e60d3..645a5d70 100644 --- a/apps/app/src/core/failure.ts +++ b/apps/app/src/core/failure.ts @@ -1,11 +1,22 @@ import type { useT } from '@/i18n/useT' +import { isUnsaved, useReportStore } from '@/state/reportStore' 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 - * stopped after its three recoveries, the clear final state (reload the page, the report is - * kept in the tab) instead of a retry that cannot succeed (owner decision 2026-10-15). + * The alert after a core action failed: the fallback ("try again") while a retry can work; + * once the engine stopped after its three recoveries, the clear final state instead of a + * 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): string { - return t(coreStopped() ? 'core.stopped' : 'core.action_failed') +export function coreFailureMessage( + t: ReturnType, + fallbackKey = 'core.action_failed', +): string { + if (!coreStopped()) return t(fallbackKey) + return t(stoppedMessageKey(isUnsaved(useReportStore.getState()))) } diff --git a/apps/app/src/core/runtime.ts b/apps/app/src/core/runtime.ts index f0910b7c..2a77ab6d 100644 --- a/apps/app/src/core/runtime.ts +++ b/apps/app/src/core/runtime.ts @@ -1,3 +1,4 @@ +import { useSyncExternalStore } from 'react' import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url' import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url' import { @@ -39,6 +40,16 @@ export function coreStopped(): boolean { 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. */ export function coreRuntime(): CoreRuntime { runtime ??= new CoreRuntime(browserSource) diff --git a/apps/app/src/core/sheetOps.ts b/apps/app/src/core/sheetOps.ts index 95b34c57..9cde325b 100644 --- a/apps/app/src/core/sheetOps.ts +++ b/apps/app/src/core/sheetOps.ts @@ -14,7 +14,7 @@ import type { /** * 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 - * 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 { diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index cf148a2a..ae4d7683 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -202,7 +202,10 @@ export const en: Dict = { "Faunosteo's computation engine could not be loaded. Your session data is kept.", 'sheet.core_retry': 'Retry', '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': "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': diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 1ead74b7..966843d6 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -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.", 'sheet.core_retry': 'Réessayer', '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': "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': diff --git a/apps/app/src/lib/download.ts b/apps/app/src/lib/download.ts new file mode 100644 index 00000000..e19ec8e1 --- /dev/null +++ b/apps/app/src/lib/download.ts @@ -0,0 +1,20 @@ +import { todayIso } from '@/lib/dates' + +const REVOKE_DELAY_MS = 30_000 + +/** + * Saves `raw` as `-.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) +} diff --git a/apps/app/src/state/reportStore.ts b/apps/app/src/state/reportStore.ts index a6040ad8..c198b4fb 100644 --- a/apps/app/src/state/reportStore.ts +++ b/apps/app/src/state/reportStore.ts @@ -141,6 +141,10 @@ const OK: ActionResult = { ok: true } const FAILED: ActionResult = { ok: false } 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): boolean => + s.saveFailed && s.report !== null + function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) { 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 * 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( index: SheetIndex, persistence: ReportPersistence, archives: ArchivePersistence, -): boolean { +): ActionResult { const draft = persistence.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) if (!outcome.ok) { - if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return false - return quarantineSession(draft, archiveText) + if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return FAILED + return quarantineSession(draft, archiveText) ? OK : HELD } - if (!outcome.value.archiveRejected || archiveText === null) return true - return quarantine('archive', archiveText, ARCHIVE_KEY) + if (!outcome.value.archiveRejected || archiveText === null) return OK + return quarantine('archive', archiveText, ARCHIVE_KEY) ? OK : HELD } 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. */ - const mayStartSession = (index: SheetIndex) => - store.getState().report !== null || - releaseUnreadSession(index, persistence, archives) + const mayStartSession = (index: SheetIndex): ActionResult => + store.getState().report !== null + ? OK + : releaseUnreadSession(index, persistence, archives) const store = create((set, get) => ({ report: null, @@ -289,7 +295,8 @@ export function createReportStore( saveFailed: false, initReport: (draft, sheet, index) => { - if (!mayStartSession(index)) return HELD + const may = mayStartSession(index) + if (!may.ok) return may const outcome = reportOps.newReport({ draft, sheet, @@ -303,7 +310,8 @@ export function createReportStore( }, hydrateImport: ({ report, archive }, index) => { - if (!mayStartSession(index)) return HELD + const may = mayStartSession(index) + if (!may.ok) return may set(withArchive({ report, activeObservationIndex: 0 }, archive)) return OK }, diff --git a/apps/app/tests/helpers/core.ts b/apps/app/tests/helpers/core.ts index c649ae2d..9a7c8345 100644 --- a/apps/app/tests/helpers/core.ts +++ b/apps/app/tests/helpers/core.ts @@ -6,6 +6,19 @@ export function testCoreRuntime(): Promise { 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({ diff --git a/apps/app/tests/unit/components.AnatomyCanvas.test.tsx b/apps/app/tests/unit/components.AnatomyCanvas.test.tsx index 16aa1e4c..cd1b5db3 100644 --- a/apps/app/tests/unit/components.AnatomyCanvas.test.tsx +++ b/apps/app/tests/unit/components.AnatomyCanvas.test.tsx @@ -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( 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 () => { diff --git a/apps/app/tests/unit/routes.HomeRoute.import.test.tsx b/apps/app/tests/unit/routes.HomeRoute.import.test.tsx index f129bc31..7c7d3500 100644 --- a/apps/app/tests/unit/routes.HomeRoute.import.test.tsx +++ b/apps/app/tests/unit/routes.HomeRoute.import.test.tsx @@ -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 }) + } + }) +}) diff --git a/apps/app/tests/unit/routes.coreStopped.test.tsx b/apps/app/tests/unit/routes.coreStopped.test.tsx new file mode 100644 index 00000000..5452a7d0 --- /dev/null +++ b/apps/app/tests/unit/routes.coreStopped.test.tsx @@ -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()), + readAttachment: vi.fn(), +})) +vi.mock('@/sheets/useSheet', async (importOriginal) => ({ + ...(await importOriginal()), + loadSheetIndex: vi.fn((await importOriginal()).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({node}) + +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() + expectSavedVariant() + cleanup() + inRouter() + expectSavedVariant() + cleanup() + render( 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() + await expectUnsavedVariant() + cleanup() + blobs.length = 0 + inRouter() + await expectUnsavedVariant() + cleanup() + blobs.length = 0 + render( undefined} />) + await expectUnsavedVariant() + }) + + it('is absent while the engine runs, and appears when it stops', async () => { + setStopped(false) + inRouter() + 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( undefined} />) + expect(screen.getByText(fr['sheet.core_unavailable']!)).toBeInTheDocument() + expect(retryButton()).toBeInTheDocument() + }) +}) + +describe('EditorRoute', () => { + const mountEditor = () => inRouter() + + 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() + 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() + 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']), + ) + }) +}) diff --git a/apps/app/tests/unit/state.heldSession.test.ts b/apps/app/tests/unit/state.heldSession.test.ts index cd8bb8d3..d5f28ac2 100644 --- a/apps/app/tests/unit/state.heldSession.test.ts +++ b/apps/app/tests/unit/state.heldSession.test.ts @@ -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() }) }) diff --git a/docs/development/RUST.md b/docs/development/RUST.md index bab20b58..b7a4fb02 100644 --- a/docs/development/RUST.md +++ b/docs/development/RUST.md @@ -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 made meanwhile answer `core_unavailable`. Sheet handles carry the instance 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 editor and the new-report page show the notice with "Réessayer" (the retry 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` 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 @@ -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`, `internal`: the existing `sheet.core_unavailable` notice with "Réessayer", the retry builds again on a fresh instance), the engine stopped after its - three recoveries (`CoreRuntime.stopped`: the `core.stopped` notice, "reload - the page, your report is kept in this tab", no retry; the editor's action - alerts say the same instead of "try again") or the view itself cannot be + three recoveries (`CoreRuntime.stopped`: no retry anywhere; the canvas shows + the stopped text, and `CoreStoppedNotice` sits in the editor's banner slot + 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`, `no_asset`, `unknown_view`, `invalid_character`, a parse failure: the `canvas.view_unavailable` notice, no retry since nothing would change). The diff --git a/packages/core-wasm/src/runtime.ts b/packages/core-wasm/src/runtime.ts index ba3ad82a..16279175 100644 --- a/packages/core-wasm/src/runtime.ts +++ b/packages/core-wasm/src/runtime.ts @@ -13,6 +13,8 @@ import { * 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 * `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. */ @@ -60,6 +62,7 @@ export class CoreRuntime { private imports = 0 private recoveries = 0 private readonly maxRecoveries: number + private readonly listeners = new Set<() => void>() /** Increments with every instance; sheet handles of an older generation are dropped. */ generation = 0 @@ -82,9 +85,30 @@ export class CoreRuntime { 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. */ ready(): Promise { if (this.state === 'ready') return Promise.resolve(true) + if (this.restartable) return this.retry() if (this.state === 'unavailable') return Promise.resolve(false) this.pending ??= this.load() return this.pending @@ -94,12 +118,18 @@ export class CoreRuntime { retry(): Promise { if (this.state !== 'unavailable') return this.ready() if (this.recoveries >= this.maxRecoveries) return Promise.resolve(false) - this.state = 'idle' - this.compiled = null + this.setState('idle') + // 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 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. */ call(op: string, input: string): CoreOutcome { return this.invoke((glue) => parseOutcome(glue.call(op, input))) @@ -116,7 +146,10 @@ export class CoreRuntime { */ invoke(fn: (glue: GlueModule) => CoreOutcome): CoreOutcome { const glue = this.glue - if (this.state !== 'ready' || !glue) return CORE_UNAVAILABLE + if (this.state !== 'ready' || !glue) { + this.kickRestart() + return CORE_UNAVAILABLE + } try { return fn(glue) } catch (error) { @@ -126,12 +159,12 @@ export class CoreRuntime { } private async load(): Promise { - this.state = 'loading' + this.setState('loading') try { await this.instantiate(await this.source.importGlue(this.nextImport())) return true } catch { - this.state = 'unavailable' + this.setState('unavailable') this.pending = null return false } @@ -142,12 +175,28 @@ export class CoreRuntime { await glue.default({ module_or_path: await this.compiled }) this.glue = glue this.generation += 1 - this.state = 'ready' + this.setState('ready') this.spare = this.source .importGlue(this.nextImport()) .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 { this.imports += 1 return this.imports @@ -156,11 +205,11 @@ export class CoreRuntime { private poison(): void { this.glue = null if (this.recoveries >= this.maxRecoveries) { - this.state = 'unavailable' + this.setState('unavailable') return } this.recoveries += 1 - this.state = 'recovering' + this.setState('recovering') this.pending = this.recover() } @@ -172,7 +221,7 @@ export class CoreRuntime { ) return true } catch { - this.state = 'unavailable' + this.setState('unavailable') return false } finally { 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. */ private current(): CoreOutcome { if (this.handle && this.handleGeneration === this.runtime.generation) { - return this.runtime.status === 'ready' - ? { ok: true, value: this.handle } - : CORE_UNAVAILABLE + if (this.runtime.status === 'ready') return { ok: true, value: this.handle } + this.runtime.kickRestart() + return CORE_UNAVAILABLE } this.handle = null return this.runtime.invoke((glue) => { diff --git a/packages/core-wasm/tests/runtime.test.ts b/packages/core-wasm/tests/runtime.test.ts index 08a2b181..2591aa74 100644 --- a/packages/core-wasm/tests/runtime.test.ts +++ b/packages/core-wasm/tests/runtime.test.ts @@ -47,6 +47,38 @@ function countingSource(offlineAfter = Infinity) { 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 => { + 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). */ function trap(runtime: CoreRuntime) { return runtime.invoke((glue) => { @@ -91,6 +123,7 @@ describe('core runtime', () => { ok: true, value: { ref: { sheetId: 'sheet', versionId: null } }, }) + retainHandle(sheet) trap(runtime) expect(sheet.call('index_data', '')).toMatchObject({ kind: 'core_unavailable', @@ -180,4 +213,100 @@ describe('core runtime', () => { expect(runtime.sheet(BUNDLE).open()).toMatchObject({ ok: false, kind: 'internal' }) 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]) + }) })