From 9bd9acaf58f9bc393ba40fcc8d63b8ac15bb6bf0 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 17 Oct 2026 12:58:57 +0200 Subject: [PATCH] fix(app): rescue copy importable, trapping draft held, replace confirmed The JSON rescue copy could not be restored in the app, a draft that traps the engine left the tab on a reload screen and spent a recovery on every read, and an unsaved or in-progress report could be lost by a reload outside the editor or by New report / Import without warning. Home import reads the copy (content-sniffed, 16 MiB cap, strict UTF-8) through the core's draft.restore before any session change; a trapping (draft, archive) pair is held in the resolution panel and only re-read on Retry; ReplaceSessionDialog guards New report and Import; the beforeunload guard is app-wide while unsaved. Supersedes BDR-055's "never held" for `internal` only. --- CHANGELOG.md | 3 +- CLAUDE.md | 3 +- apps/app/src/app/App.tsx | 3 + apps/app/src/app/routes/EditorRoute.tsx | 19 +- apps/app/src/app/routes/HomeRoute.tsx | 107 +++++++++- apps/app/src/app/routes/NewReportRoute.tsx | 25 ++- apps/app/src/app/useUnsavedGuard.ts | 19 ++ .../components/report/HeldSessionPanel.tsx | 8 +- .../report/ReplaceSessionDialog.tsx | 54 +++++ apps/app/src/i18n/en.ts | 21 +- apps/app/src/i18n/fr.ts | 21 +- apps/app/src/pdf/import.ts | 21 +- apps/app/src/state/reportStore.ts | 79 ++++++- apps/app/tests/helpers/core.ts | 40 +++- .../tests/unit/app.useUnsavedGuard.test.tsx | 69 +++++++ .../unit/routes.HomeRoute.rescueCopy.test.tsx | 150 ++++++++++++++ .../tests/unit/routes.coreStopped.test.tsx | 22 +- .../tests/unit/routes.heldSession.test.tsx | 4 + .../tests/unit/routes.replaceSession.test.tsx | 194 ++++++++++++++++++ .../tests/unit/routes.trappingDraft.test.tsx | 181 ++++++++++++++++ apps/app/tests/unit/state.quarantine.test.ts | 88 +++++++- docs/development/RUST.md | 27 ++- 22 files changed, 1090 insertions(+), 68 deletions(-) create mode 100644 apps/app/src/app/useUnsavedGuard.ts create mode 100644 apps/app/src/components/report/ReplaceSessionDialog.tsx create mode 100644 apps/app/tests/unit/app.useUnsavedGuard.test.tsx create mode 100644 apps/app/tests/unit/routes.HomeRoute.rescueCopy.test.tsx create mode 100644 apps/app/tests/unit/routes.replaceSession.test.tsx create mode 100644 apps/app/tests/unit/routes.trappingDraft.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ca474f7..e7a7bbd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ 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, 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. +- 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 (except a trap of the engine on the draft, `internal`, held as an engine failure since the final checks below). +- R3 final checks (owner decisions 2026-10-17): **the rescue copy can be restored**: the Home picker now accepts the JSON downloaded by "Télécharger une copie" next to the PDF (routed by content, strict UTF-8, size cap, read by the core's draft restore; a refused file changes nothing). **A draft that traps the engine** (out of memory) no longer loops on the reload screen: the editor shows the resolution panel with the draft kept as is, New report and Import say so and open it, the trapping draft is read once, and only "Réessayer" reads it again. **New report and the file pick ask before replacing a bilan in progress** (cancel, open it, replace), and the "unsaved changes" browser prompt now guards every page, not only the editor. Documented in `docs/development/RUST.md` §8.3, §8.7 item 3 and §9.4 item 9. ### Security (maintenance after R2, 2026-10-14) diff --git a/CLAUDE.md b/CLAUDE.md index 1ac6949d..dee3db76 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -196,6 +196,7 @@ faunosteo/ │ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched │ ├─ app/ │ │ ├─ App.tsx ← root router +│ │ ├─ useUnsavedGuard.ts ← beforeunload while the report is unsaved, called once in App │ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx │ │ ├─ routes/auth/{Login,Signup,ForgotPassword,ResetPassword,AuthCallback}Route.tsx │ │ ├─ routes/app/{Dashboard,Account}Route.tsx ← behind RequireAuth, inside AppLayout @@ -227,7 +228,7 @@ faunosteo/ │ │ │ VertebraPicker,SeveritySelector,LateralityPicker, │ │ │ FreeTextFindingInput}.tsx │ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog, -│ │ │ ConclusionPanel,NextAppointmentPicker,CoreUnavailable,HeldSessionPanel}.tsx +│ │ │ ConclusionPanel,NextAppointmentPicker,CoreUnavailable,HeldSessionPanel,ReplaceSessionDialog}.tsx │ │ ├─ brand/{Brand,AppHeader,Footer,LanguageSwitcher,HomeSpaceLink}.tsx │ │ ├─ auth/{AuthLayout,OAuthButtons,PasswordField,UnavailableNotice,AuthLink}.tsx │ │ ├─ shell/{AppLayout,SidebarNav,MobileDrawer,UserBadge,SignOutButton}.tsx diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index ca232e07..4ceb897b 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -16,6 +16,7 @@ import ResetPasswordRoute from './routes/auth/ResetPasswordRoute' import AuthCallbackRoute from './routes/auth/AuthCallbackRoute' import DashboardRoute from './routes/app/DashboardRoute' import AccountRoute from './routes/app/AccountRoute' +import { useUnsavedGuard } from './useUnsavedGuard' /** The local tool: unchanged routes, no account needed, shared footer. */ function LocalToolShell() { @@ -58,6 +59,8 @@ export function AppRoutes() { } export default function App() { + // The store is not a context: one call above the route tree guards every page. + useUnsavedGuard() return ( diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index 8c748874..62dd0dc0 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -20,7 +20,6 @@ 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, @@ -76,7 +75,6 @@ export default function EditorRoute() { // 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( @@ -137,17 +135,6 @@ 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(() => { @@ -288,7 +275,11 @@ export default function EditorRoute() { restoreOptions.current = { replaceOriginal: true } retryRestore() }} - onRetry={retryRestore} + onRetry={() => { + // The one explicit way to read a draft the engine trapped on again. + restoreOptions.current = { retryTrapped: true } + retryRestore() + }} /> ) } diff --git a/apps/app/src/app/routes/HomeRoute.tsx b/apps/app/src/app/routes/HomeRoute.tsx index 04bb0787..3b00a235 100644 --- a/apps/app/src/app/routes/HomeRoute.tsx +++ b/apps/app/src/app/routes/HomeRoute.tsx @@ -7,15 +7,23 @@ import type { import AppHeader from '@/components/brand/AppHeader' import HomeSpaceLink from '@/components/brand/HomeSpaceLink' import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice' +import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog' import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' import { importAttachment, ImportError, + MAX_ATTACHMENT_BYTES, MAX_PDF_BYTES, readAttachment, + readRescueCopy, } from '@/pdf/import' -import { useReportStore } from '@/state/reportStore' +import { + isSessionInProgress, + useReportStore, + type ImportedSession, +} from '@/state/reportStore' +import type { SheetIndex } from '@/services/sheetIndex' import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet' import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { useT } from '@/i18n/useT' @@ -107,11 +115,50 @@ function importErrorMessage(err: unknown, t: Translate): string { return t('home.import.error_no_attachment') case 'lone_surrogate': return t('home.import.error_lone_surrogate') + case 'invalid_copy': + return t('home.import.error_invalid_copy') case 'core_unavailable': return coreFailureMessage(t, 'home.import.error_core_unavailable') } } +/** What a picked file read into: the session to open and the alert lines to show after. */ +interface ImportRead { + session: ImportedSession + index: SheetIndex + lines: string[] +} + +const SNIFF_BYTES = 1024 +const PDF_MAGIC = '%PDF-' + +/** First non-blank byte of the head, after an optional UTF-8 byte order mark. */ +function firstContentByte(head: Uint8Array): number | undefined { + const start = head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0 + return head.slice(start).find((b) => ![0x20, 0x09, 0x0a, 0x0d].includes(b)) +} + +/** + * Routes by content, from the first KiB only: a PDF starts with its magic, a rescue copy + * is JSON (an object) or is named as such; anything else goes the PDF path and its error. + */ +function isRescueCopy(file: File, head: Uint8Array): boolean { + const start = new TextDecoder('latin1').decode(head.slice(0, PDF_MAGIC.length)) + if (start === PDF_MAGIC) return false + if (firstContentByte(head) === 0x7b) return true + return file.name.toLowerCase().endsWith('.json') || file.type === 'application/json' +} + +/** The copy's text, refused (never altered) when it is over the cap or not valid UTF-8. */ +async function readCopyText(file: File): Promise { + if (file.size > MAX_ATTACHMENT_BYTES) throw new ImportError('invalid_copy') + try { + return new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer()) + } catch { + throw new ImportError('invalid_copy') + } +} + export default function HomeRoute() { const navigate = useNavigate() const fileRef = useRef(null) @@ -120,10 +167,11 @@ export default function HomeRoute() { const sheet = useSheetAvailability(DEFAULT_SPECIES_ID) const [error, setError] = useState(null) const [busy, setBusy] = useState(false) + const [confirmingReplace, setConfirmingReplace] = useState(false) const t = useT() - /** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */ - async function importFile(file: File) { + /** A Faunosteo PDF: its attachment, read and rebased by the core on the loaded sheet. */ + async function readPdf(file: File): Promise { // The engine refuses the same size; checking first keeps a huge file out of memory. if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf') const bytes = new Uint8Array(await file.arrayBuffer()) @@ -131,20 +179,43 @@ export default function HomeRoute() { const index = await loadSheetIndex(DEFAULT_SPECIES_ID) if (!index) throw new ImportError('core_unavailable') const { read: outcome, rebase } = importAttachment(attachment, index) - const opened = hydrateImport( - { report: rebase.report, archive: outcome.archive }, + return { + session: { report: rebase.report, archive: outcome.archive }, index, - ) + lines: importMessages(outcome, rebase, t), + } + } + + /** A rescue copy: read before any session change, so a refusal leaves the tab untouched. */ + async function readCopy(file: File): Promise { + const text = await readCopyText(file) + const index = await loadSheetIndex(DEFAULT_SPECIES_ID) + if (!index) throw new ImportError('core_unavailable') + const rebase = readRescueCopy(text, index) + const count = String(rebase.unresolvedZones + rebase.unresolvedFindings) + return { + session: { report: rebase.report, archive: null }, + index, + lines: rebase.rebased ? [t('editor.draft_rebased').replace('{count}', count)] : [], + } + } + + /** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */ + async function importFile(file: File) { + const head = new Uint8Array(await file.slice(0, SNIFF_BYTES).arrayBuffer()) + const read = isRescueCopy(file, head) ? await readCopy(file) : await readPdf(file) + const opened = hydrateImport(read.session, read.index) // 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')) + window.alert( + t(opened.engine ? 'session.held_blocked_engine' : 'session.held_blocked'), + ) navigate('/editor') return } - const lines = importMessages(outcome, rebase, t) - if (lines.length > 0) window.alert(lines.join('\n\n')) + if (read.lines.length > 0) window.alert(read.lines.join('\n\n')) navigate('/editor') } @@ -208,14 +279,18 @@ export default function HomeRoute() { + setConfirmingReplace(false)} + onOpen={() => navigate('/editor')} + onConfirm={() => { + setConfirmingReplace(false) + void createReport() + }} + /> ) } diff --git a/apps/app/src/app/useUnsavedGuard.ts b/apps/app/src/app/useUnsavedGuard.ts new file mode 100644 index 00000000..3a11dd9e --- /dev/null +++ b/apps/app/src/app/useUnsavedGuard.ts @@ -0,0 +1,19 @@ +import { useEffect } from 'react' +import { isUnsaved, useReportStore } from '@/state/reportStore' + +/** + * The report lives only in this tab's memory while the tab's storage refuses its writes: + * on any page, the browser asks before a reload, a close or a full-page redirect. + */ +export function useUnsavedGuard(): void { + const unsaved = useReportStore(isUnsaved) + useEffect(() => { + if (!unsaved) return + const guard = (event: BeforeUnloadEvent) => { + event.preventDefault() + event.returnValue = '' + } + window.addEventListener('beforeunload', guard) + return () => window.removeEventListener('beforeunload', guard) + }, [unsaved]) +} diff --git a/apps/app/src/components/report/HeldSessionPanel.tsx b/apps/app/src/components/report/HeldSessionPanel.tsx index dddce818..226fceb9 100644 --- a/apps/app/src/components/report/HeldSessionPanel.tsx +++ b/apps/app/src/components/report/HeldSessionPanel.tsx @@ -56,7 +56,13 @@ export default function HeldSessionPanel({ return (
- {t('session.held.notice')} + + {t( + held.some((item) => item.reason === 'engine_failure') + ? 'session.held.notice_engine' + : 'session.held.notice', + )} +
    {held.map((item) => (
  • void + /** Leaves for the editor, where the bilan in progress is. */ + onOpen: () => void + onConfirm: () => void +} + +/** + * Asked before a new report or an import replaces the bilan in progress in this tab, + * saved or not: the practitioner cancels, goes back to it, or replaces it knowingly. + * An unsaved report (tab storage full) comes with its rescue copy. + */ +export default function ReplaceSessionDialog({ + open, + onCancel, + onOpen, + onConfirm, +}: ReplaceSessionDialogProps) { + const t = useT() + const report = useReportStore((s) => s.report) + const unsaved = useReportStore(isUnsaved) + const body = report + ? t('session.replace.body').replace(/\{animal\}/, () => report.animal.name) + : t('session.replace.body_unloaded') + return ( + +

    {body}

    + {unsaved && ( +
    +

    {t('session.replace.unsaved')}

    + +
    + )} +
    + + + +
    +
    + ) +} diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index ae4d7683..8846d23c 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -19,15 +19,17 @@ export const en: Dict = { 'home.new_report.description': 'Start a new osteopathic report for an animal.', 'home.new_report.cta': 'Start', - 'home.import.title': 'Import a PDF', + 'home.import.title': 'Import a PDF or a rescue copy', 'home.import.description': 'Reopen a previous report generated by this app to follow up.', - 'home.import.cta': 'Choose a PDF', + 'home.import.cta': 'Choose a file', 'home.import.loading': 'Reading…', 'home.import.error_core_unavailable': 'The reading engine could not be loaded. Try the import again.', 'home.import.error_generic': 'Failed to read the PDF.', 'home.import.error_invalid_pdf': 'This file is not a readable PDF.', + 'home.import.error_invalid_copy': + 'This file is not a Faunosteo rescue copy this version can read. Import refused; the file was not changed.', 'home.import.error_no_attachment': 'This PDF was not generated by Faunosteo (no data detected).', 'home.import.error_incompatible_version': @@ -122,6 +124,21 @@ export const en: Dict = { "Open", 'session.held_blocked': "A draft in this tab must be recovered or deleted first: it could not be set aside and would be overwritten. The editor will open to resolve it.", + 'session.held.notice_engine': + "Faunosteo's computation engine cannot open a draft of this tab. It is kept as is; nothing was deleted. Download a copy, try again, or delete it to start a new report.", + 'session.held.draft_engine_failure': + "Draft the computation engine cannot open ({size})", + 'session.held_blocked_engine': + "A draft of this tab makes the computation engine fail: recover or delete it first. The editor will open to resolve it.", + 'session.replace.title': 'Replace the report in progress?', + 'session.replace.body': + "The report of {animal} will be replaced in this tab. Export it as a PDF to keep it.", + 'session.replace.body_unloaded': + "The report in progress in this tab will be replaced. Open it and export it as a PDF to keep it.", + 'session.replace.unsaved': + "Its latest changes are not saved in this tab.", + 'session.replace.open': 'Open the report in progress', + 'session.replace.confirm': 'Replace', 'editor.edit_infos': 'Edit info', 'editor.edit_dialog_title': 'Edit information', 'editor.disclaimer_title': 'Legal scope of animal osteopathy', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 966843d6..319712a9 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -21,15 +21,17 @@ export const fr: Dict = { 'home.new_report.description': "Démarrer un nouveau bilan d'ostéopathie sur un animal.", 'home.new_report.cta': 'Commencer', - 'home.import.title': 'Importer un PDF', + 'home.import.title': 'Importer un PDF ou une copie de secours', 'home.import.description': 'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.', - 'home.import.cta': 'Choisir un PDF', + 'home.import.cta': 'Choisir un fichier', 'home.import.loading': 'Lecture…', 'home.import.error_core_unavailable': "Le moteur de lecture n'a pas pu être chargé. Réessayez l'import.", 'home.import.error_generic': 'Erreur de lecture du PDF.', 'home.import.error_invalid_pdf': "Ce fichier n'est pas un PDF lisible.", + 'home.import.error_invalid_copy': + "Ce fichier n'est pas une copie de secours Faunosteo lisible par cette version. Import refusé ; le fichier n'a pas été modifié.", 'home.import.error_no_attachment': "Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).", 'home.import.error_incompatible_version': @@ -128,6 +130,21 @@ export const fr: Dict = { "Ouvrir", 'session.held_blocked': "Un brouillon de cet onglet doit d'abord être récupéré ou supprimé : il n'a pas pu être mis de côté et serait écrasé. L'éditeur va s'ouvrir pour le résoudre.", + 'session.held.notice_engine': + "Le moteur de calcul n'arrive pas à ouvrir un brouillon de cet onglet. Il est conservé tel quel ; rien n'a été supprimé. Téléchargez-en une copie, réessayez, ou supprimez-le pour commencer un nouveau bilan.", + 'session.held.draft_engine_failure': + "Brouillon que le moteur de calcul n'arrive pas à ouvrir ({size})", + 'session.held_blocked_engine': + "Un brouillon de cet onglet fait échouer le moteur de calcul : il doit d'abord être récupéré ou supprimé. L'éditeur va s'ouvrir pour le résoudre.", + 'session.replace.title': 'Remplacer le bilan en cours ?', + 'session.replace.body': + "Le bilan de {animal} sera remplacé dans cet onglet. Exportez-le en PDF pour le garder.", + 'session.replace.body_unloaded': + "Le bilan en cours dans cet onglet sera remplacé. Ouvrez-le et exportez-le en PDF pour le garder.", + 'session.replace.unsaved': + "Ses dernières modifications ne sont pas enregistrées dans l'onglet.", + 'session.replace.open': 'Ouvrir le bilan en cours', + 'session.replace.confirm': 'Remplacer', 'editor.edit_infos': 'Modifier les infos', 'editor.edit_dialog_title': 'Modifier les informations', 'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale", diff --git a/apps/app/src/pdf/import.ts b/apps/app/src/pdf/import.ts index f97d281a..100c0ea6 100644 --- a/apps/app/src/pdf/import.ts +++ b/apps/app/src/pdf/import.ts @@ -1,21 +1,24 @@ -import type { ArchiveImport } from '@faunosteo/core-wasm/types' +import type { ArchiveImport, RebaseOutcome } from '@faunosteo/core-wasm/types' import { ArchiveReadError, readAttachedDocument, type ArchiveReadErrorKind, } from '@faunosteo/pdf' import type { SheetIndex } from '@/services/sheetIndex' +import { UNREADABLE_DRAFT_KINDS } from '@/state/reportStore' -export { MAX_PDF_BYTES } from '@faunosteo/pdf' +export { MAX_ATTACHMENT_BYTES, MAX_PDF_BYTES } from '@faunosteo/pdf' /** * `lone_surrogate`: the attachment escapes a lone UTF-16 surrogate, which the * core cannot read without altering it (L1): refused, the file untouched. + * `invalid_copy`: a file offered as a rescue copy that this build cannot read. */ export type ImportErrorKind = | ArchiveReadErrorKind | 'core_unavailable' | 'lone_surrogate' + | 'invalid_copy' /** * Localization-agnostic import error. Carries a kind discriminant + an @@ -84,3 +87,17 @@ export async function importReportFromPdf( ): Promise { return importAttachment(await readAttachment(pdfBytes), index) } + +/** + * A rescue copy (`JSON.stringify(report)`, the byte format of the tab's draft) + * read by the core's draft restore, no archive beside it. Content the core + * refuses is `invalid_copy`; any other failure is the engine's or the sheet's. + */ +export function readRescueCopy(text: string, index: SheetIndex): RebaseOutcome { + const outcome = index.ops.restoreDraft(text, null) + if (outcome.ok) return outcome.value.rebase + if (UNREADABLE_DRAFT_KINDS.has(outcome.kind)) { + throw new ImportError('invalid_copy') + } + throw new ImportError('core_unavailable') +} diff --git a/apps/app/src/state/reportStore.ts b/apps/app/src/state/reportStore.ts index c198b4fb..09dffb2c 100644 --- a/apps/app/src/state/reportStore.ts +++ b/apps/app/src/state/reportStore.ts @@ -20,6 +20,7 @@ import { ARCHIVE_KEY, quarantine, quarantineSession, + readSessionText, removeSessionText, sessionStorageArchivePersistence, sessionStoragePersistence, @@ -57,17 +58,20 @@ export interface ActionResult { ok: boolean /** Refused because a session text is held (it could not be set aside and would be lost). */ reason?: 'held' + /** With `held`: the engine itself fails on the tab's draft (a trap), not a storage problem. */ + engine?: boolean } /** * A session text kept in place because its safety copy failed (storage full, or the * quarantine slot already holds an earlier text): `unreadable` by this build, the * archive `companion` of an unreadable draft, or a draft whose `pre_rebase` original - * could not be kept before the rebase replaces it. + * could not be kept before the rebase replaces it, or a draft the engine trapped on + * (`engine_failure`, kept as is). */ export interface HeldText { text: SessionText - reason: 'unreadable' | 'companion' | 'pre_rebase' + reason: 'unreadable' | 'companion' | 'pre_rebase' | 'engine_failure' /** UTF-8 size of the stored text, for the resolution panel. */ bytes: number } @@ -75,6 +79,8 @@ export interface HeldText { export interface RestoreOptions { /** The practitioner confirmed that the rebased draft may replace its original. */ replaceOriginal?: boolean + /** The practitioner asked to read a draft the engine trapped on again. */ + retryTrapped?: boolean } /** What a draft restore did; `null` from the action when there was nothing to restore. */ @@ -116,6 +122,8 @@ export interface ReportStore { ) => RestoreResult | null /** Removes a held session text, on the practitioner's confirmed request; no-op once a report is open. */ discardSessionText: (text: SessionText) => void + /** Forgets the draft the engine trapped on (test seam; every discard does it too). */ + clearTrapped: () => void addObservation: () => ActionResult removeObservation: (index: number) => ActionResult moveObservationUp: (index: number) => ActionResult @@ -140,6 +148,7 @@ type Getter = () => ReportStore const OK: ActionResult = { ok: true } const FAILED: ActionResult = { ok: false } const HELD: ActionResult = { ok: false, reason: 'held' } +const HELD_ENGINE: ActionResult = { ok: false, reason: 'held', engine: true } /** The tab's storage refused the last write: the in-memory report is the only copy. */ export const isUnsaved = (s: Pick): boolean => @@ -172,7 +181,7 @@ function applyCore( * (`lone_surrogate`: reading it would alter a string, L1). Any other failure is the core's * or the sheet's and leaves the draft in place. */ -const UNREADABLE_DRAFT_KINDS: ReadonlySet = new Set([ +export const UNREADABLE_DRAFT_KINDS: ReadonlySet = new Set([ 'invalid', 'unsupported_version', 'lone_surrogate', @@ -186,6 +195,37 @@ function held(text: SessionText, reason: HeldText['reason'], raw: string): HeldT return { text, reason, bytes: utf8Bytes(raw) } } +/** + * The (draft, archive) pair a `draft.restore` call trapped on. The same pair is never read + * again until the practitioner retries: each read of it would spend an engine recovery. + */ +interface TrapMemory { + matches: (draft: string, archiveText: string | null) => boolean + remember: (draft: string, archiveText: string | null) => void + clear: () => void +} + +function createTrapMemory(): TrapMemory { + let trapped: { draft: string; archive: string | null } | null = null + return { + matches: (draft, archiveText) => + trapped !== null && trapped.draft === draft && trapped.archive === archiveText, + remember: (draft, archiveText) => { + trapped = { draft, archive: archiveText } + }, + clear: () => { + trapped = null + }, + } +} + +/** The held rows of a trapped draft: the draft, and its archive when one is beside it. */ +function engineFailureRows(draft: string, archiveText: string | null): HeldText[] { + const rows = [held('draft', 'engine_failure', draft)] + if (archiveText !== null) rows.push(held('archive', 'companion', archiveText)) + return rows +} + type Restored = { result: RestoreResult; patch?: Patch } | null /** An archive with no draft beside it can never be restored: set it aside, or hold it. */ @@ -212,12 +252,21 @@ function restore( persistence: ReportPersistence, archives: ArchivePersistence, options: RestoreOptions, + trap: TrapMemory, ): Restored { const draft = persistence.loadText() const archiveText = archives.loadText() if (draft === null) return restoreOrphanArchive(archiveText) + if (options.retryTrapped) trap.clear() + if (trap.matches(draft, archiveText)) { + return { result: { kind: 'held', held: engineFailureRows(draft, archiveText) } } + } const outcome = index.ops.restoreDraft(draft, archiveText) if (!outcome.ok) { + if (outcome.kind === 'internal') { + trap.remember(draft, archiveText) + return { result: { kind: 'held', held: engineFailureRows(draft, archiveText) } } + } // Only an unreadable draft is set aside; a core or sheet failure leaves it in place. if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) { return { result: { kind: 'core_unavailable' } } @@ -247,19 +296,26 @@ 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. 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). + * before. HELD when something could not be set aside, or when the engine traps on the draft + * (`engine`: kept as is); 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, + trap: TrapMemory, ): ActionResult { const draft = persistence.loadText() const archiveText = archives.loadText() if (draft === null) return restoreOrphanArchive(archiveText) === null ? OK : HELD + if (trap.matches(draft, archiveText)) return HELD_ENGINE const outcome = index.ops.restoreDraft(draft, archiveText) if (!outcome.ok) { + if (outcome.kind === 'internal') { + trap.remember(draft, archiveText) + return HELD_ENGINE + } if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return FAILED return quarantineSession(draft, archiveText) ? OK : HELD } @@ -271,6 +327,7 @@ export function createReportStore( persistence: ReportPersistence, archives: ArchivePersistence, ) { + const trap = createTrapMemory() /** The archive mirror is explicit: these actions are the session's edges. */ // The archive of this session could not be written: the tab's copy lacks it (banner). let archiveRefused = false @@ -286,7 +343,7 @@ export function createReportStore( const mayStartSession = (index: SheetIndex): ActionResult => store.getState().report !== null ? OK - : releaseUnreadSession(index, persistence, archives) + : releaseUnreadSession(index, persistence, archives, trap) const store = create((set, get) => ({ report: null, @@ -318,7 +375,7 @@ export function createReportStore( restoreDraft: (index, options = {}) => { if (get().report) return null - const restored = restore(index, persistence, archives, options) + const restored = restore(index, persistence, archives, options, trap) if (!restored) return null if (restored.patch) set(restored.patch) return restored.result @@ -326,9 +383,12 @@ export function createReportStore( discardSessionText: (text) => { if (get().report) return + trap.clear() removeSessionText(text) }, + clearTrapped: () => trap.clear(), + addObservation: () => applyCore( set, @@ -409,3 +469,8 @@ export const useReportStore = createReportStore( sessionStoragePersistence, sessionStorageArchivePersistence, ) + +/** A bilan is in progress in this tab: in memory, or as a draft this page never opened. */ +export function isSessionInProgress(): boolean { + return useReportStore.getState().report !== null || readSessionText('draft') !== null +} diff --git a/apps/app/tests/helpers/core.ts b/apps/app/tests/helpers/core.ts index 9a7c8345..691c245c 100644 --- a/apps/app/tests/helpers/core.ts +++ b/apps/app/tests/helpers/core.ts @@ -1,5 +1,5 @@ -import { CoreRuntime } from '@faunosteo/core-wasm' -import { nodeCoreRuntime } from '@faunosteo/core-wasm/node' +import { CoreRuntime, type CoreSource } from '@faunosteo/core-wasm' +import { nodeCoreRuntime, nodeCoreSource } from '@faunosteo/core-wasm/node' /** A loaded runtime on the shipped build (the package's Node source). */ export function testCoreRuntime(): Promise { @@ -26,3 +26,39 @@ export function unavailableCoreRuntime(): CoreRuntime { importGlue: () => Promise.reject(new TypeError('blocked')), }) } + +/** + * A real runtime on the shipped module whose `SheetHandle.call` throws a + * `WebAssembly.RuntimeError` (as an out-of-memory trap does) for `draft.restore` + * calls whose input contains `marker`; `traps.count` counts them. The runtime + * poisons and recovers exactly as in production (three recoveries). + */ +export async function trappingCoreRuntime(marker: string) { + const source = nodeCoreSource('pkg') + const traps = { count: 0 } + const wrapped: CoreSource = { + compile: () => source.compile(), + importGlue: async (instance) => { + const glue = await source.importGlue(instance) + const Real = glue.SheetHandle + class Trapping extends Real { + call(op: string, input: string): string { + if (op === 'draft.restore' && input.includes(marker)) { + traps.count += 1 + throw new WebAssembly.RuntimeError('unreachable') + } + return super.call(op, input) + } + } + return { + default: glue.default, + core_version: glue.core_version, + call: glue.call, + SheetHandle: Trapping, + } + }, + } + const runtime = new CoreRuntime(wrapped) + if (!(await runtime.ready())) throw new Error('trapping runtime failed to load') + return { runtime, traps } +} diff --git a/apps/app/tests/unit/app.useUnsavedGuard.test.tsx b/apps/app/tests/unit/app.useUnsavedGuard.test.tsx new file mode 100644 index 00000000..474e83ca --- /dev/null +++ b/apps/app/tests/unit/app.useUnsavedGuard.test.tsx @@ -0,0 +1,69 @@ +/** + * The beforeunload guard is app-wide (R3 final checks): prevented exactly while the report + * is unsaved, on any page; App mounts it, the editor no longer registers its own. + */ +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react' +import App from '@/app/App' +import { useUnsavedGuard } from '@/app/useUnsavedGuard' +import { useReportStore } from '@/state/reportStore' +import type { SheetIndex } from '@/services/sheetIndex' +import { loadTestSheet, minimalReport } from '../helpers/sheet' + +let sheet: SheetIndex + +beforeAll(async () => { + sheet = await loadTestSheet() +}) +beforeEach(() => { + sessionStorage.clear() + useReportStore.setState({ report: null, archive: null, saveFailed: false }) + useReportStore.getState().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet) +}) +afterEach(() => { + cleanup() + vi.restoreAllMocks() + useReportStore.setState({ report: null, saveFailed: false }) +}) + +const leave = () => { + const event = new Event('beforeunload', { cancelable: true }) + window.dispatchEvent(event) + return event.defaultPrevented +} + +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) +} + +describe('useUnsavedGuard', () => { + it('prevents the unload exactly while the report is unsaved', async () => { + renderHook(() => useUnsavedGuard()) + expect(leave()).toBe(false) + fillStorage() + await waitFor(() => expect(leave()).toBe(true)) + vi.restoreAllMocks() + act(() => useReportStore.getState().setConclusion('saved again')) + await waitFor(() => expect(leave()).toBe(false)) + }) + + it('leaves the listener off once the hook unmounts', async () => { + const { unmount } = renderHook(() => useUnsavedGuard()) + fillStorage() + await waitFor(() => expect(leave()).toBe(true)) + unmount() + expect(leave()).toBe(false) + }) + + it('is mounted by App, on a page that is not the editor', async () => { + window.history.pushState({}, '', '/') + render() + expect(leave()).toBe(false) + fillStorage() + await waitFor(() => expect(leave()).toBe(true)) + }) +}) diff --git a/apps/app/tests/unit/routes.HomeRoute.rescueCopy.test.tsx b/apps/app/tests/unit/routes.HomeRoute.rescueCopy.test.tsx new file mode 100644 index 00000000..652c3c0f --- /dev/null +++ b/apps/app/tests/unit/routes.HomeRoute.rescueCopy.test.tsx @@ -0,0 +1,150 @@ +/** + * The rescue copy (`JSON.stringify(report)`, the downloaded format) imported from Home: + * routed by content from the first KiB, read by the core's draft restore, opened as the + * original report; every refusal leaves the store and the tab's slots untouched. + */ +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import HomeRoute from '@/app/routes/HomeRoute' +import { MAX_ATTACHMENT_BYTES } from '@/pdf/import' +import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence' +import { useReportStore } from '@/state/reportStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import type { SheetIndex } from '@/services/sheetIndex' +import { buildGoldenReports, GOLDEN_REPORTS } from '../helpers/goldenReports' +import { loadTestSheet, minimalReport } from '../helpers/sheet' + +let sheet: SheetIndex + +beforeAll(async () => { + sheet = await loadTestSheet() +}) +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + sessionStorage.clear() + useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 }) + useReportStore.getState().clearTrapped() + vi.stubGlobal('alert', vi.fn()) +}) +afterEach(() => { + cleanup() + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +async function pick(file: File) { + render( + + + } /> + } /> + + , + ) + const button = screen.getByRole('button', { name: fr['home.import.cta'] }) + await waitFor(() => expect(button).toBeEnabled()) + fireEvent.change(document.querySelector('input[type="file"]')!, { + target: { files: [file] }, + }) +} + +const copyFile = (text: string, name = 'faunosteo-brouillon.json') => + new File([text], name, { type: 'application/json' }) + +describe('opening a rescue copy', () => { + it.each(GOLDEN_REPORTS)('reopens the %s report equal to the original', async (name) => { + const { reports } = buildGoldenReports(sheet) + await pick(copyFile(JSON.stringify(reports[name]))) + await screen.findByTestId('editor-route') + expect(useReportStore.getState().report).toEqual(reports[name]) + expect(useReportStore.getState().archive).toBeNull() + }) + + it('routes by content: no .json name, no type, leading blanks and a BOM', async () => { + const report = minimalReport(sheet, { conclusion: 'sniffed' }) + const text = ` \n${JSON.stringify(report)}` + await pick(new File([text], 'secours')) + await screen.findByTestId('editor-route') + expect(useReportStore.getState().report).toEqual(report) + }) + + it('announces a copy rebased on another sheet revision', async () => { + const stale = minimalReport(sheet, { + sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) }, + observations: [ + { + id: 'o', + zones: [{ annotationId: 'point-gone', viewId: 'main' }], + findings: [], + freeTextFindings: [], + comment: '', + }, + ], + }) + await pick(copyFile(JSON.stringify(stale))) + await screen.findByTestId('editor-route') + expect(window.alert).toHaveBeenCalledWith( + fr['editor.draft_rebased']!.replace('{count}', '1'), + ) + }) + + it('still sends a PDF down the PDF path', async () => { + await pick(new File(['%PDF-1.7 not really'], 'bilan.pdf', { type: 'application/pdf' })) + await screen.findByText(fr['home.import.error_no_attachment']!) + expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull() + }) +}) + +describe('refusing a file', () => { + const unreadable = JSON.stringify({ version: 7 }) + const refused: [string, () => File][] = [ + ['invalid JSON', () => copyFile('{not json')], + ['an unsupported version', () => copyFile(JSON.stringify({ version: 1 }))], + [ + 'a lone surrogate', + () => copyFile(JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))), + ], + [ + 'invalid UTF-8', + () => new File([new Uint8Array([0x7b, 0xff, 0xfe, 0x7d])], 'copie.json'), + ], + ] + + async function expectUntouched() { + await screen.findByText(fr['home.import.error_invalid_copy']!) + expect(useReportStore.getState().report).toBeNull() + expect(sessionStorage.getItem(DRAFT_KEY)).toBe(unreadable) + expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull() + expect(window.alert).not.toHaveBeenCalled() + expect(screen.queryByTestId('editor-route')).toBeNull() + } + + it.each(refused)('%s: error line, nothing changed, nothing held', async (_label, make) => { + sessionStorage.setItem(DRAFT_KEY, unreadable) + await pick(make()) + await expectUntouched() + }) + + it('an over-cap file is refused before any full read', async () => { + sessionStorage.setItem(DRAFT_KEY, unreadable) + const file = copyFile('{"version":3}') + Object.defineProperty(file, 'size', { value: MAX_ATTACHMENT_BYTES + 1 }) + const read = vi.spyOn(file, 'arrayBuffer') + await pick(file) + await expectUntouched() + expect(read).not.toHaveBeenCalled() + }) + + it.each(['internal', 'rebase_failed'])( + 'the core kind %s takes the engine message path, not the copy message', + async (kind) => { + vi.spyOn(sheet.ops, 'restoreDraft').mockReturnValue({ ok: false, kind } as never) + await pick(copyFile(JSON.stringify(minimalReport(sheet)))) + await screen.findByText(fr['home.import.error_core_unavailable']!) + expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull() + expect(useReportStore.getState().report).toBeNull() + }, + ) +}) diff --git a/apps/app/tests/unit/routes.coreStopped.test.tsx b/apps/app/tests/unit/routes.coreStopped.test.tsx index 5452a7d0..b3c8112e 100644 --- a/apps/app/tests/unit/routes.coreStopped.test.tsx +++ b/apps/app/tests/unit/routes.coreStopped.test.tsx @@ -2,7 +2,7 @@ * 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. + * and the stopped alerts (the beforeunload guard has its own hook test). */ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' @@ -167,24 +167,6 @@ describe('EditorRoute', () => { 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')) @@ -244,6 +226,8 @@ describe('the stopped text on the Home import line and the New report alert', () const submit = screen.getByRole('button', { name: fr['new_report.submit']! }) await waitFor(() => expect(submit).toBeEnabled()) await user.click(submit) + // A report is in progress (beforeEach): replacing it is confirmed first. + await user.click(await screen.findByRole('button', { name: fr['session.replace.confirm']! })) } it('Home import: the engine error line says the stopped text', async () => { diff --git a/apps/app/tests/unit/routes.heldSession.test.tsx b/apps/app/tests/unit/routes.heldSession.test.tsx index 35d54f38..5df48641 100644 --- a/apps/app/tests/unit/routes.heldSession.test.tsx +++ b/apps/app/tests/unit/routes.heldSession.test.tsx @@ -177,6 +177,10 @@ describe('a new report over a held draft', () => { const submit = screen.getByRole('button', { name: fr['new_report.submit'] }) await waitFor(() => expect(submit).toBeEnabled()) await user.click(submit) + // A draft sits in the slot: replacing it is confirmed first. + await user.click( + await screen.findByRole('button', { name: fr['session.replace.confirm']! }), + ) await waitFor(() => expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked']), ) diff --git a/apps/app/tests/unit/routes.replaceSession.test.tsx b/apps/app/tests/unit/routes.replaceSession.test.tsx new file mode 100644 index 00000000..64de66ae --- /dev/null +++ b/apps/app/tests/unit/routes.replaceSession.test.tsx @@ -0,0 +1,194 @@ +/** + * Replacing the bilan in progress (R3 final checks): New report and the Home file pick ask + * first when a report is in memory or a draft sits in the slot (named, unloaded and + * unsaved variants); Annuler changes nothing, Ouvrir goes back to the editor, Remplacer + * proceeds; nothing in progress, no dialog. + */ +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import HomeRoute from '@/app/routes/HomeRoute' +import NewReportRoute from '@/app/routes/NewReportRoute' +import { DRAFT_KEY } from '@/state/persistence' +import { useReportStore } from '@/state/reportStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import type { SheetIndex } from '@/services/sheetIndex' +import { loadTestSheet, minimalReport } from '../helpers/sheet' + +let sheet: SheetIndex + +beforeAll(async () => { + sheet = await loadTestSheet() +}) +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + sessionStorage.clear() + localStorage.clear() + useReportStore.setState({ + report: null, + archive: null, + activeObservationIndex: 0, + saveFailed: false, + }) + useReportStore.getState().clearTrapped() + vi.stubGlobal('alert', vi.fn()) +}) +afterEach(() => { + cleanup() + vi.unstubAllGlobals() + vi.restoreAllMocks() + useReportStore.setState({ report: null, saveFailed: false }) +}) + +const mount = (path: '/' | '/new') => + render( + + + } /> + } /> + } /> + + , + ) + +const openReport = (animalName = 'Mistral') => + useReportStore.getState().hydrateImport( + { report: minimalReport(sheet, { animal: { speciesId: 'equine', name: animalName } }), archive: null }, + sheet, + ) + +async function submitForm(user: ReturnType) { + 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) +} + +const button = (key: string) => screen.getByRole('button', { name: fr[key]! }) +/** A button of the open dialog (the page behind has its own Annuler). */ +const dialogButton = (key: string) => + within(screen.getByRole('dialog')).getByRole('button', { name: fr[key]! }) + +describe('New report over a bilan in progress', () => { + it('names the animal of the report in memory and replaces it on Remplacer', async () => { + const user = userEvent.setup() + openReport() + mount('/new') + await submitForm(user) + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent(fr['session.replace.body']!.replace('{animal}', 'Mistral')) + expect(dialog).not.toHaveTextContent(fr['session.replace.unsaved']!) + await user.click(button('session.replace.confirm')) + await screen.findByTestId('editor-route') + expect(useReportStore.getState().report?.animal.name).toBe('Rex') + }) + + it('renders an animal name with a replacement pattern literally', async () => { + const user = userEvent.setup() + openReport('Rex$&$1') + mount('/new') + await submitForm(user) + expect(await screen.findByRole('dialog')).toHaveTextContent('Le bilan de Rex$&$1 sera') + }) + + it('uses the unloaded text for a draft this page never opened', async () => { + const user = userEvent.setup() + sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet))) + mount('/new') + await submitForm(user) + expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!) + }) + + it('adds the unsaved line and the copy button when the tab storage is full', async () => { + const user = userEvent.setup() + openReport() + vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => { + throw new DOMException('full', 'QuotaExceededError') + }) + act(() => useReportStore.getState().setConclusion('edited')) + mount('/new') + await submitForm(user) + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent(fr['session.replace.unsaved']!) + expect(dialog).toHaveTextContent(fr['session.held.download']!) + }) + + it('Annuler changes nothing and Ouvrir goes to the editor', async () => { + const user = userEvent.setup() + openReport() + const before = useReportStore.getState().report + mount('/new') + await submitForm(user) + await screen.findByRole('dialog') + await user.click(dialogButton('common.cancel')) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(useReportStore.getState().report).toBe(before) + await user.click(button('new_report.submit')) + await screen.findByRole('dialog') + await user.click(button('session.replace.open')) + await screen.findByTestId('editor-route') + expect(useReportStore.getState().report).toBe(before) + }) + + it('asks nothing when no bilan is in progress', async () => { + const user = userEvent.setup() + mount('/new') + await submitForm(user) + await screen.findByTestId('editor-route') + expect(screen.queryByRole('dialog')).toBeNull() + expect(useReportStore.getState().report?.animal.name).toBe('Rex') + }) +}) + +describe('the Home file pick over a bilan in progress', () => { + const pickButton = () => button('home.import.cta') + const enabled = () => waitFor(() => expect(pickButton()).toBeEnabled()) + + it('asks first; Remplacer opens the picker inside the same click', async () => { + const user = userEvent.setup() + openReport() + const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined) + mount('/') + await enabled() + await user.click(pickButton()) + expect(await screen.findByRole('dialog')).toHaveTextContent('Mistral') + expect(click).not.toHaveBeenCalled() + fireEvent.click(button('session.replace.confirm')) + expect(click).toHaveBeenCalledOnce() + }) + + it('Annuler never opens the picker; Ouvrir goes to the editor; the report stays', async () => { + const user = userEvent.setup() + openReport() + const before = useReportStore.getState().report + const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined) + mount('/') + await enabled() + await user.click(pickButton()) + await user.click(dialogButton('common.cancel')) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + await user.click(pickButton()) + await user.click(button('session.replace.open')) + await screen.findByTestId('editor-route') + expect(click).not.toHaveBeenCalled() + expect(useReportStore.getState().report).toBe(before) + }) + + it('also asks for a draft only in the slot (unloaded text), nothing otherwise', async () => { + const user = userEvent.setup() + const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined) + mount('/') + await enabled() + await user.click(pickButton()) + expect(screen.queryByRole('dialog')).toBeNull() + expect(click).toHaveBeenCalledOnce() + sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet))) + await user.click(pickButton()) + expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!) + expect(click).toHaveBeenCalledOnce() + }) +}) diff --git a/apps/app/tests/unit/routes.trappingDraft.test.tsx b/apps/app/tests/unit/routes.trappingDraft.test.tsx new file mode 100644 index 00000000..fc97986c --- /dev/null +++ b/apps/app/tests/unit/routes.trappingDraft.test.tsx @@ -0,0 +1,181 @@ +/** + * A draft the engine traps on (R3 final checks): on a real poisoning runtime the editor + * shows the resolution panel (engine_failure row, engine notice), never the reload screen + * while the engine is not stopped; New report and Import answer the engine message then + * open the panel; the trapping (draft, archive) pair is read once (one trap across mount, + * New report, Import and remount); only the panel's Retry reads it again; a confirmed + * discard removes the draft and clears the memory. + */ +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import EditorRoute from '@/app/routes/EditorRoute' +import HomeRoute from '@/app/routes/HomeRoute' +import NewReportRoute from '@/app/routes/NewReportRoute' +import { setCoreRuntime } from '@/core/runtime' +import { bundledSheetProvider } from '@/sheets/provider' +import { setSheetProvider } from '@/sheets/useSheet' +import { useReportStore } from '@/state/reportStore' +import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import type { SheetIndex } from '@/services/sheetIndex' +import { testCoreRuntime, trappingCoreRuntime } from '../helpers/core' +import { loadTestSheet, minimalReport } from '../helpers/sheet' + +const MARKER = 'trap-me' +let sheet: SheetIndex +let draft: string +let traps: { count: number } +let engineStopped: () => boolean +let engineReady: () => Promise + +beforeAll(async () => { + sheet = await loadTestSheet() + draft = JSON.stringify(minimalReport(sheet, { conclusion: MARKER })) +}) +beforeEach(async () => { + useLocaleStore.setState({ locale: 'fr' }) + sessionStorage.clear() + localStorage.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().clearTrapped() + const trapping = await trappingCoreRuntime(MARKER) + traps = trapping.traps + engineStopped = () => trapping.runtime.stopped + engineReady = () => trapping.runtime.ready() + setCoreRuntime(trapping.runtime) + setSheetProvider(bundledSheetProvider) + // After the reset (an empty store mirrors no draft): the tab as a reload finds it. + sessionStorage.setItem(DRAFT_KEY, draft) +}) +afterEach(async () => { + cleanup() + vi.unstubAllGlobals() + vi.restoreAllMocks() + useReportStore.getState().clearTrapped() + setCoreRuntime(await testCoreRuntime()) + setSheetProvider(bundledSheetProvider) +}) + +const routes = (initial: string) => + render( + + + } /> + } /> + } /> + + , + ) + +async function expectEnginePanel() { + await screen.findByText(fr['session.held.notice_engine']!) + expect(screen.getByTestId('held-draft')).toHaveTextContent( + fr['session.held.draft_engine_failure']!.replace('{size}', /\d+ Ko/.exec( + screen.getByTestId('held-draft').textContent ?? '', + )![0]), + ) + expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull() + expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft) +} + +async function submitNewReport(user: ReturnType) { + 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) + await user.click( + await screen.findByRole('button', { name: fr['session.replace.confirm']! }), + ) +} + +async function pickCopy(user: ReturnType) { + const pick = screen.getByRole('button', { name: fr['home.import.cta']! }) + await waitFor(() => expect(pick).toBeEnabled()) + await user.click(pick) + vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined) + await user.click( + await screen.findByRole('button', { name: fr['session.replace.confirm']! }), + ) + const copy = JSON.stringify(minimalReport(sheet, { id: 'other' })) + fireEvent.change(document.querySelector('input[type="file"]')!, { + target: { files: [new File([copy], 'copie.json', { type: 'application/json' })] }, + }) +} + +describe('a draft the engine traps on', () => { + it('opens the engine_failure panel, never the reload screen', async () => { + routes('/editor') + await expectEnginePanel() + expect(traps.count).toBe(1) + expect(engineStopped()).toBe(false) + expect(useReportStore.getState().report).toBeNull() + }) + + it('is read once across mount, New report, Import and remount', async () => { + const user = userEvent.setup() + routes('/editor') + await expectEnginePanel() + cleanup() + + routes('/new') + await submitNewReport(user) + await waitFor(() => + expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']), + ) + await expectEnginePanel() + cleanup() + + routes('/') + await pickCopy(user) + await waitFor(() => + expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']), + ) + await expectEnginePanel() + cleanup() + + routes('/editor') + await expectEnginePanel() + expect(traps.count).toBe(1) + expect(useReportStore.getState().report).toBeNull() + expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull() + }) + + it('reads the pair again only on the panel Retry', async () => { + const user = userEvent.setup() + routes('/editor') + await expectEnginePanel() + // The instance that trapped is replaced in the background: retry on the fresh one. + await engineReady() + await user.click(screen.getByRole('button', { name: fr['session.held.retry'] })) + await waitFor(() => expect(traps.count).toBe(2)) + await expectEnginePanel() + }) + + it('removes only the draft after the confirmation and forgets the trap', async () => { + const user = userEvent.setup() + routes('/editor') + await expectEnginePanel() + await user.click(screen.getByRole('button', { name: fr['session.held.discard'] })) + expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft) + await user.click( + screen.getByRole('button', { name: fr['session.held.discard_confirm'] }), + ) + expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull() + expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull() + cleanup() + await engineReady() + // The memory is gone: the same text, stored again, is read (and traps) anew. + sessionStorage.setItem(DRAFT_KEY, draft) + routes('/editor') + await expectEnginePanel() + expect(traps.count).toBe(2) + }) +}) diff --git a/apps/app/tests/unit/state.quarantine.test.ts b/apps/app/tests/unit/state.quarantine.test.ts index 1ca0677e..e7e8d22c 100644 --- a/apps/app/tests/unit/state.quarantine.test.ts +++ b/apps/app/tests/unit/state.quarantine.test.ts @@ -32,6 +32,7 @@ beforeEach(() => { archive: null, activeObservationIndex: 0, }) + useReportStore.getState().clearTrapped() }) afterEach(() => vi.restoreAllMocks()) @@ -91,7 +92,7 @@ describe('an unreadable draft', () => { }) describe('a core failure while reading the draft', () => { - it.each(['core_unavailable', 'internal', 'rebase_failed'])( + it.each(['core_unavailable', 'rebase_failed'])( '%s leaves the draft and the archive untouched', (kind) => { const draft = JSON.stringify(minimalReport(sheet)) @@ -109,6 +110,91 @@ describe('a core failure while reading the draft', () => { ) }) +describe('a core trap while reading the draft (internal)', () => { + /** A sheet whose draft restore traps (`internal`), counting the reads. */ + function trappingSheet() { + const calls = { n: 0 } + const index = { + ...sheet, + ops: { + restoreDraft: () => { + calls.n += 1 + return { ok: false, kind: 'internal' } + }, + }, + } as unknown as SheetIndex + return { index, calls } + } + const draftText = () => JSON.stringify(minimalReport(sheet)) + + function seed() { + const draft = draftText() + sessionStorage.setItem(DRAFT_KEY, draft) + sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}') + return draft + } + + it('holds the draft (engine_failure) and its archive, both untouched', () => { + const draft = seed() + const { index } = trappingSheet() + const result = useReportStore.getState().restoreDraft(index) + expect(result).toMatchObject({ + kind: 'held', + held: [ + { text: 'draft', reason: 'engine_failure' }, + { text: 'archive', reason: 'companion' }, + ], + }) + expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft) + expect(sessionStorage.getItem(ARCHIVE_KEY)).toBe('{"kept":true}') + expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull() + expect(useReportStore.getState().report).toBeNull() + }) + + it('never reads the same pair again, except on the explicit retry', () => { + seed() + const { index, calls } = trappingSheet() + const store = useReportStore.getState() + store.restoreDraft(index) + expect(store.restoreDraft(index)).toMatchObject({ kind: 'held' }) + expect(calls.n).toBe(1) + store.restoreDraft(index, { retryTrapped: true }) + expect(calls.n).toBe(2) + }) + + it('answers a new session HELD with the engine cause, without a second read', () => { + seed() + const { index, calls } = trappingSheet() + const store = useReportStore.getState() + store.restoreDraft(index) + const draft = { practitioner: { name: 'p' } } as never + expect(store.initReport(draft, sheet.sheet.ref, index)).toEqual({ + ok: false, + reason: 'held', + engine: true, + }) + expect(store.hydrateImport({ report: minimalReport(sheet), archive: null }, index)).toEqual({ + ok: false, + reason: 'held', + engine: true, + }) + expect(calls.n).toBe(1) + }) + + it('reads again once the stored pair changed, or after a discard', () => { + seed() + const { index, calls } = trappingSheet() + const store = useReportStore.getState() + store.restoreDraft(index) + sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet, { conclusion: 'x' }))) + store.restoreDraft(index) + expect(calls.n).toBe(2) + store.discardSessionText('archive') + store.restoreDraft(index) + expect(calls.n).toBe(3) + }) +}) + describe('an unreadable archive beside a readable draft', () => { it('goes to its quarantine key while the draft restores', () => { sessionStorage.setItem( diff --git a/docs/development/RUST.md b/docs/development/RUST.md index b7a4fb02..55e22c48 100644 --- a/docs/development/RUST.md +++ b/docs/development/RUST.md @@ -518,7 +518,9 @@ Closed failure kinds: `invalid_json`, `invalid_shape`, `unknown_op`, 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. + guard (`app/useUnsavedGuard.ts`, called once in `App`, on every page) asks + before a reload, a close or a full-page redirect 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 @@ -643,7 +645,18 @@ application itself builds. (`reason: 'held'`, alert, then the panel) while such a text is held, and first reads through the core any draft this page never opened: an unreadable one is set aside before the new session replaces it, a - readable one is replaced as before. The draft mirror is written only + readable one is replaced as before. R3 final checks (2026-10-17): a draft + the engine traps on (`draft.restore` answering `internal`, an out-of-memory + trap on a very large draft) is held too, as the `engine_failure` row with + its archive as `companion` (`session.held.notice_engine`), kept as is; the + store remembers the (draft, archive) pair that trapped and answers held + without calling the core again, from the editor, New report and Import + alike (`ActionResult.engine`, alert `session.held_blocked_engine`), until + the panel's "Réessayer" (`retryTrapped`) or a confirmed discard; other core + failures keep their behaviour (`core_unavailable`: the reload screen). New + report and the Home file pick ask first (`ReplaceSessionDialog`: cancel, + open the bilan in progress, replace) whenever a report is in memory or a + draft sits in the slot. The draft mirror is written only when the report changes (an unrelated store change never removes it); a refused write keeps the previous text and shows the `editor.save_failed` banner until a write succeeds; a refused archive write at a new session @@ -839,6 +852,16 @@ imports it and restyles `data-state` in place as before. (owner decision 2026-10-15: until then both name attributes and its title held the French name). Display only; the frozen oracles stay as frozen and the tests apply this declared change before comparing. +9. R3 final checks (owner decisions 2026-10-17). The rescue copy (the + "Télécharger une copie" JSON, byte format of `osteo:draft`) is importable: + the Home picker accepts it beside the PDF, routed by content from the first + KiB (`%PDF-` goes the PDF path), refused above `MAX_ATTACHMENT_BYTES`, + decoded as strict UTF-8, read by the core's `draft.restore` (no archive) and + opened like an import; a copy the core refuses is `home.import.error_invalid_copy` + (file and session untouched), a rebased one shows `editor.draft_rebased`. + The copy lacks the archive envelope, which the original PDF keeps. A draft + that traps the engine opens the resolution panel and is read once (§8.7 + item 3); importing the copy of a trapping draft runs the same input again. ### 9.5 Measurements