fix(store): hold session texts whose set-aside fails, never overwrite them

This commit is contained in:
bchanot committed 2026-10-14 23:11:59 +02:00
1 parent 1312b366b1
commit e34b7f282e
19 files changed
+1093 -86

No files matched your search

+9
View File
@@ -182,6 +182,15 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [x] L1.4 checks: rust:check, stale-module refusal shown, wasm:build, Node 915, PGlite 12 files, real stack 446/446, types no drift, check:all green; verifier CONFORME 13/13, security PASS (6 LOW)
- [x] L1.5 docs (RUST.md 8.6/8.7, PDF-FORMAT, CHANGELOG) + memory BDR-051, LRN-055, EVAL-021, journal
- [ ] R2 follow-ups: Firefox/WebKit CSP run (no browser build here; owner's manual LAN run covers its browsers), import in a Web Worker + PDF import hardening gate (R4, PDF_IMPORT_HARDENING.md §5), React error boundary (not decided), base images by digest (Step 27), wording of the storage-full degraded notice, CSP refuses the footer's external credit logo (RUST.md 8.8), no CI/CD runner on the forge (workflows prepared, never executed), rustls 0.23.45 advisories RUSTSEC-2026-0346/0347/0348 (worker; not applicable: no brotli, built-in session cache, no ECH) → `cargo update -p rustls` ≥ 0.23.46 + worker:test + e2e:avatar, unreadable session archive under full storage removed by a later reset (security LOW, decision needed), `supabase/.temp/cli-latest` tracked by mistake (untrack + ignore), wasm-bindgen boundary invariant (JSON.stringify callers only, RUST.md 8.7)
- [ ] R2 maintenance (owner brief 2026-10-14, branch bugfix/r2-maintenance; merge authorised after tests + audits)
- [x] A rustls 0.23.45 → 0.23.46 (RUSTSEC-2026-0346..0349; rust:check, worker:test, worker:image, e2e:avatar 5/5 on the new image) (f99b4a5)
- [x] C `supabase/.temp/cli-latest` untracked, local copy kept (1312b36)
- [ ] B session texts never overwritten after a failed set-aside (owner UI choice 2026-10-14: resolution panel, save-failure banner; set-aside texts UI = follow-up)
- [ ] B.1 persistence: occupied quarantine slot refused; pair set-aside with rollback; save outcome reported
- [ ] B.2 store: `held` restore result (unreadable draft / archive / pre-rebase original), no patch applied; mirror written only on report change; session edges (new, import) guarded on foreign texts via the core; discard + open-adapted actions; `saveFailed` flag
- [ ] B.3 UI: HeldSessionPanel (download copy, delete with confirmation, open adapted with confirmation, retry), save-failure banner, Home/New refusal → editor; i18n FR/EN
- [ ] B.4 tests: quota, refused writes, corrupted data, later overwriting actions (new, import, reset, unrelated set), panel flows
- [ ] B.5 docs (RUST.md 8.7/8.8, CHANGELOG), gates (verifier, security), check:all, finish into develop
- [ ] R3 anatomy core: tree, one sanitiser, serialiser, layer renderer, `compose_view_svg`; app canvas switched; composed views frozen as trees first
- [ ] R4 pdf core: reader (Web Worker, BLK-009 browser measurements) + writer (`pdf-writer`, Std14 AFM, draw log; lines/rects/colours golden frozen with the TS engine first, D-R2) + `report-compare` tool; `packages/pdf` deleted; N-1 scanner reads R4 PDFs
- [ ] R5 curation pipeline + importer + upload tool: seed golden regenerated once (new `documentSha256`, D-R5), `packages/anatomy` + `packages/domain` deleted, docs map; all before Step 13
+1
View File
@@ -12,6 +12,7 @@ Versions follow [Semantic Versioning](https://semver.org/).
### Fixed (maintenance after R2, 2026-10-14)
- **Session texts never lost when the browser storage is full.** A draft or archive the running build cannot read, and that cannot be set aside (storage full, or the quarantine slot already holds an earlier text, which is no longer replaced), now stays where it is: nothing is opened over it, and the editor shows a resolution panel with an exact copy to download, a permanent deletion or (for a draft to adapt to the current sheet) the adapted version, each behind a confirmation, and a retry. "New report" and "Import" refuse to start while such a text is held and send the practitioner to that panel; they also read a draft the page never opened before replacing it, so an unreadable one is set aside first. An unreadable draft is set aside together with the archive kept beside it. The draft mirror no longer reacts to unrelated store changes, and a refused draft write shows a storage-full banner in the editor. No change for a readable session.
- `supabase/.temp/cli-latest` (the Supabase CLI's version-check cache) is no longer tracked: it had been committed before the `supabase/.temp/` ignore rule existed, so every CLI run dirtied the tree. The local copy stays; the ignore rules already cover `.temp/`, `.branches/` and `supabase/.env.*`.
### Changed (Rust R2, domain core, 2026-10-14)
+46 -4
View File
@@ -15,10 +15,14 @@ import EditInfosDialog, {
} from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import HeldSessionPanel from '@/components/report/HeldSessionPanel'
import Notice from '@/components/ui/Notice'
import Button from '@/components/ui/Button'
import {
useReportStore,
type ActionResult,
type HeldText,
type RestoreOptions,
type RestoreResult,
} from '@/state/reportStore'
import { writeCachedPractitioner } from '@/state/practitionerCache'
@@ -77,6 +81,13 @@ export default function EditorRoute() {
)
// The core failed while reading the draft: stay here, keep the draft, offer a retry.
const [restoreFailed, setRestoreFailed] = useState(false)
// Texts that could not be set aside: the resolution panel replaces the editor.
const [held, setHeld] = useState<HeldText[] | null>(null)
// Each resolution step (retry, deletion, confirmed replacement) runs the restore again.
const [restoreAttempt, setRestoreAttempt] = useState(0)
const restoreOptions = useRef<RestoreOptions>({})
// The attempt that ended held: the effect runs again on every render, the restore must not.
const heldAttempt = useRef<number | null>(null)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
const [editDraft, setEditDraft] = useState<Identity | null>(null)
@@ -91,17 +102,25 @@ export default function EditorRoute() {
// A draft rebased on another sheet is announced with its unresolved count,
// an unreadable one is set aside. While the core cannot run, nothing is
// read or written and the page stays on the degraded notice (no redirect).
// A text that could not be set aside stays in place behind the resolution panel.
useEffect(() => {
if (report) return
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet')
return
if (sheet.status === 'ready') {
const result = store.restoreDraft(sheet.index)
// Nothing could be read or set aside: stay, keep the draft where it is.
if (result?.kind === 'core_unavailable' || result?.kind === 'unreadable_kept') {
if (heldAttempt.current === restoreAttempt) return
const result = store.restoreDraft(sheet.index, restoreOptions.current)
restoreOptions.current = {}
if (result?.kind === 'core_unavailable') {
setRestoreFailed(true)
return
}
if (result?.kind === 'held') {
heldAttempt.current = restoreAttempt
setHeld(result.held)
return
}
setHeld(null)
const alert = result ? restoreAlert(result, t) : null
if (alert && !rebaseAlerted.current) {
rebaseAlerted.current = true
@@ -110,7 +129,9 @@ export default function EditorRoute() {
}
if (sheet.status !== 'loading' && !useReportStore.getState().report)
navigate('/')
}, [report, sheet, store, navigate, t])
}, [report, sheet, store, navigate, t, restoreAttempt])
const retryRestore = useCallback(() => setRestoreAttempt((n) => n + 1), [])
useEffect(() => {
if (sheet.status !== 'ready' || typeof sessionStorage === 'undefined')
@@ -238,6 +259,22 @@ export default function EditorRoute() {
if (restoreFailed) {
return <CoreUnavailable onRetry={() => window.location.reload()} />
}
if (held && !report) {
return (
<HeldSessionPanel
held={held}
onDiscard={(text) => {
store.discardSessionText(text)
retryRestore()
}}
onOpenAdapted={() => {
restoreOptions.current = { replaceOriginal: true }
retryRestore()
}}
onRetry={retryRestore}
/>
)
}
if (!report) return null
if (sheet.status === 'loading') {
return (
@@ -262,6 +299,11 @@ export default function EditorRoute() {
})
}
/>
{store.saveFailed && (
<Notice tone="error" className="mx-4 sm:mx-6 mt-4">
{t('editor.save_failed')}
</Notice>
)}
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
<AnatomyCanvas
+10 -1
View File
@@ -129,7 +129,16 @@ 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)
hydrateImport({ report: rebase.report, archive: outcome.archive })
const opened = hydrateImport(
{ report: rebase.report, archive: outcome.archive },
index,
)
// A tab text that could not be set aside would be overwritten: resolve it first.
if (!opened.ok) {
window.alert(t('session.held_blocked'))
navigate('/editor')
return
}
const lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
navigate('/editor')
+9 -4
View File
@@ -13,8 +13,7 @@ import {
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore'
import { useSheetAvailability } from '@/sheets/useSheet'
import { coreRuntime } from '@/core/runtime'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { useT } from '@/i18n/useT'
/** The one species this build ships a sheet for. */
@@ -49,7 +48,9 @@ export default function NewReportRoute() {
async function submit() {
if (!canSubmit || sheet.status !== 'ready') return
writeCachedPractitioner(practitioner)
if (!(await coreRuntime().ready())) {
// The loaded sheet lets the store read a draft this page never opened before replacing it.
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) {
window.alert(t('sheet.core_unavailable'))
return
}
@@ -64,9 +65,13 @@ export default function NewReportRoute() {
recommendations: '',
},
sheet.sheet.ref,
index,
)
if (created.ok) navigate('/editor')
else window.alert(t('core.action_failed'))
else if (created.reason === 'held') {
window.alert(t('session.held_blocked'))
navigate('/editor')
} else window.alert(t('core.action_failed'))
}
return (
@@ -0,0 +1,145 @@
import { useState } from 'react'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice'
import { todayIso } from '@/lib/dates'
import { readSessionText, type SessionText } from '@/state/persistence'
import type { HeldText } from '@/state/reportStore'
import { useT } from '@/i18n/useT'
export interface HeldSessionPanelProps {
held: readonly HeldText[]
/** Removes the text from the tab; called only after the practitioner confirmed. */
onDiscard: (text: SessionText) => void
/** Opens the rebased draft, replacing its original; called only after confirmation. */
onOpenAdapted: () => void
onRetry: () => void
}
type Pending = { action: 'discard'; text: SessionText } | { action: 'open' }
const FILE_STEM: Record<SessionText, string> = {
draft: 'faunosteo-brouillon',
archive: 'faunosteo-archive',
}
/** Saves the stored text verbatim (it is JSON.stringify output: ASCII escapes, lossless). */
function downloadCopy(text: SessionText): void {
const raw = readSessionText(text)
if (raw === null) return
const url = URL.createObjectURL(new Blob([raw], { type: 'application/json' }))
const a = document.createElement('a')
a.href = url
a.download = `${FILE_STEM[text]}-${todayIso()}.json`
a.click()
URL.revokeObjectURL(url)
}
function rowLabelKey(item: HeldText): string {
return `session.held.${item.text}_${item.reason}`
}
/**
* Resolution of the session texts the store holds in place because their safety copy
* failed (STEP R2 maintenance B): one row per text, a copy to download, an explicit
* deletion or replacement behind a confirmation, a retry. Nothing happens on its own.
*/
export default function HeldSessionPanel({
held,
onDiscard,
onOpenAdapted,
onRetry,
}: HeldSessionPanelProps) {
const t = useT()
const [pending, setPending] = useState<Pending | null>(null)
function confirm() {
if (!pending) return
if (pending.action === 'discard') onDiscard(pending.text)
else onOpenAdapted()
setPending(null)
}
return (
<main className="p-4 sm:p-6 space-y-4 max-w-2xl">
<Notice tone="error">{t('session.held.notice')}</Notice>
<ul className="space-y-3">
{held.map((item) => (
<li
key={item.text}
className="rounded-lg border border-[var(--color-border)] p-3 space-y-2"
data-testid={`held-${item.text}`}
>
<p className="text-sm">
{t(rowLabelKey(item)).replace(
'{size}',
t('session.held.size_kb').replace(
'{n}',
String(Math.max(1, Math.ceil(item.bytes / 1024))),
),
)}
</p>
<div className="flex flex-wrap gap-2">
<Button variant="secondary" onClick={() => downloadCopy(item.text)}>
{t(
item.reason === 'pre_rebase'
? 'session.held.download_original'
: 'session.held.download',
)}
</Button>
{item.reason === 'pre_rebase' ? (
<Button variant="ghost" onClick={() => setPending({ action: 'open' })}>
{t('session.held.open_adapted')}
</Button>
) : (
<Button
variant="ghost"
onClick={() => setPending({ action: 'discard', text: item.text })}
>
{t('session.held.discard')}
</Button>
)}
</div>
</li>
))}
</ul>
<div className="flex justify-end">
<Button onClick={onRetry}>{t('session.held.retry')}</Button>
</div>
<Dialog
open={pending !== null}
onClose={() => setPending(null)}
title={t(
pending?.action === 'open'
? 'session.held.open_title'
: `session.held.discard_title_${pending?.action === 'discard' ? pending.text : 'draft'}`,
)}
size="sm"
>
<p className="text-sm text-[var(--color-ink-muted)]">
{t(
pending?.action === 'open'
? 'session.held.open_body'
: 'session.held.discard_body',
)}
</p>
<div className="mt-4 flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => setPending(null)}>
{t('common.cancel')}
</Button>
<Button
type="button"
variant={pending?.action === 'open' ? 'primary' : 'danger'}
onClick={confirm}
>
{t(
pending?.action === 'open'
? 'session.held.open_confirm'
: 'session.held.discard_confirm',
)}
</Button>
</div>
</Dialog>
</main>
)
}
+40
View File
@@ -82,6 +82,46 @@ export const en: Dict = {
'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).',
'editor.draft_quarantined':
"This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted.",
'editor.save_failed':
"This tab's storage is full: your latest changes are no longer saved in the tab. Export the PDF to keep them.",
'session.held.notice':
"Some data in this tab could not be set aside in the browser's storage (not enough space, or the slot is taken). It is kept as it is; nothing was deleted. Until it is resolved, no report can be created or imported in this tab.",
'session.held.draft_unreadable':
"Draft this version cannot read ({size})",
'session.held.draft_pre_rebase':
"Draft to adapt to the current anatomical sheet; its original could not be set aside ({size})",
'session.held.archive_unreadable':
"Archive of the imported report, unreadable ({size})",
'session.held.archive_companion':
"Archive of the imported report that goes with this draft ({size})",
'session.held.size_kb':
"{n} KB",
'session.held.download':
"Download a copy",
'session.held.download_original':
"Download the original",
'session.held.discard':
"Delete permanently…",
'session.held.open_adapted':
"Open the adapted version…",
'session.held.retry':
"Retry",
'session.held.discard_title_draft':
"Delete this draft permanently?",
'session.held.discard_title_archive':
"Delete this archive permanently?",
'session.held.discard_body':
"This text will be erased from this tab and cannot be recovered. Download a copy first to keep it.",
'session.held.discard_confirm':
"Delete",
'session.held.open_title':
"Open the adapted version?",
'session.held.open_body':
"The original will be replaced in this tab by the version adapted to the current anatomical sheet (items not found are kept with their labels). Download the original first to keep it.",
'session.held.open_confirm':
"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.",
'editor.edit_infos': 'Edit info',
'editor.edit_dialog_title': 'Edit information',
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
+40
View File
@@ -88,6 +88,46 @@ export const fr: Dict = {
'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).',
'editor.draft_quarantined':
"Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé.",
'editor.save_failed':
"L'espace de stockage de cet onglet est plein : vos dernières modifications ne sont plus enregistrées dans l'onglet. Exportez le PDF pour les conserver.",
'session.held.notice':
"Des données de cet onglet n'ont pas pu être mises de côté dans le stockage du navigateur (espace insuffisant ou emplacement occupé). Elles sont conservées telles quelles ; rien n'a été supprimé. Tant qu'elles ne sont pas résolues, aucun bilan ne peut être créé ou importé dans cet onglet.",
'session.held.draft_unreadable':
"Brouillon illisible par cette version ({size})",
'session.held.draft_pre_rebase':
"Brouillon à adapter à la fiche anatomique actuelle ; son original n'a pas pu être mis de côté ({size})",
'session.held.archive_unreadable':
"Archive du bilan importé, illisible ({size})",
'session.held.archive_companion':
"Archive du bilan importé qui accompagne ce brouillon ({size})",
'session.held.size_kb':
"{n} Ko",
'session.held.download':
"Télécharger une copie",
'session.held.download_original':
"Télécharger l'original",
'session.held.discard':
"Supprimer définitivement…",
'session.held.open_adapted':
"Ouvrir la version adaptée…",
'session.held.retry':
"Réessayer",
'session.held.discard_title_draft':
"Supprimer définitivement ce brouillon ?",
'session.held.discard_title_archive':
"Supprimer définitivement cette archive ?",
'session.held.discard_body':
"Ce texte sera effacé de cet onglet et ne pourra pas être récupéré. Téléchargez d'abord une copie pour le garder.",
'session.held.discard_confirm':
"Supprimer",
'session.held.open_title':
"Ouvrir la version adaptée ?",
'session.held.open_body':
"L'original sera remplacé dans cet onglet par la version adaptée à la fiche anatomique actuelle (les éléments non retrouvés sont conservés avec leurs libellés). Téléchargez d'abord l'original pour le garder.",
'session.held.open_confirm':
"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.",
'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",
+68 -20
View File
@@ -14,12 +14,13 @@ import type { Report, ReportArchiveEnvelope } from '@faunosteo/core-wasm/types'
export interface ReportPersistence {
/** The raw draft text, null when there is none. */
loadText(): string | null
save(report: Report | null): void
/** Writes (or removes, for null) the draft; false when the storage refused the write. */
save(report: Report | null): boolean
}
export interface ArchivePersistence {
loadText(): string | null
save(archive: ReportArchiveEnvelope | null): void
save(archive: ReportArchiveEnvelope | null): boolean
}
export const DRAFT_KEY = 'osteo:draft'
@@ -38,25 +39,49 @@ function storage(): Storage | null {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
}
function writeOrRemove(key: string, value: unknown): void {
/** A refused write (quota) leaves the previous value in place, as the Storage API does. */
function writeOrRemove(key: string, value: unknown): boolean {
const store = storage()
if (!store) return
if (!store) return false
if (value === null) {
store.removeItem(key)
return
return true
}
try {
store.setItem(key, JSON.stringify(value))
return true
} catch (err) {
// Quota exceeded: the session goes on, only the mirror is lost.
if (import.meta.env.DEV) console.warn(`${key} not saved`, err)
return false
}
}
/**
* Writes `raw` into an empty quarantine slot; a slot already holding another text is
* never replaced (that earlier text would be lost). Answers whether `raw` is now in
* the slot and whether this call wrote it (so a failed pair can undo its own copy).
*/
function copyToSlot(
store: Storage,
slot: QuarantineSlot,
raw: string,
): 'written' | 'present' | 'refused' {
const current = store.getItem(QUARANTINE_KEYS[slot])
if (current === raw) return 'present'
if (current !== null) return 'refused'
try {
store.setItem(QUARANTINE_KEYS[slot], raw)
return 'written'
} catch (err) {
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
return 'refused'
}
}
/**
* Copies `raw` into its quarantine slot, then removes `source` (when given)
* only if that copy succeeded: a full storage keeps the text where it was.
* Returns whether the text is now in quarantine.
* only if that copy succeeded: a full storage or an occupied slot keeps the
* text where it was. Returns whether the text is now in quarantine.
*/
export function quarantine(
slot: QuarantineSlot,
@@ -65,26 +90,49 @@ export function quarantine(
): boolean {
const store = storage()
if (!store) return false
try {
store.setItem(QUARANTINE_KEYS[slot], raw)
} catch (err) {
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
return false
}
if (copyToSlot(store, slot, raw) === 'refused') return false
if (source) store.removeItem(source)
return true
}
/**
* Sets an unreadable draft aside together with the archive kept beside it, so a
* later session never removes that archive on its own. Both copies or neither:
* when one fails, the copy this call wrote is undone and both texts stay in place.
*/
export function quarantineSession(draft: string, archive: string | null): boolean {
const store = storage()
if (!store) return false
const draftCopy = copyToSlot(store, 'draft', draft)
if (draftCopy === 'refused') return false
if (archive !== null && copyToSlot(store, 'archive', archive) === 'refused') {
if (draftCopy === 'written') store.removeItem(QUARANTINE_KEYS.draft)
return false
}
store.removeItem(DRAFT_KEY)
if (archive !== null) store.removeItem(ARCHIVE_KEY)
return true
}
/** The session texts a resolution may download or remove, by their kind. */
export const SESSION_KEYS = { draft: DRAFT_KEY, archive: ARCHIVE_KEY } as const
export type SessionText = keyof typeof SESSION_KEYS
export function readSessionText(text: SessionText): string | null {
return storage()?.getItem(SESSION_KEYS[text]) ?? null
}
/** Removes a session text: only ever called on the practitioner's confirmed request. */
export function removeSessionText(text: SessionText): void {
storage()?.removeItem(SESSION_KEYS[text])
}
export const sessionStoragePersistence: ReportPersistence = {
loadText: () => storage()?.getItem(DRAFT_KEY) ?? null,
save(report) {
writeOrRemove(DRAFT_KEY, report)
},
save: (report) => writeOrRemove(DRAFT_KEY, report),
}
export const sessionStorageArchivePersistence: ArchivePersistence = {
loadText: () => storage()?.getItem(ARCHIVE_KEY) ?? null,
save(archive) {
writeOrRemove(ARCHIVE_KEY, archive)
},
save: (archive) => writeOrRemove(ARCHIVE_KEY, archive),
}
+144 -26
View File
@@ -18,12 +18,14 @@ import { nowIso } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import {
ARCHIVE_KEY,
DRAFT_KEY,
quarantine,
quarantineSession,
removeSessionText,
sessionStorageArchivePersistence,
sessionStoragePersistence,
type ArchivePersistence,
type ReportPersistence,
type SessionText,
} from './persistence'
/**
@@ -37,6 +39,9 @@ import {
* The per-tab draft is mirrored through the persistence adapter and restored
* once the sheet is known; the archive an import brought along is kept
* beside the report and written only when the session starts or ends.
* A session text this page has not read, or whose safety copy failed, is
* never removed or overwritten implicitly: restore holds it, and a new
* session (new report, import) is refused until the practitioner resolves it.
*/
export type { NewReportDraft }
@@ -48,6 +53,26 @@ export interface ImportedSession {
export interface ActionResult {
ok: boolean
/** Refused because a session text is held (it could not be set aside and would be lost). */
reason?: 'held'
}
/**
* 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.
*/
export interface HeldText {
text: SessionText
reason: 'unreadable' | 'companion' | 'pre_rebase'
/** UTF-8 size of the stored text, for the resolution panel. */
bytes: number
}
export interface RestoreOptions {
/** The practitioner confirmed that the rebased draft may replace its original. */
replaceOriginal?: boolean
}
/** What a draft restore did; `null` from the action when there was nothing to restore. */
@@ -56,10 +81,10 @@ export type RestoreResult =
/** The draft is unreadable by this build: set aside, verbatim, under a quarantine key. */
| { kind: 'quarantined' }
/**
* The draft is unreadable but could not be set aside (storage full): it stays in
* `osteo:draft`, and the caller must not start anything that would overwrite it.
* Texts that could not be set aside stay where they are, nothing is opened, and the
* store refuses any new session until they are resolved.
*/
| { kind: 'unreadable_kept' }
| { kind: 'held'; held: HeldText[] }
/** The core failed: nothing read, nothing written, the draft is where it was. */
| { kind: 'core_unavailable' }
@@ -68,15 +93,27 @@ export interface ReportStore {
/** The envelope of the imported archive, as exported; null otherwise. */
archive: ReportArchiveEnvelope | null
activeObservationIndex: number
initReport: (draft: NewReportDraft, sheet: SheetRef) => ActionResult
/** Opens an imported report (read and rebased by the core) with its archive. */
hydrateImport: (session: ImportedSession) => void
/** The last draft mirror write was refused (storage full): the tab's copy is stale. */
saveFailed: boolean
/** Starts a report; refused (`held`) while an unread session text cannot be set aside. */
initReport: (
draft: NewReportDraft,
sheet: SheetRef,
index: SheetIndex,
) => ActionResult
/** Opens an imported report (read and rebased by the core) with its archive; same guard. */
hydrateImport: (session: ImportedSession, index: SheetIndex) => ActionResult
/**
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
* written on another revision; a no-op (null) when a report is already open
* or there is no draft.
* or there is nothing to restore.
*/
restoreDraft: (index: SheetIndex) => RestoreResult | null
restoreDraft: (
index: SheetIndex,
options?: RestoreOptions,
) => RestoreResult | null
/** Removes a held session text, on the practitioner's confirmed request; no-op once a report is open. */
discardSessionText: (text: SessionText) => void
addObservation: () => ActionResult
removeObservation: (index: number) => ActionResult
moveObservationUp: (index: number) => ActionResult
@@ -93,13 +130,14 @@ export interface ReportStore {
}
type Patch = Partial<
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex' | 'saveFailed'>
>
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
type Getter = () => ReportStore
const OK: ActionResult = { ok: true }
const FAILED: ActionResult = { ok: false }
const HELD: ActionResult = { ok: false, reason: 'held' }
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
@@ -134,37 +172,94 @@ const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
'lone_surrogate',
])
/** Reads the draft through the core; unreadable content goes to quarantine, never away. */
function utf8Bytes(text: string): number {
return new TextEncoder().encode(text).length
}
function held(text: SessionText, reason: HeldText['reason'], raw: string): HeldText {
return { text, reason, bytes: utf8Bytes(raw) }
}
type Restored = { result: RestoreResult; patch?: Patch } | null
/** An archive with no draft beside it can never be restored: set it aside, or hold it. */
function restoreOrphanArchive(archiveText: string | null): Restored {
if (archiveText === null || quarantine('archive', archiveText, ARCHIVE_KEY)) return null
return { result: { kind: 'held', held: [held('archive', 'companion', archiveText)] } }
}
/** An unreadable draft goes to quarantine with its archive, never away; else both are held. */
function setAsideUnreadable(draft: string, archiveText: string | null): Restored {
if (quarantineSession(draft, archiveText)) return { result: { kind: 'quarantined' } }
const kept = [held('draft', 'unreadable', draft)]
if (archiveText !== null) kept.push(held('archive', 'companion', archiveText))
return { result: { kind: 'held', held: kept } }
}
/**
* Reads the draft through the core. Unreadable content goes to quarantine, never away;
* a text whose safety copy fails is held in place and nothing is opened (opening would
* let the mirror overwrite the draft, or a later session remove the archive).
*/
function restore(
index: SheetIndex,
persistence: ReportPersistence,
archives: ArchivePersistence,
): { result: RestoreResult; patch?: Patch } | null {
options: RestoreOptions,
): Restored {
const draft = persistence.loadText()
if (draft === null) return null
const archiveText = archives.loadText()
if (draft === null) return restoreOrphanArchive(archiveText)
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
// 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' } }
}
const setAside = quarantine('draft', draft, DRAFT_KEY)
return { result: { kind: setAside ? 'quarantined' : 'unreadable_kept' } }
return setAsideUnreadable(draft, archiveText)
}
const { rebase, archive, archiveRejected } = outcome.value
const kept: HeldText[] = []
if (archiveRejected && archiveText !== null) {
quarantine('archive', archiveText, ARCHIVE_KEY)
if (!quarantine('archive', archiveText, ARCHIVE_KEY)) {
kept.push(held('archive', 'unreadable', archiveText))
}
}
if (rebase.rebased && rebase.unresolvedZones + rebase.unresolvedFindings > 0) {
quarantine('draftPreRebase', draft)
const flagged = rebase.unresolvedZones + rebase.unresolvedFindings > 0
if (rebase.rebased && flagged && !options.replaceOriginal) {
if (!quarantine('draftPreRebase', draft)) {
kept.push(held('draft', 'pre_rebase', draft))
}
}
if (kept.length > 0) return { result: { kind: 'held', held: kept } }
return {
result: { kind: 'restored', rebase },
patch: { report: rebase.report, archive, activeObservationIndex: 0 },
}
}
/**
* Before a new session replaces texts this page never read: an unreadable draft (and its
* archive) or an unreadable archive is set aside first; a readable draft is replaced as
* before. False when something could not be set aside, or could not even be read.
*/
function releaseUnreadSession(
index: SheetIndex,
persistence: ReportPersistence,
archives: ArchivePersistence,
): boolean {
const draft = persistence.loadText()
const archiveText = archives.loadText()
if (draft === null) return restoreOrphanArchive(archiveText) === null
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return false
return quarantineSession(draft, archiveText)
}
if (!outcome.value.archiveRejected || archiveText === null) return true
return quarantine('archive', archiveText, ARCHIVE_KEY)
}
export function createReportStore(
persistence: ReportPersistence,
archives: ArchivePersistence,
@@ -175,12 +270,19 @@ export function createReportStore(
return { ...patch, archive }
}
/** A new session may start: either one is open (its texts are this store's), or none is left unread. */
const mayStartSession = (index: SheetIndex) =>
store.getState().report !== null ||
releaseUnreadSession(index, persistence, archives)
const store = create<ReportStore>((set, get) => ({
report: null,
archive: null,
activeObservationIndex: 0,
saveFailed: false,
initReport: (draft, sheet) => {
initReport: (draft, sheet, index) => {
if (!mayStartSession(index)) return HELD
const outcome = reportOps.newReport({
draft,
sheet,
@@ -193,17 +295,25 @@ export function createReportStore(
return OK
},
hydrateImport: ({ report, archive }) =>
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
hydrateImport: ({ report, archive }, index) => {
if (!mayStartSession(index)) return HELD
set(withArchive({ report, activeObservationIndex: 0 }, archive))
return OK
},
restoreDraft: (index) => {
restoreDraft: (index, options = {}) => {
if (get().report) return null
const restored = restore(index, persistence, archives)
const restored = restore(index, persistence, archives, options)
if (!restored) return null
if (restored.patch) set(restored.patch)
return restored.result
},
discardSessionText: (text) => {
if (get().report) return
removeSessionText(text)
},
addObservation: () =>
applyCore(
set,
@@ -265,10 +375,18 @@ export function createReportStore(
delete rest.nextAppointment
return { report: next ? { ...rest, nextAppointment: next } : rest }
}),
reset: () =>
set(withArchive({ report: null, activeObservationIndex: 0 }, null)),
// Ends the open session only: with none open, the tab's texts are not this store's.
reset: () => {
if (!get().report) return
set(withArchive({ report: null, activeObservationIndex: 0 }, null))
},
}))
store.subscribe((state) => persistence.save(state.report))
// The mirror follows the report only: an unrelated change never writes or removes the draft.
store.subscribe((state, prev) => {
if (state.report === prev.report) return
const failed = !persistence.save(state.report)
if (failed !== state.saveFailed) store.setState({ saveFailed: failed })
})
return store
}
+3 -1
View File
@@ -86,6 +86,7 @@ describe('drafts written through the core', () => {
nextAppointment: { kind: 'period', text: 'dans 3 semaines' },
},
sheet.sheet.ref,
sheet,
)
await expectN1ReadsTheDraft()
})
@@ -102,6 +103,7 @@ describe('drafts written through the core', () => {
recommendations: '',
},
sheet.sheet.ref,
sheet,
)
const apply = (obs: ReturnType<typeof current>) =>
useReportStore.getState().updateObservation(0, obs)
@@ -164,7 +166,7 @@ describe('drafts written through the core', () => {
)
useReportStore
.getState()
.hydrateImport({ report: rebase.report, archive: read.archive })
.hydrateImport({ report: rebase.report, archive: read.archive }, sheet)
await expectN1ReadsTheDraft()
const archive: unknown = JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!)
expect(ReportArchiveEnvelopeSchema.safeParse(archive).success).toBe(true)
@@ -45,7 +45,7 @@ beforeEach(() => {
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null })
.hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
exportMock.mockReset()
downloads.length = 0
URL.createObjectURL = vi.fn(() => 'blob:faunosteo-test')
@@ -56,7 +56,7 @@ beforeEach(() => {
],
}),
archive: null,
})
}, sheet)
})
afterEach(() => {
cleanup()
@@ -0,0 +1,212 @@
/**
* R2 maintenance B, interface (owner choice 2026-10-14): a session text that
* could not be set aside shows the resolution panel in the editor (copy to
* download, deletion or replacement only after a confirmation, retry); a new
* report started from /new is refused and sends the practitioner there; a
* refused draft write shows the storage-full banner.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { cleanup, 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 NewReportRoute from '@/app/routes/NewReportRoute'
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 { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
const UNREADABLE = JSON.stringify({ version: 7 })
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
saveFailed: false,
})
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())
})
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
function quarantineFull() {
const setItem = sessionStorage.setItem.bind(sessionStorage)
vi.spyOn(sessionStorage, 'setItem').mockImplementation((key, value) => {
if (key.startsWith('osteo:quarantine:')) {
throw new DOMException('full', 'QuotaExceededError')
}
setItem(key, value)
})
}
function mount(path: '/editor' | '/new') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/" element={<p data-testid="home-route" />} />
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<EditorRoute />} />
</Routes>
</MemoryRouter>,
)
}
describe('the resolution panel', () => {
it('lists the held draft, deletes it only after the confirmation, then leaves', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
mount('/editor')
await screen.findByText(fr['session.held.notice']!)
expect(screen.getByTestId('held-draft')).toHaveTextContent(
fr['session.held.draft_unreadable']!.replace('{size}', '1 Ko'),
)
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
const dialog = screen.getByRole('dialog')
expect(dialog).toHaveTextContent(fr['session.held.discard_body']!)
await user.click(screen.getByRole('button', { name: fr['common.cancel'] }))
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(UNREADABLE)
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
await user.click(
screen.getByRole('button', { name: fr['session.held.discard_confirm'] }),
)
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
await screen.findByTestId('home-route')
})
it('downloads the stored text verbatim', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
const blobs: Blob[] = []
URL.createObjectURL = vi.fn((blob: Blob) => {
blobs.push(blob)
return 'blob:held'
})
URL.revokeObjectURL = vi.fn()
const clicks = vi
.spyOn(HTMLAnchorElement.prototype, 'click')
.mockImplementation(() => undefined)
mount('/editor')
await user.click(
await screen.findByRole('button', { name: fr['session.held.download'] }),
)
expect(clicks).toHaveBeenCalledOnce()
expect(await blobs[0]!.text()).toBe(UNREADABLE)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(UNREADABLE)
})
it('opens the adapted draft only after the replacement is confirmed', async () => {
const user = userEvent.setup()
const stale = JSON.stringify(
minimalReport(sheet, {
conclusion: 'work in progress',
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
sessionStorage.setItem(DRAFT_KEY, stale)
quarantineFull()
mount('/editor')
await user.click(
await screen.findByRole('button', { name: fr['session.held.open_adapted'] }),
)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(stale)
await user.click(
screen.getByRole('button', { name: fr['session.held.open_confirm'] }),
)
await waitFor(() =>
expect(useReportStore.getState().report?.conclusion).toBe('work in progress'),
)
expect(screen.queryByText(fr['session.held.notice']!)).toBeNull()
})
it('retries the set-aside once the storage accepts it', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
mount('/editor')
await screen.findByText(fr['session.held.notice']!)
vi.restoreAllMocks()
await user.click(screen.getByRole('button', { name: fr['session.held.retry'] }))
await screen.findByTestId('home-route')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(UNREADABLE)
})
})
describe('a new report over a held draft', () => {
it('is refused and sends the practitioner to the resolution panel', async () => {
const user = userEvent.setup()
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
mount('/new')
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr. Dupont')
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Mistral')
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Jean Martin')
const submit = screen.getByRole('button', { name: fr['new_report.submit'] })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked']),
)
await screen.findByText(fr['session.held.notice']!)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(UNREADABLE)
expect(useReportStore.getState().report).toBeNull()
})
})
describe('the storage-full banner', () => {
it('shows while the draft mirror is refused and goes once a write succeeds', async () => {
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
mount('/editor')
await screen.findByTestId('sheet-status')
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
const setItem = sessionStorage.setItem.bind(sessionStorage)
const spy = vi
.spyOn(sessionStorage, 'setItem')
.mockImplementation((key, value) => {
if (key === DRAFT_KEY) throw new DOMException('full', 'QuotaExceededError')
setItem(key, value)
})
useReportStore.getState().setConclusion('lost on reload')
await screen.findByText(fr['editor.save_failed']!)
spy.mockRestore()
useReportStore.getState().setConclusion('saved')
await waitFor(() =>
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull(),
)
})
})
@@ -88,14 +88,14 @@ describe('store actions on a failing core', () => {
expect(s.addObservation()).toEqual({ ok: false })
expect(s.moveObservationUp(1)).toEqual({ ok: false })
expect(s.removeObservation(0)).toEqual({ ok: false })
expect(s.initReport(draft(), sheet.sheet.ref)).toEqual({ ok: false })
expect(s.initReport(draft(), sheet.sheet.ref, sheet)).toEqual({ ok: false })
expect(useReportStore.getState().report).toBe(report)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
})
it('answer { ok: true } on the live core', () => {
const s = useReportStore.getState()
expect(s.initReport(draft(), sheet.sheet.ref)).toEqual({ ok: true })
expect(s.initReport(draft(), sheet.sheet.ref, sheet)).toEqual({ ok: true })
expect(s.addObservation()).toEqual({ ok: true })
expect(useReportStore.getState().report!.observations).toHaveLength(2)
})
@@ -0,0 +1,309 @@
/**
* R2 maintenance B (owner rule 2026-10-14): no session text is removed or
* overwritten implicitly when a save or a quarantine fails. A text whose
* safety copy fails stays where it is (`held`), nothing is opened over it,
* and every later action that would replace it (new report, import, reset,
* an unrelated store change) leaves it alone until the practitioner decides.
* Covers the quota errors, the refused writes, an occupied quarantine slot,
* corrupted texts and the later overwriting actions.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import { useReportStore } from '@/state/reportStore'
import { ARCHIVE_KEY, DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { archiveEnvelope, loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
saveFailed: false,
})
sessionStorage.clear()
})
afterEach(() => vi.restoreAllMocks())
const store = () => useReportStore.getState()
const UNREADABLE = JSON.stringify({ version: 7 })
const newDraft = () => ({
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
})
/** The storage refuses writes to the keys `refused` matches, as a full quota does. */
function refuseWrites(refused: (key: string) => boolean) {
const setItem = sessionStorage.setItem.bind(sessionStorage)
vi.spyOn(sessionStorage, 'setItem').mockImplementation((key, value) => {
if (refused(key)) throw new DOMException('full', 'QuotaExceededError')
setItem(key, value)
})
}
const quarantineFull = () =>
refuseWrites((key) => key.startsWith('osteo:quarantine:'))
/** Every session key and its value: what must not move. */
function snapshotStorage(): Record<string, string | null> {
const keys = [DRAFT_KEY, ARCHIVE_KEY, ...Object.values(QUARANTINE_KEYS)]
return Object.fromEntries(keys.map((k) => [k, sessionStorage.getItem(k)]))
}
/** The editor's sequence for a draft it cannot set aside, then the later actions. */
function expectEveryLaterActionRefused(before: Record<string, string | null>) {
expect(store().initReport(newDraft(), sheet.sheet.ref, sheet)).toEqual({
ok: false,
reason: 'held',
})
const report = minimalReport(sheet)
expect(
store().hydrateImport({ report, archive: archiveEnvelope(sheet, report) }, sheet),
).toEqual({ ok: false, reason: 'held' })
store().reset()
store().setActiveObservation(3)
store().setConclusion('x')
expect(store().report).toBeNull()
expect(snapshotStorage()).toEqual(before)
}
describe('an unreadable draft that cannot be set aside', () => {
it('is held verbatim when the quota refuses the quarantine write', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toEqual({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable', bytes: UNREADABLE.length }],
})
expectEveryLaterActionRefused(before)
})
it('never replaces an earlier text already in its quarantine slot', () => {
sessionStorage.setItem(QUARANTINE_KEYS.draft, '{"earlier":true}')
sessionStorage.setItem(DRAFT_KEY, '{not json')
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable' }],
})
expectEveryLaterActionRefused(before)
})
it('is set aside when the slot already holds the same text (idempotent)', () => {
sessionStorage.setItem(QUARANTINE_KEYS.draft, UNREADABLE)
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
expect(store().restoreDraft(sheet)).toEqual({ kind: 'quarantined' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
})
it('keeps a lone surrogate (L1) text byte for byte', () => {
const raw = JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))
sessionStorage.setItem(DRAFT_KEY, raw)
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({ kind: 'held' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
})
})
describe('an unreadable draft and the archive beside it', () => {
it('go to quarantine together, so no later session removes the archive', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
sessionStorage.setItem(ARCHIVE_KEY, '{"archive":1}')
expect(store().restoreDraft(sheet)).toEqual({ kind: 'quarantined' })
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(UNREADABLE)
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{"archive":1}')
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
})
it('both stay in place, the draft copy undone, when the archive copy fails', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
sessionStorage.setItem(ARCHIVE_KEY, '{"archive":1}')
refuseWrites((key) => key === QUARANTINE_KEYS.archive)
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [
{ text: 'draft', reason: 'unreadable' },
{ text: 'archive', reason: 'companion' },
],
})
expect(snapshotStorage()).toEqual(before)
expectEveryLaterActionRefused(before)
})
})
describe('an unreadable archive beside a readable draft', () => {
it('is held, and the draft is not opened over it', () => {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
quarantineFull()
const before = snapshotStorage()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'archive', reason: 'unreadable' }],
})
expectEveryLaterActionRefused(before)
})
it('once deleted on request, lets the draft open', () => {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({ kind: 'held' })
store().discardSessionText('archive')
expect(sessionStorage.getItem(DRAFT_KEY)).not.toBeNull()
expect(store().restoreDraft(sheet)).toMatchObject({ kind: 'restored' })
})
})
describe('an archive with no draft beside it', () => {
it('is set aside, or held when that fails', () => {
sessionStorage.setItem(ARCHIVE_KEY, '{"orphan":1}')
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'archive', reason: 'companion' }],
})
vi.restoreAllMocks()
expect(store().restoreDraft(sheet)).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{"orphan":1}')
})
})
describe('a draft rebased with unresolved items whose original cannot be kept', () => {
const stale = () =>
JSON.stringify(
minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
it('is held unrebased: the mirror never overwrites the original', () => {
const raw = stale()
sessionStorage.setItem(DRAFT_KEY, raw)
quarantineFull()
expect(store().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'draft', reason: 'pre_rebase' }],
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
expect(store().report).toBeNull()
})
it('opens the adapted version only on the confirmed replacement', () => {
const raw = stale()
sessionStorage.setItem(DRAFT_KEY, raw)
quarantineFull()
expect(store().restoreDraft(sheet, { replaceOriginal: true })).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 1 },
})
expect(store().report).not.toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).not.toBe(raw)
})
})
describe('a new session over texts this page never read (after a reload)', () => {
it('sets an unreadable draft and its archive aside before starting', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
sessionStorage.setItem(ARCHIVE_KEY, '{"archive":1}')
expect(store().initReport(newDraft(), sheet.sheet.ref, sheet)).toEqual({ ok: true })
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(UNREADABLE)
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{"archive":1}')
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
})
it('is refused, nothing touched, when that set-aside fails', () => {
sessionStorage.setItem(DRAFT_KEY, UNREADABLE)
quarantineFull()
const before = snapshotStorage()
expectEveryLaterActionRefused(before)
})
it('sets an unreadable archive beside a readable draft aside before an import', () => {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
const report = minimalReport(sheet, { conclusion: 'imported' })
expect(store().hydrateImport({ report, archive: null }, sheet)).toEqual({ ok: true })
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{not json')
})
it('replaces a readable draft as before (explicit new report)', () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: 'previous' })),
)
expect(store().initReport(newDraft(), sheet.sheet.ref, sheet)).toEqual({ ok: true })
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).conclusion).toBe('')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
it('is refused when the core cannot read the draft at all', () => {
const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft)
const broken = {
...sheet,
ops: { restoreDraft: () => ({ ok: false, kind: 'core_unavailable' }) },
} as unknown as SheetIndex
expect(store().initReport(newDraft(), sheet.sheet.ref, broken)).toEqual({
ok: false,
reason: 'held',
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
})
})
describe('the draft mirror', () => {
it('reports a refused write and keeps the previous text in place', () => {
store().initReport(newDraft(), sheet.sheet.ref, sheet)
const saved = sessionStorage.getItem(DRAFT_KEY)
refuseWrites((key) => key === DRAFT_KEY)
store().setConclusion('not saved')
expect(store().saveFailed).toBe(true)
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(saved)
vi.restoreAllMocks()
store().setConclusion('saved again')
expect(store().saveFailed).toBe(false)
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).conclusion).toBe('saved again')
})
it('is never written or removed by a change that leaves the report alone', () => {
sessionStorage.setItem(DRAFT_KEY, '{"unread":true}')
store().setActiveObservation(2)
useReportStore.setState({ archive: null })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe('{"unread":true}')
})
it('a deletion request is ignored while a report is open', () => {
store().initReport(newDraft(), sheet.sheet.ref, sheet)
store().discardSessionText('draft')
expect(sessionStorage.getItem(DRAFT_KEY)).not.toBeNull()
})
})
+4 -1
View File
@@ -81,7 +81,10 @@ describe('an unreadable draft', () => {
setItem(key, value)
})
// Not announced as set aside: the editor stays put instead of leaving for Home.
expect(restore()).toEqual({ kind: 'unreadable_kept' })
expect(restore()).toEqual({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable', bytes: raw.length }],
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(raw)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
+23 -21
View File
@@ -51,7 +51,7 @@ const draft = () => ({
describe('initReport', () => {
it('stamps version 3, id, createdAt, the sheet ref and one empty observation', () => {
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet)
const report = useReportStore.getState().report!
expect(report.version).toBe(3)
expect(report.id).toBeTruthy()
@@ -66,7 +66,7 @@ describe('initReport', () => {
describe('observation actions', () => {
it('adds, updates, moves and removes observations, keeping the active index sane', () => {
const s = useReportStore.getState()
s.initReport(draft(), sheet.sheet.ref)
s.initReport(draft(), sheet.sheet.ref, sheet)
s.addObservation()
expect(useReportStore.getState().report!.observations).toHaveLength(2)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
@@ -91,7 +91,7 @@ describe('observation actions', () => {
it('setters replace identity, conclusion and appointment; nextAppointment can be cleared', () => {
const s = useReportStore.getState()
s.initReport(draft(), sheet.sheet.ref)
s.initReport(draft(), sheet.sheet.ref, sheet)
s.setPractitioner({ name: 'Dr. X' })
s.setAnimal({ speciesId: 'equine', name: 'Y' })
s.setOwner({ name: 'Z' })
@@ -124,7 +124,7 @@ describe('observation actions', () => {
describe('sessionStorage mirror and restore', () => {
it('mirrors every change under osteo:draft and removes it on reset', () => {
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet)
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
useReportStore.getState().reset()
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
@@ -154,15 +154,17 @@ describe('sessionStorage mirror and restore', () => {
kind: 'quarantined',
})
expect(useReportStore.getState().report).toBeNull()
// R2 maintenance B: the slot already holds the first text, which is never replaced.
sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ version: 1 }))
expect(useReportStore.getState().restoreDraft(sheet)).toEqual({
kind: 'quarantined',
expect(useReportStore.getState().restoreDraft(sheet)).toMatchObject({
kind: 'held',
held: [{ text: 'draft', reason: 'unreadable' }],
})
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(
JSON.stringify({ version: 1 }),
)
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe('{not json')
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(JSON.stringify({ version: 1 }))
useReportStore.getState().discardSessionText('draft')
useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet)
const before = useReportStore.getState().report
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
useReportStore.getState().restoreDraft(sheet)
@@ -172,10 +174,10 @@ describe('sessionStorage mirror and restore', () => {
it('createReportStore accepts another persistence adapter', () => {
const saved: unknown[] = []
const store = createReportStore(
{ loadText: () => null, save: (r) => saved.push(r) },
{ loadText: () => null, save: () => undefined },
{ loadText: () => null, save: (r) => saved.push(r) > 0 },
{ loadText: () => null, save: () => true },
)
store.getState().initReport(draft(), sheet.sheet.ref)
store.getState().initReport(draft(), sheet.sheet.ref, sheet)
expect(saved.at(-1)).toMatchObject({ version: 3 })
})
})
@@ -200,7 +202,7 @@ describe('archive of an imported Step 6 PDF', () => {
it('hydrateImport keeps the archive and mirrors it under osteo:archive', () => {
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
useReportStore.getState().hydrateImport({ report, archive })
useReportStore.getState().hydrateImport({ report, archive }, sheet)
expect(useReportStore.getState().archive).toEqual(archive)
expect(JSON.parse(sessionStorage.getItem(ARCHIVE_KEY)!).report.id).toBe(
report.id,
@@ -211,12 +213,12 @@ describe('archive of an imported Step 6 PDF', () => {
it('the archive is written at the session edges only, never on an edit', () => {
const archiveSaves: unknown[] = []
const store = createReportStore(
{ loadText: () => null, save: () => undefined },
{ loadText: () => null, save: (a) => archiveSaves.push(a) },
{ loadText: () => null, save: () => true },
{ loadText: () => null, save: (a) => archiveSaves.push(a) > 0 },
)
const report = minimalReport(sheet)
const archive = archiveEnvelope(sheet, report)
store.getState().hydrateImport({ report, archive })
store.getState().hydrateImport({ report, archive }, sheet)
expect(archiveSaves).toEqual([archive])
store.getState().setConclusion('edited')
store.getState().addObservation()
@@ -230,7 +232,7 @@ describe('archive of an imported Step 6 PDF', () => {
it('restoreDraft brings the archive back with the draft', () => {
const report = minimalReport(sheet, { conclusion: 'kept' })
const archive = archiveEnvelope(sheet, report)
useReportStore.getState().hydrateImport({ report, archive })
useReportStore.getState().hydrateImport({ report, archive }, sheet)
// Emptying the state clears the draft mirror, not the archive mirror.
useReportStore.setState({ report: null, archive: null })
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
@@ -248,21 +250,21 @@ describe('archive of an imported Step 6 PDF', () => {
it.each([
[
'initReport',
() => useReportStore.getState().initReport(draft(), sheet.sheet.ref),
() => useReportStore.getState().initReport(draft(), sheet.sheet.ref, sheet),
],
[
'hydrateImport without an archive',
() =>
useReportStore
.getState()
.hydrateImport({ report: minimalReport(sheet), archive: null }),
.hydrateImport({ report: minimalReport(sheet), archive: null }, sheet),
],
['reset', () => useReportStore.getState().reset()],
])('%s clears the archive and removes its mirror', (_name, act) => {
const report = minimalReport(sheet)
useReportStore
.getState()
.hydrateImport({ report, archive: archiveEnvelope(sheet, report) })
.hydrateImport({ report, archive: archiveEnvelope(sheet, report) }, sheet)
act()
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
+26 -4
View File
@@ -621,7 +621,23 @@ application itself builds.
3. An unreadable draft or archive is set aside under `osteo:quarantine:*`
with the `editor.draft_quarantined` alert, instead of being dropped
silently; a draft rebased with unresolved items keeps its raw text under
`osteo:quarantine:draft-pre-rebase`.
`osteo:quarantine:draft-pre-rebase`. An unreadable draft goes there with
the archive kept beside it, both or neither. A slot already holding
another text is never replaced. Owner rule of 2026-10-14 (maintenance B):
no session text is removed or overwritten implicitly when a save or a
set-aside fails. Such a text stays in place and is held: nothing is
opened over it (`RestoreResult` `held`: an unreadable draft, its
companion archive, an unreadable archive, or the original of a draft to
rebase), and the editor shows the resolution panel (download an exact
copy, delete permanently or open the adapted version after a
confirmation, retry). A new report or an import refuses to start
(`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
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.
4. A core that cannot load leaves the editor on the degraded notice
(before R2 a failed sheet chunk left it on "loading").
5. Home and `/new` no longer load the sheet into memory on mount.
@@ -633,9 +649,9 @@ application itself builds.
8. The publish gate throws `SheetPublishError` with closed kinds
(`invalid_shape`, `not_publishable` with the same message as before,
`validator_unavailable`), never a raw ZodError.
9. An unreadable draft that cannot be set aside (storage full) keeps the
editor on the degraded notice, whose text speaks of the engine: wording to
revisit if the case matters.
9. Superseded by item 3 (maintenance B, 2026-10-14): an unreadable draft
that cannot be set aside shows the resolution panel, no longer the
engine notice.
### 8.8 Residual risks
@@ -653,6 +669,12 @@ application itself builds.
(practitioner, owner and animal data) until the tab closes, the same
exposure as `osteo:draft` itself (sessionStorage, tab and origin scoped);
nothing clears them on a new report, by design (they exist to survive it).
They have no interface yet: the practitioner cannot see or download a
set-aside text, and it disappears when the tab closes (owner decision
2026-10-14: follow-up, not part of the maintenance fix).
- "New report" from Home replaces the tab's readable draft without asking,
as before R2 (a single draft per tab, the PDF is the saved copy); the
maintenance fix only guards texts that are unreadable or held.
- Base images by tag, the new `rust:1.99.0-bookworm` included (digest pinning
is the Step 27 follow-up of R0).
- The documented CSP refuses the footer's external credit logo