Files
faunosteo/.claude/tasks/plans/2026-10-15-core-stopped-audit-fix-1830.md

130 lines
11 KiB
Markdown

# Plan — engine stopped: audit fixes on 0279953 (bugfix, branch feature/rust-r3-anatomy-core)
## Context
Commit 0279953 added `CoreRuntime.stopped` (recovery cap 3 spent), `coreStopped()`, `coreFailureMessage(t)`
(apps/app/src/core/failure.ts), canvas failure `engine_stopped`, key `core.stopped` ("reload the page, your
report is kept in this tab"). Independent audit found:
- A. `core.stopped` ignores `reportStore.saveFailed` (set by the draft mirror when sessionStorage refuses a write,
reportStore.ts:392-396, shown as banner `editor.save_failed` "Exportez le PDF pour les conserver",
EditorRoute.tsx:303). Once stopped, export needs the core (pdf/export.ts:37 `index.ops.snapshot`) → impossible.
Reload restores the last successful write → edits since the refused write lost, unannounced.
- B. Surfaces still offering a retry that cannot work once stopped: CoreUnavailable (EditorRoute.tsx:257,
`sheet.retry` → runtime.retry() returns false at cap), export catch (`editor.export_failed` "Réessayez"),
import (`home.import.error_core_unavailable` "Réessayez l'import"), NewReportRoute.tsx:55
(`sheet.core_unavailable`). Also `releaseUnreadSession` (reportStore.ts:248-262) returns false on a core
failure, so initReport / hydrateImport return HELD and the pages say `session.held_blocked` (wrong cause).
- C. Canvas "Réessayer" (AnatomyCanvas.tsx ~145) only bumps `attempt` (rebuild), never calls
`coreRuntime().retry()`: after a failed recovery below the cap (state unavailable, stopped false) it is a dead end.
- D. Stale comment core/sheetOps.ts:17; test gaps (default cap 3 unpinned, failed recovery below/at cap, no census
of call sites, no stopped+saveFailed test).
Owner choices (AskUserQuestion 2026-10-15):
1. stopped + save failed → variant message `core.stopped_unsaved` + "Télécharger une copie" button writing the
IN-MEMORY report as JSON, no core (rescue copy; not importable today, import reads PDFs only).
FR: « 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. »
EN: "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."
2. `core.stopped` wording: "plusieurs erreurs successives" → "plusieurs erreurs" (EN "several successive errors"
→ "several errors"); rest unchanged.
3. "Recharger la page" button (new key `core.reload`, FR « Recharger la page », EN "Reload the page") on the
stopped notice ONLY when the save is fine; never in the unsaved variant.
## Fix plan (rev 2, after 3 challengers)
1. packages/core-wasm/src/runtime.ts —
a. Self-restart after a failed recovery (closes C everywhere, not only on the canvas): `restartable` =
`state === 'unavailable' && !stopped && generation > 0` (an instance ran before: a failed recovery or a
failed restart; a failed FIRST load stays on useSheet's explicit retry). `ready()` on a restartable runtime
returns `this.retry()` (awaits the restart); every CORE_UNAVAILABLE answer of `invoke()` and of
`SheetSession.current()` on a restartable runtime kicks `void this.retry()` and still answers
CORE_UNAVAILABLE (the next user action works: "Réessayez" becomes true). No counter change: a restart is
not a recovery; the cap still counts traps. A restart keeps `compiled` when `generation > 0` (the module
already ran; only a failed FIRST load clears it), so a restart fetches a glue record, never recompiles.
b. Status listeners: `subscribe(listener): () => void`. Notification is deferred (`queueMicrotask`) after the
transition, never inside the try blocks of load/recover, each listener wrapped in try/catch; a throwing or
re-entrant listener cannot change the state machine.
2. apps/app/src/core/runtime.ts — module-scope `subscribeCore(cb) = coreRuntime().subscribe(cb)` (stable
identity) and `useCoreStopped()` = `useSyncExternalStore(subscribeCore, coreStopped)`. Used on the three core
pages only (Editor, Home, New report); creating the runtime object loads nothing (lazy load stays on ready()).
3. apps/app/src/state/reportStore.ts —
a. exported selector `isUnsaved(s) = s.saveFailed && s.report !== null` (one rule, used by the notice and the
alerts).
b. `releaseUnreadSession` / `mayStartSession` return `ActionResult`: set-aside failure → HELD; core cannot read
the unread draft (any kind outside UNREADABLE_DRAFT_KINDS) → FAILED (never HELD); initReport / hydrateImport:
`const may = mayStartSession(index); if (!may.ok) return may`. Nothing written in either case (unchanged).
4. apps/app/src/core/failure.ts — `stoppedMessageKey()` = `isUnsaved(useReportStore.getState()) ?
'core.stopped_unsaved' : 'core.stopped'`; `coreFailureMessage(t, fallbackKey = 'core.action_failed')`:
stopped → `t(stoppedMessageKey())`, else `t(fallbackKey)`.
5. apps/app/src/lib/download.ts (new) — `downloadJson(raw, stem)`: body of HeldSessionPanel's `downloadCopy`
(Blob application/json, anchor attached while clicked, URL revoked after 30 s, `<stem>-<todayIso()>.json`).
HeldSessionPanel calls it (behaviour unchanged).
6. apps/app/src/components/report/CoreStoppedNotice.tsx (new) — the one host of the stopped buttons. Reads
`useReportStore(isUnsaved)` and `report`. unsaved → Notice error `core.stopped_unsaved` + Button
`session.held.download` (reused key) → `downloadJson(JSON.stringify(report), 'faunosteo-brouillon')`;
otherwise Notice error `core.stopped` + Button `core.reload` → `window.location.reload()`. Never a retry.
`CoreStoppedBanner` (same file or inline) = `useCoreStopped() ? <CoreStoppedNotice/> : null`.
7. Placement (persistent, whenever stopped, so alerts never name a button that is not on the page):
- EditorRoute banner slot: stopped → `<CoreStoppedNotice/>` (same margins as the save banner) INSTEAD of
`editor.save_failed`; not stopped + saveFailed → `editor.save_failed` text + the same core-free
"Télécharger une copie" button [rev 3, owner gate Q1]: the rescue exists in every engine state (a restart that
keeps failing offline never reaches `stopped`).
- [rev 3, owner gate Q2] `beforeunload` guard while `isUnsaved` (native browser confirm), registered in
EditorRoute; removed when the save recovers.
- HomeRoute and NewReportRoute: `<CoreStoppedBanner/>` at the top of the page content (below the header), so the
unsaved variant's download is on every page that can show its text.
- CoreUnavailable: `useCoreStopped()` → `<main><CoreStoppedNotice/></main>` instead of notice + retry.
8. apps/app/src/components/canvas/AnatomyCanvas.tsx — the engine variant is derived at render: a build failure
`engine` with `useCoreStopped()` true (or a build `engine_stopped`) → Notice with the stopped text chosen from
`useReportStore(isUnsaved)` (reactive), no button (the page banner holds the buttons; DetailModal never opens once stopped: a zone click is a core call).
"Réessayer" (engine only): `void coreRuntime().retry().finally(() => setAttempt(n => n + 1))`.
9. Alerts / error lines: EditorRoute export catch → `coreFailureMessage(t, 'editor.export_failed')`;
NewReportRoute:55 → `coreFailureMessage(t, 'sheet.core_unavailable')`; HomeRoute `importErrorMessage`
core_unavailable → `coreFailureMessage(t, 'home.import.error_core_unavailable')`; HomeRoute hydrateImport
`!ok`: `reason === 'held'` → held alert + navigate (unchanged), else throw `ImportError('core_unavailable')`.
10. apps/app/src/core/sheetOps.ts:17 comment → "shows `coreFailureMessage`".
11. i18n fr.ts / en.ts — `core.stopped` reworded (choice 2); new `core.stopped_unsaved`, `core.reload`.
12. ESLint (apps/app/eslint.config.js): `no-restricted-syntax` on `t('core.action_failed')`,
`t('editor.export_failed')`, `t('home.import.error_core_unavailable')`, `t('sheet.core_unavailable')` call
literals in src, except src/core/failure.ts, and for `sheet.core_unavailable` also CoreUnavailable.tsx and
AnatomyCanvas.tsx (the census, codebase idiom; dictionaries are not call sites).
13. docs/development/RUST.md §9.4 (+ §8 runtime note if it describes recovery) and the CHANGELOG R3 owner-decisions
line: restart on next action after a failed recovery; stopped notice on the core pages (reload, or unsaved
variant with copy); export / import / new report say the stopped message.
## Tests
- core-wasm runtime.test.ts: default cap = 3 (three recoveries succeed, fourth trap → stopped, retry false);
failed recovery below the cap → stopped false, then the next call kicks a restart and the call after it
succeeds; `ready()` after a failed recovery restarts and resolves true; third recovery fails → stopped true, no
restart kicked; a failed first load is NOT restarted by a call (only retry()); subscribe notified (after a
microtask) on the transition to stopped, a throwing listener does not change the state, unsubscribe stops it.
- AnatomyCanvas: engine retry calls `coreRuntime().retry()` (spy) then rebuilds; engine_stopped shows the stopped
text (unsaved variant when isUnsaved) and no button.
- CoreStoppedNotice: save fine → `core.stopped` + reload button, no retry; isUnsaved → `core.stopped_unsaved` +
download whose Blob content equals JSON.stringify(report).
- EditorRoute: stopped → banner notice replaces `editor.save_failed`; not stopped + saveFailed → save banner
with the copy button; beforeunload registered only while isUnsaved; export failure while stopped → stopped alert.
- runtime: a restart after a failed recovery reuses `compiled` (compile called once).
- HomeRoute / NewReportRoute: stopped → banner present; stopped + unsaved → download button on the page.
- state.heldSession.test.ts:268-280 inverted: core cannot read the draft → `{ ok: false }` without
`reason: 'held'`, draft untouched; same for hydrateImport.
- ESLint rule proven: lint fails on a sample `t('core.action_failed')` outside failure.ts (rule test via
`pnpm lint` on the tree + one RuleTester-free check: the tree lints clean).
- `pnpm typecheck && pnpm test:run && pnpm lint` green; core-wasm vitest green (TS-only runtime change, no wasm
rebuild; stamp unaffected).
## Known residuals (recorded, not fixed here)
- `saveFailed` also covers a refused archive write (BDR-052 banner semantics, pre-existing): the unsaved variant
over-warns then; the copy holds the report, the archive is the imported PDF still on disk.
- Kinds such as `rebase_failed` (sheet defect) answer FAILED → "Réessayez" (generic; near-unreachable).
- Home while not stopped but the engine cannot restart (offline) and saveFailed: no banner there; the editor
banner holds the copy.
- New report banner "Recharger la page" discards a typed form (shown from page entry, so usually before typing).
- New report / import while an open report has saveFailed replace it (pre-existing; deliberate user action).
- A draft that traps the core on every load → reload loop (pre-existing).
## Out of scope
R4, merge, the frozen PDF engine, Rust crates, goldens; making the JSON copy importable.