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.
This commit is contained in:
bchanot committed 2026-10-17 12:58:57 +02:00
1 parent 9464651140
commit 9bd9acaf58
22 files changed
+1090 -68

No files matched your search

+3
View File
@@ -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 (
<ConfigProvider>
<AuthProvider>
+5 -14
View File
@@ -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<string | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
@@ -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()
}}
/>
)
}
+96 -11
View File
@@ -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<string> {
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<HTMLInputElement | null>(null)
@@ -120,10 +167,11 @@ export default function HomeRoute() {
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(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<ImportRead> {
// 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<ImportRead> {
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() {
<input
ref={fileRef}
type="file"
accept="application/pdf,.pdf"
accept="application/pdf,.pdf,application/json,.json"
className="hidden"
onChange={onPickFile}
/>
<Button
variant="secondary"
size="lg"
onClick={() => fileRef.current?.click()}
onClick={() =>
isSessionInProgress()
? setConfirmingReplace(true)
: fileRef.current?.click()
}
disabled={busy || sheet.status !== 'ready'}
>
{busy ? t('home.import.loading') : t('home.import.cta')}
@@ -224,6 +299,16 @@ export default function HomeRoute() {
</Card>
</div>
</section>
<ReplaceSessionDialog
open={confirmingReplace}
onCancel={() => setConfirmingReplace(false)}
onOpen={() => navigate('/editor')}
onConfirm={() => {
// The picker opens inside this click: a later call loses the user activation.
fileRef.current?.click()
setConfirmingReplace(false)
}}
/>
</main>
)
}
+22 -3
View File
@@ -5,6 +5,7 @@ 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 ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label'
@@ -13,7 +14,7 @@ import {
readCachedPractitioner,
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore'
import { isSessionInProgress, useReportStore } from '@/state/reportStore'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { useT } from '@/i18n/useT'
import { coreFailureMessage } from '@/core/failure'
@@ -35,6 +36,7 @@ export default function NewReportRoute() {
})
const [owner, setOwner] = useState<Owner>({ name: '' })
const [date, setDate] = useState(todayIso())
const [confirmingReplace, setConfirmingReplace] = useState(false)
useEffect(() => {
const cached = readCachedPractitioner()
@@ -47,8 +49,14 @@ export default function NewReportRoute() {
owner.name.trim() &&
sheet.status === 'ready'
async function submit() {
function submit() {
if (!canSubmit || sheet.status !== 'ready') return
if (isSessionInProgress()) setConfirmingReplace(true)
else void createReport()
}
async function createReport() {
if (sheet.status !== 'ready') return
writeCachedPractitioner(practitioner)
// The loaded sheet lets the store read a draft this page never opened before replacing it.
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
@@ -71,7 +79,9 @@ export default function NewReportRoute() {
)
if (created.ok) navigate('/editor')
else if (created.reason === 'held') {
window.alert(t('session.held_blocked'))
window.alert(
t(created.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
)
navigate('/editor')
} else window.alert(coreFailureMessage(t))
}
@@ -129,6 +139,15 @@ export default function NewReportRoute() {
</Button>
</div>
</div>
<ReplaceSessionDialog
open={confirmingReplace}
onCancel={() => setConfirmingReplace(false)}
onOpen={() => navigate('/editor')}
onConfirm={() => {
setConfirmingReplace(false)
void createReport()
}}
/>
</main>
)
}
+19
View File
@@ -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])
}
@@ -56,7 +56,13 @@ export default function HeldSessionPanel({
return (
<main className="p-4 sm:p-6 space-y-4 max-w-2xl">
<Notice tone="error">{t('session.held.notice')}</Notice>
<Notice tone="error">
{t(
held.some((item) => item.reason === 'engine_failure')
? 'session.held.notice_engine'
: 'session.held.notice',
)}
</Notice>
<ul className="space-y-3">
{held.map((item) => (
<li
@@ -0,0 +1,54 @@
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { CopyReportButton } from '@/components/report/CoreStoppedNotice'
import { isUnsaved, useReportStore } from '@/state/reportStore'
import { useT } from '@/i18n/useT'
export interface ReplaceSessionDialogProps {
open: boolean
onCancel: () => 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 (
<Dialog open={open} onClose={onCancel} title={t('session.replace.title')} size="sm">
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
{unsaved && (
<div className="mt-3 space-y-2">
<p className="text-sm">{t('session.replace.unsaved')}</p>
<CopyReportButton />
</div>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{t('common.cancel')}
</Button>
<Button type="button" variant="secondary" onClick={onOpen}>
{t('session.replace.open')}
</Button>
<Button type="button" variant="danger" onClick={onConfirm}>
{t('session.replace.confirm')}
</Button>
</div>
</Dialog>
)
}
+19 -2
View File
@@ -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',
+19 -2
View File
@@ -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",
+19 -2
View File
@@ -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<ArchiveImport> {
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')
}
+72 -7
View File
@@ -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<ReportStore, 'saveFailed' | 'report'>): 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<string> = new Set([
export const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = 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<ReportStore>((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
}