Files
faunosteo/apps/app/tests/unit/state.quarantine.test.ts
bchanot 9bd9acaf58 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.
2026-10-17 12:58:57 +02:00

288 lines
10 KiB
TypeScript

/**
* R2 plan P12 (rev 2): a draft or an archive the running build cannot read is
* set aside under a quarantine key, never dropped; only the content failures
* of the core (`invalid`, `unsupported_version`, `lone_surrogate`: L1, a text
* the core would alter) quarantine, any other failure
* leaves both keys where they were; the source key is removed only once the
* quarantine write succeeded; a draft rebased with unresolved items keeps its
* raw pre-rebase text.
*/
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 { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
useReportStore.getState().clearTrapped()
})
afterEach(() => vi.restoreAllMocks())
const restore = () => useReportStore.getState().restoreDraft(sheet)
/** A sheet whose core answers `kind` to every draft restore. */
function sheetFailingWith(kind: string): SheetIndex {
return {
...sheet,
ops: { restoreDraft: () => ({ ok: false, kind }) },
} as unknown as SheetIndex
}
describe('an unreadable draft', () => {
it.each([
['a known version that does not parse', JSON.stringify({ version: 3 })],
['an unknown version', JSON.stringify({ version: 7 })],
['text that is not JSON', '{not json'],
])('%s is moved to its quarantine key', (_label, raw) => {
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toEqual({ kind: 'quarantined' })
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBe(raw)
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('with a lone surrogate (L1) is moved verbatim, the surrogate kept', () => {
const raw = JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))
expect(raw).toContain('\\ud800')
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toEqual({ kind: 'quarantined' })
const kept = sessionStorage.getItem(QUARANTINE_KEYS.draft)
expect(kept).toBe(raw)
expect(JSON.parse(kept!).conclusion).toBe('a\ud800b')
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('stays where it is when the quarantine write fails (storage full)', () => {
const raw = JSON.stringify({ version: 7 })
sessionStorage.setItem(DRAFT_KEY, raw)
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)
})
// Not announced as set aside: the editor stays put instead of leaving for Home.
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()
})
})
describe('a core failure while reading the draft', () => {
it.each(['core_unavailable', 'rebase_failed'])(
'%s leaves the draft and the archive untouched',
(kind) => {
const draft = JSON.stringify(minimalReport(sheet))
sessionStorage.setItem(DRAFT_KEY, draft)
sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}')
const result = useReportStore
.getState()
.restoreDraft(sheetFailingWith(kind))
expect(result).toEqual({ kind: 'core_unavailable' })
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBe('{"kept":true}')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
},
)
})
describe('a core trap while reading the draft (internal)', () => {
/** A sheet whose draft restore traps (`internal`), counting the reads. */
function trappingSheet() {
const calls = { n: 0 }
const index = {
...sheet,
ops: {
restoreDraft: () => {
calls.n += 1
return { ok: false, kind: 'internal' }
},
},
} as unknown as SheetIndex
return { index, calls }
}
const draftText = () => JSON.stringify(minimalReport(sheet))
function seed() {
const draft = draftText()
sessionStorage.setItem(DRAFT_KEY, draft)
sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}')
return draft
}
it('holds the draft (engine_failure) and its archive, both untouched', () => {
const draft = seed()
const { index } = trappingSheet()
const result = useReportStore.getState().restoreDraft(index)
expect(result).toMatchObject({
kind: 'held',
held: [
{ text: 'draft', reason: 'engine_failure' },
{ text: 'archive', reason: 'companion' },
],
})
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBe('{"kept":true}')
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(useReportStore.getState().report).toBeNull()
})
it('never reads the same pair again, except on the explicit retry', () => {
seed()
const { index, calls } = trappingSheet()
const store = useReportStore.getState()
store.restoreDraft(index)
expect(store.restoreDraft(index)).toMatchObject({ kind: 'held' })
expect(calls.n).toBe(1)
store.restoreDraft(index, { retryTrapped: true })
expect(calls.n).toBe(2)
})
it('answers a new session HELD with the engine cause, without a second read', () => {
seed()
const { index, calls } = trappingSheet()
const store = useReportStore.getState()
store.restoreDraft(index)
const draft = { practitioner: { name: 'p' } } as never
expect(store.initReport(draft, sheet.sheet.ref, index)).toEqual({
ok: false,
reason: 'held',
engine: true,
})
expect(store.hydrateImport({ report: minimalReport(sheet), archive: null }, index)).toEqual({
ok: false,
reason: 'held',
engine: true,
})
expect(calls.n).toBe(1)
})
it('reads again once the stored pair changed, or after a discard', () => {
seed()
const { index, calls } = trappingSheet()
const store = useReportStore.getState()
store.restoreDraft(index)
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet, { conclusion: 'x' })))
store.restoreDraft(index)
expect(calls.n).toBe(2)
store.discardSessionText('archive')
store.restoreDraft(index)
expect(calls.n).toBe(3)
})
})
describe('an unreadable archive beside a readable draft', () => {
it('goes to its quarantine key while the draft restores', () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: 'kept' })),
)
sessionStorage.setItem(ARCHIVE_KEY, '{not json')
expect(restore()).toMatchObject({ kind: 'restored' })
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(useReportStore.getState().archive).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe('{not json')
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBeNull()
})
})
describe('a lone surrogate (L1) beside a readable draft or in the open report', () => {
it('sets the archive aside verbatim while the draft restores', () => {
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: 'kept' })),
)
const archive = JSON.stringify({ format: 'x', note: '\udc00' })
sessionStorage.setItem(ARCHIVE_KEY, archive)
expect(restore()).toMatchObject({ kind: 'restored' })
expect(useReportStore.getState().report?.conclusion).toBe('kept')
expect(sessionStorage.getItem(QUARANTINE_KEYS.archive)).toBe(archive)
})
it('refuses a core action and leaves the report as it was', () => {
const report = minimalReport(sheet, { conclusion: 'a\ud800b' })
useReportStore.setState({ report })
expect(useReportStore.getState().addObservation()).toEqual({ ok: false })
expect(useReportStore.getState().report).toBe(report)
expect(useReportStore.getState().report?.conclusion).toBe('a\ud800b')
})
it('leaves normal text with pairs and literal backslashes unchanged', () => {
const text = 'é 😀 \\ud800 \ufffd'
sessionStorage.setItem(
DRAFT_KEY,
JSON.stringify(minimalReport(sheet, { conclusion: text })),
)
expect(restore()).toMatchObject({ kind: 'restored' })
expect(useReportStore.getState().report?.conclusion).toBe(text)
expect(useReportStore.getState().addObservation()).toEqual({ ok: true })
expect(useReportStore.getState().report?.conclusion).toBe(text)
})
})
describe('a draft rebased onto the loaded sheet', () => {
const OTHER_SHA = 'c'.repeat(64)
it('keeps its raw text when the rebase flagged items', () => {
const stale = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
const raw = JSON.stringify(stale)
sessionStorage.setItem(DRAFT_KEY, raw)
expect(restore()).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 1 },
})
expect(sessionStorage.getItem(QUARANTINE_KEYS.draftPreRebase)).toBe(raw)
// The mirror now holds the rebased draft.
expect(
JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).sheet.documentSha256,
).toBe(sheet.sheet.ref.documentSha256)
})
it('keeps nothing aside when the rebase resolved everything', () => {
const moved = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: OTHER_SHA },
})
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(moved))
expect(restore()).toMatchObject({
kind: 'restored',
rebase: { rebased: true, unresolvedZones: 0, unresolvedFindings: 0 },
})
expect(sessionStorage.getItem(QUARANTINE_KEYS.draftPreRebase)).toBeNull()
})
})