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:
1 parent
9464651140
commit
9bd9acaf58
22 files changed
+1090
-68
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { CoreRuntime } from '@faunosteo/core-wasm'
|
||||
import { nodeCoreRuntime } from '@faunosteo/core-wasm/node'
|
||||
import { CoreRuntime, type CoreSource } from '@faunosteo/core-wasm'
|
||||
import { nodeCoreRuntime, nodeCoreSource } from '@faunosteo/core-wasm/node'
|
||||
|
||||
/** A loaded runtime on the shipped build (the package's Node source). */
|
||||
export function testCoreRuntime(): Promise<CoreRuntime> {
|
||||
@@ -26,3 +26,39 @@ export function unavailableCoreRuntime(): CoreRuntime {
|
||||
importGlue: () => Promise.reject(new TypeError('blocked')),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* A real runtime on the shipped module whose `SheetHandle.call` throws a
|
||||
* `WebAssembly.RuntimeError` (as an out-of-memory trap does) for `draft.restore`
|
||||
* calls whose input contains `marker`; `traps.count` counts them. The runtime
|
||||
* poisons and recovers exactly as in production (three recoveries).
|
||||
*/
|
||||
export async function trappingCoreRuntime(marker: string) {
|
||||
const source = nodeCoreSource('pkg')
|
||||
const traps = { count: 0 }
|
||||
const wrapped: CoreSource = {
|
||||
compile: () => source.compile(),
|
||||
importGlue: async (instance) => {
|
||||
const glue = await source.importGlue(instance)
|
||||
const Real = glue.SheetHandle
|
||||
class Trapping extends Real {
|
||||
call(op: string, input: string): string {
|
||||
if (op === 'draft.restore' && input.includes(marker)) {
|
||||
traps.count += 1
|
||||
throw new WebAssembly.RuntimeError('unreachable')
|
||||
}
|
||||
return super.call(op, input)
|
||||
}
|
||||
}
|
||||
return {
|
||||
default: glue.default,
|
||||
core_version: glue.core_version,
|
||||
call: glue.call,
|
||||
SheetHandle: Trapping,
|
||||
}
|
||||
},
|
||||
}
|
||||
const runtime = new CoreRuntime(wrapped)
|
||||
if (!(await runtime.ready())) throw new Error('trapping runtime failed to load')
|
||||
return { runtime, traps }
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The beforeunload guard is app-wide (R3 final checks): prevented exactly while the report
|
||||
* is unsaved, on any page; App mounts it, the editor no longer registers its own.
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react'
|
||||
import App from '@/app/App'
|
||||
import { useUnsavedGuard } from '@/app/useUnsavedGuard'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||
|
||||
let sheet: SheetIndex
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
})
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear()
|
||||
useReportStore.setState({ report: null, archive: null, saveFailed: false })
|
||||
useReportStore.getState().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
useReportStore.setState({ report: null, saveFailed: false })
|
||||
})
|
||||
|
||||
const leave = () => {
|
||||
const event = new Event('beforeunload', { cancelable: true })
|
||||
window.dispatchEvent(event)
|
||||
return event.defaultPrevented
|
||||
}
|
||||
|
||||
function fillStorage() {
|
||||
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('full', 'QuotaExceededError')
|
||||
})
|
||||
act(() => useReportStore.getState().setConclusion('edited after the quota'))
|
||||
expect(useReportStore.getState().saveFailed).toBe(true)
|
||||
}
|
||||
|
||||
describe('useUnsavedGuard', () => {
|
||||
it('prevents the unload exactly while the report is unsaved', async () => {
|
||||
renderHook(() => useUnsavedGuard())
|
||||
expect(leave()).toBe(false)
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
vi.restoreAllMocks()
|
||||
act(() => useReportStore.getState().setConclusion('saved again'))
|
||||
await waitFor(() => expect(leave()).toBe(false))
|
||||
})
|
||||
|
||||
it('leaves the listener off once the hook unmounts', async () => {
|
||||
const { unmount } = renderHook(() => useUnsavedGuard())
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
unmount()
|
||||
expect(leave()).toBe(false)
|
||||
})
|
||||
|
||||
it('is mounted by App, on a page that is not the editor', async () => {
|
||||
window.history.pushState({}, '', '/')
|
||||
render(<App />)
|
||||
expect(leave()).toBe(false)
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* The rescue copy (`JSON.stringify(report)`, the downloaded format) imported from Home:
|
||||
* routed by content from the first KiB, read by the core's draft restore, opened as the
|
||||
* original report; every refusal leaves the store and the tab's slots untouched.
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import HomeRoute from '@/app/routes/HomeRoute'
|
||||
import { MAX_ATTACHMENT_BYTES } from '@/pdf/import'
|
||||
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { buildGoldenReports, GOLDEN_REPORTS } from '../helpers/goldenReports'
|
||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||
|
||||
let sheet: SheetIndex
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
})
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
sessionStorage.clear()
|
||||
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
|
||||
useReportStore.getState().clearTrapped()
|
||||
vi.stubGlobal('alert', vi.fn())
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function pick(file: File) {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomeRoute />} />
|
||||
<Route path="/editor" element={<p data-testid="editor-route" />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
fireEvent.change(document.querySelector('input[type="file"]')!, {
|
||||
target: { files: [file] },
|
||||
})
|
||||
}
|
||||
|
||||
const copyFile = (text: string, name = 'faunosteo-brouillon.json') =>
|
||||
new File([text], name, { type: 'application/json' })
|
||||
|
||||
describe('opening a rescue copy', () => {
|
||||
it.each(GOLDEN_REPORTS)('reopens the %s report equal to the original', async (name) => {
|
||||
const { reports } = buildGoldenReports(sheet)
|
||||
await pick(copyFile(JSON.stringify(reports[name])))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report).toEqual(reports[name])
|
||||
expect(useReportStore.getState().archive).toBeNull()
|
||||
})
|
||||
|
||||
it('routes by content: no .json name, no type, leading blanks and a BOM', async () => {
|
||||
const report = minimalReport(sheet, { conclusion: 'sniffed' })
|
||||
const text = ` \n${JSON.stringify(report)}`
|
||||
await pick(new File([text], 'secours'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report).toEqual(report)
|
||||
})
|
||||
|
||||
it('announces a copy rebased on another sheet revision', async () => {
|
||||
const stale = minimalReport(sheet, {
|
||||
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
|
||||
observations: [
|
||||
{
|
||||
id: 'o',
|
||||
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
},
|
||||
],
|
||||
})
|
||||
await pick(copyFile(JSON.stringify(stale)))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(window.alert).toHaveBeenCalledWith(
|
||||
fr['editor.draft_rebased']!.replace('{count}', '1'),
|
||||
)
|
||||
})
|
||||
|
||||
it('still sends a PDF down the PDF path', async () => {
|
||||
await pick(new File(['%PDF-1.7 not really'], 'bilan.pdf', { type: 'application/pdf' }))
|
||||
await screen.findByText(fr['home.import.error_no_attachment']!)
|
||||
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('refusing a file', () => {
|
||||
const unreadable = JSON.stringify({ version: 7 })
|
||||
const refused: [string, () => File][] = [
|
||||
['invalid JSON', () => copyFile('{not json')],
|
||||
['an unsupported version', () => copyFile(JSON.stringify({ version: 1 }))],
|
||||
[
|
||||
'a lone surrogate',
|
||||
() => copyFile(JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' }))),
|
||||
],
|
||||
[
|
||||
'invalid UTF-8',
|
||||
() => new File([new Uint8Array([0x7b, 0xff, 0xfe, 0x7d])], 'copie.json'),
|
||||
],
|
||||
]
|
||||
|
||||
async function expectUntouched() {
|
||||
await screen.findByText(fr['home.import.error_invalid_copy']!)
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(unreadable)
|
||||
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
|
||||
expect(window.alert).not.toHaveBeenCalled()
|
||||
expect(screen.queryByTestId('editor-route')).toBeNull()
|
||||
}
|
||||
|
||||
it.each(refused)('%s: error line, nothing changed, nothing held', async (_label, make) => {
|
||||
sessionStorage.setItem(DRAFT_KEY, unreadable)
|
||||
await pick(make())
|
||||
await expectUntouched()
|
||||
})
|
||||
|
||||
it('an over-cap file is refused before any full read', async () => {
|
||||
sessionStorage.setItem(DRAFT_KEY, unreadable)
|
||||
const file = copyFile('{"version":3}')
|
||||
Object.defineProperty(file, 'size', { value: MAX_ATTACHMENT_BYTES + 1 })
|
||||
const read = vi.spyOn(file, 'arrayBuffer')
|
||||
await pick(file)
|
||||
await expectUntouched()
|
||||
expect(read).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['internal', 'rebase_failed'])(
|
||||
'the core kind %s takes the engine message path, not the copy message',
|
||||
async (kind) => {
|
||||
vi.spyOn(sheet.ops, 'restoreDraft').mockReturnValue({ ok: false, kind } as never)
|
||||
await pick(copyFile(JSON.stringify(minimalReport(sheet))))
|
||||
await screen.findByText(fr['home.import.error_core_unavailable']!)
|
||||
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -2,7 +2,7 @@
|
||||
* The engine stopped for good (three recoveries spent, owner decision 2026-10-15): the
|
||||
* stopped notice on every core page, its two variants (tab copy saved: reload; tab storage
|
||||
* full: download a copy), no retry anywhere, the editor's save banner with its copy button,
|
||||
* the beforeunload guard while the report is unsaved, and the stopped alerts.
|
||||
* and the stopped alerts (the beforeunload guard has its own hook test).
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
@@ -167,24 +167,6 @@ describe('EditorRoute', () => {
|
||||
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
|
||||
})
|
||||
|
||||
it('guards the page with beforeunload exactly while the report is unsaved', async () => {
|
||||
setStopped(false)
|
||||
mountEditor()
|
||||
await screen.findByTestId('sheet-status')
|
||||
const leave = () => {
|
||||
const event = new Event('beforeunload', { cancelable: true })
|
||||
window.dispatchEvent(event)
|
||||
return event.defaultPrevented
|
||||
}
|
||||
expect(leave()).toBe(false)
|
||||
fillStorage()
|
||||
await waitFor(() => expect(leave()).toBe(true))
|
||||
vi.restoreAllMocks()
|
||||
act(() => useReportStore.getState().setConclusion('saved again'))
|
||||
expect(useReportStore.getState().saveFailed).toBe(false)
|
||||
await waitFor(() => expect(leave()).toBe(false))
|
||||
})
|
||||
|
||||
it('says the stopped text when the export fails once the engine stopped', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
|
||||
@@ -244,6 +226,8 @@ describe('the stopped text on the Home import line and the New report alert', ()
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
// A report is in progress (beforeEach): replacing it is confirmed first.
|
||||
await user.click(await screen.findByRole('button', { name: fr['session.replace.confirm']! }))
|
||||
}
|
||||
|
||||
it('Home import: the engine error line says the stopped text', async () => {
|
||||
|
||||
@@ -177,6 +177,10 @@ describe('a new report over a held draft', () => {
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit'] })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
// A draft sits in the slot: replacing it is confirmed first.
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked']),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Replacing the bilan in progress (R3 final checks): New report and the Home file pick ask
|
||||
* first when a report is in memory or a draft sits in the slot (named, unloaded and
|
||||
* unsaved variants); Annuler changes nothing, Ouvrir goes back to the editor, Remplacer
|
||||
* proceeds; nothing in progress, no dialog.
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import HomeRoute from '@/app/routes/HomeRoute'
|
||||
import NewReportRoute from '@/app/routes/NewReportRoute'
|
||||
import { DRAFT_KEY } from '@/state/persistence'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||
|
||||
let sheet: SheetIndex
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
})
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
sessionStorage.clear()
|
||||
localStorage.clear()
|
||||
useReportStore.setState({
|
||||
report: null,
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
saveFailed: false,
|
||||
})
|
||||
useReportStore.getState().clearTrapped()
|
||||
vi.stubGlobal('alert', vi.fn())
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
useReportStore.setState({ report: null, saveFailed: false })
|
||||
})
|
||||
|
||||
const mount = (path: '/' | '/new') =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomeRoute />} />
|
||||
<Route path="/new" element={<NewReportRoute />} />
|
||||
<Route path="/editor" element={<p data-testid="editor-route" />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
const openReport = (animalName = 'Mistral') =>
|
||||
useReportStore.getState().hydrateImport(
|
||||
{ report: minimalReport(sheet, { animal: { speciesId: 'equine', name: animalName } }), archive: null },
|
||||
sheet,
|
||||
)
|
||||
|
||||
async function submitForm(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
|
||||
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
|
||||
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
}
|
||||
|
||||
const button = (key: string) => screen.getByRole('button', { name: fr[key]! })
|
||||
/** A button of the open dialog (the page behind has its own Annuler). */
|
||||
const dialogButton = (key: string) =>
|
||||
within(screen.getByRole('dialog')).getByRole('button', { name: fr[key]! })
|
||||
|
||||
describe('New report over a bilan in progress', () => {
|
||||
it('names the animal of the report in memory and replaces it on Remplacer', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(dialog).toHaveTextContent(fr['session.replace.body']!.replace('{animal}', 'Mistral'))
|
||||
expect(dialog).not.toHaveTextContent(fr['session.replace.unsaved']!)
|
||||
await user.click(button('session.replace.confirm'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report?.animal.name).toBe('Rex')
|
||||
})
|
||||
|
||||
it('renders an animal name with a replacement pattern literally', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport('Rex$&$1')
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent('Le bilan de Rex$&$1 sera')
|
||||
})
|
||||
|
||||
it('uses the unloaded text for a draft this page never opened', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!)
|
||||
})
|
||||
|
||||
it('adds the unsaved line and the copy button when the tab storage is full', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('full', 'QuotaExceededError')
|
||||
})
|
||||
act(() => useReportStore.getState().setConclusion('edited'))
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(dialog).toHaveTextContent(fr['session.replace.unsaved']!)
|
||||
expect(dialog).toHaveTextContent(fr['session.held.download']!)
|
||||
})
|
||||
|
||||
it('Annuler changes nothing and Ouvrir goes to the editor', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
const before = useReportStore.getState().report
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
await screen.findByRole('dialog')
|
||||
await user.click(dialogButton('common.cancel'))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
expect(useReportStore.getState().report).toBe(before)
|
||||
await user.click(button('new_report.submit'))
|
||||
await screen.findByRole('dialog')
|
||||
await user.click(button('session.replace.open'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(useReportStore.getState().report).toBe(before)
|
||||
})
|
||||
|
||||
it('asks nothing when no bilan is in progress', async () => {
|
||||
const user = userEvent.setup()
|
||||
mount('/new')
|
||||
await submitForm(user)
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(useReportStore.getState().report?.animal.name).toBe('Rex')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the Home file pick over a bilan in progress', () => {
|
||||
const pickButton = () => button('home.import.cta')
|
||||
const enabled = () => waitFor(() => expect(pickButton()).toBeEnabled())
|
||||
|
||||
it('asks first; Remplacer opens the picker inside the same click', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
mount('/')
|
||||
await enabled()
|
||||
await user.click(pickButton())
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent('Mistral')
|
||||
expect(click).not.toHaveBeenCalled()
|
||||
fireEvent.click(button('session.replace.confirm'))
|
||||
expect(click).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('Annuler never opens the picker; Ouvrir goes to the editor; the report stays', async () => {
|
||||
const user = userEvent.setup()
|
||||
openReport()
|
||||
const before = useReportStore.getState().report
|
||||
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
mount('/')
|
||||
await enabled()
|
||||
await user.click(pickButton())
|
||||
await user.click(dialogButton('common.cancel'))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
await user.click(pickButton())
|
||||
await user.click(button('session.replace.open'))
|
||||
await screen.findByTestId('editor-route')
|
||||
expect(click).not.toHaveBeenCalled()
|
||||
expect(useReportStore.getState().report).toBe(before)
|
||||
})
|
||||
|
||||
it('also asks for a draft only in the slot (unloaded text), nothing otherwise', async () => {
|
||||
const user = userEvent.setup()
|
||||
const click = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
mount('/')
|
||||
await enabled()
|
||||
await user.click(pickButton())
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(click).toHaveBeenCalledOnce()
|
||||
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
|
||||
await user.click(pickButton())
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent(fr['session.replace.body_unloaded']!)
|
||||
expect(click).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* A draft the engine traps on (R3 final checks): on a real poisoning runtime the editor
|
||||
* shows the resolution panel (engine_failure row, engine notice), never the reload screen
|
||||
* while the engine is not stopped; New report and Import answer the engine message then
|
||||
* open the panel; the trapping (draft, archive) pair is read once (one trap across mount,
|
||||
* New report, Import and remount); only the panel's Retry reads it again; a confirmed
|
||||
* discard removes the draft and clears the memory.
|
||||
*/
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import EditorRoute from '@/app/routes/EditorRoute'
|
||||
import HomeRoute from '@/app/routes/HomeRoute'
|
||||
import NewReportRoute from '@/app/routes/NewReportRoute'
|
||||
import { setCoreRuntime } from '@/core/runtime'
|
||||
import { bundledSheetProvider } from '@/sheets/provider'
|
||||
import { setSheetProvider } from '@/sheets/useSheet'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { testCoreRuntime, trappingCoreRuntime } from '../helpers/core'
|
||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||
|
||||
const MARKER = 'trap-me'
|
||||
let sheet: SheetIndex
|
||||
let draft: string
|
||||
let traps: { count: number }
|
||||
let engineStopped: () => boolean
|
||||
let engineReady: () => Promise<boolean>
|
||||
|
||||
beforeAll(async () => {
|
||||
sheet = await loadTestSheet()
|
||||
draft = JSON.stringify(minimalReport(sheet, { conclusion: MARKER }))
|
||||
})
|
||||
beforeEach(async () => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
sessionStorage.clear()
|
||||
localStorage.clear()
|
||||
sessionStorage.setItem('osteo:disclaimer-shown', '1')
|
||||
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
|
||||
vi.stubGlobal('alert', vi.fn())
|
||||
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
|
||||
useReportStore.getState().clearTrapped()
|
||||
const trapping = await trappingCoreRuntime(MARKER)
|
||||
traps = trapping.traps
|
||||
engineStopped = () => trapping.runtime.stopped
|
||||
engineReady = () => trapping.runtime.ready()
|
||||
setCoreRuntime(trapping.runtime)
|
||||
setSheetProvider(bundledSheetProvider)
|
||||
// After the reset (an empty store mirrors no draft): the tab as a reload finds it.
|
||||
sessionStorage.setItem(DRAFT_KEY, draft)
|
||||
})
|
||||
afterEach(async () => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
useReportStore.getState().clearTrapped()
|
||||
setCoreRuntime(await testCoreRuntime())
|
||||
setSheetProvider(bundledSheetProvider)
|
||||
})
|
||||
|
||||
const routes = (initial: string) =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={[initial]}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomeRoute />} />
|
||||
<Route path="/new" element={<NewReportRoute />} />
|
||||
<Route path="/editor" element={<EditorRoute />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
async function expectEnginePanel() {
|
||||
await screen.findByText(fr['session.held.notice_engine']!)
|
||||
expect(screen.getByTestId('held-draft')).toHaveTextContent(
|
||||
fr['session.held.draft_engine_failure']!.replace('{size}', /\d+ Ko/.exec(
|
||||
screen.getByTestId('held-draft').textContent ?? '',
|
||||
)![0]),
|
||||
)
|
||||
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
|
||||
}
|
||||
|
||||
async function submitNewReport(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
|
||||
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
|
||||
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
|
||||
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
|
||||
await waitFor(() => expect(submit).toBeEnabled())
|
||||
await user.click(submit)
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
|
||||
)
|
||||
}
|
||||
|
||||
async function pickCopy(user: ReturnType<typeof userEvent.setup>) {
|
||||
const pick = screen.getByRole('button', { name: fr['home.import.cta']! })
|
||||
await waitFor(() => expect(pick).toBeEnabled())
|
||||
await user.click(pick)
|
||||
vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
|
||||
)
|
||||
const copy = JSON.stringify(minimalReport(sheet, { id: 'other' }))
|
||||
fireEvent.change(document.querySelector('input[type="file"]')!, {
|
||||
target: { files: [new File([copy], 'copie.json', { type: 'application/json' })] },
|
||||
})
|
||||
}
|
||||
|
||||
describe('a draft the engine traps on', () => {
|
||||
it('opens the engine_failure panel, never the reload screen', async () => {
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
expect(traps.count).toBe(1)
|
||||
expect(engineStopped()).toBe(false)
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
})
|
||||
|
||||
it('is read once across mount, New report, Import and remount', async () => {
|
||||
const user = userEvent.setup()
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
cleanup()
|
||||
|
||||
routes('/new')
|
||||
await submitNewReport(user)
|
||||
await waitFor(() =>
|
||||
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
|
||||
)
|
||||
await expectEnginePanel()
|
||||
cleanup()
|
||||
|
||||
routes('/')
|
||||
await pickCopy(user)
|
||||
await waitFor(() =>
|
||||
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
|
||||
)
|
||||
await expectEnginePanel()
|
||||
cleanup()
|
||||
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
expect(traps.count).toBe(1)
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
|
||||
})
|
||||
|
||||
it('reads the pair again only on the panel Retry', async () => {
|
||||
const user = userEvent.setup()
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
// The instance that trapped is replaced in the background: retry on the fresh one.
|
||||
await engineReady()
|
||||
await user.click(screen.getByRole('button', { name: fr['session.held.retry'] }))
|
||||
await waitFor(() => expect(traps.count).toBe(2))
|
||||
await expectEnginePanel()
|
||||
})
|
||||
|
||||
it('removes only the draft after the confirmation and forgets the trap', async () => {
|
||||
const user = userEvent.setup()
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: fr['session.held.discard_confirm'] }),
|
||||
)
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
|
||||
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
|
||||
cleanup()
|
||||
await engineReady()
|
||||
// The memory is gone: the same text, stored again, is read (and traps) anew.
|
||||
sessionStorage.setItem(DRAFT_KEY, draft)
|
||||
routes('/editor')
|
||||
await expectEnginePanel()
|
||||
expect(traps.count).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -32,6 +32,7 @@ beforeEach(() => {
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
})
|
||||
useReportStore.getState().clearTrapped()
|
||||
})
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
@@ -91,7 +92,7 @@ describe('an unreadable draft', () => {
|
||||
})
|
||||
|
||||
describe('a core failure while reading the draft', () => {
|
||||
it.each(['core_unavailable', 'internal', 'rebase_failed'])(
|
||||
it.each(['core_unavailable', 'rebase_failed'])(
|
||||
'%s leaves the draft and the archive untouched',
|
||||
(kind) => {
|
||||
const draft = JSON.stringify(minimalReport(sheet))
|
||||
@@ -109,6 +110,91 @@ describe('a core failure while reading the draft', () => {
|
||||
)
|
||||
})
|
||||
|
||||
describe('a core trap while reading the draft (internal)', () => {
|
||||
/** A sheet whose draft restore traps (`internal`), counting the reads. */
|
||||
function trappingSheet() {
|
||||
const calls = { n: 0 }
|
||||
const index = {
|
||||
...sheet,
|
||||
ops: {
|
||||
restoreDraft: () => {
|
||||
calls.n += 1
|
||||
return { ok: false, kind: 'internal' }
|
||||
},
|
||||
},
|
||||
} as unknown as SheetIndex
|
||||
return { index, calls }
|
||||
}
|
||||
const draftText = () => JSON.stringify(minimalReport(sheet))
|
||||
|
||||
function seed() {
|
||||
const draft = draftText()
|
||||
sessionStorage.setItem(DRAFT_KEY, draft)
|
||||
sessionStorage.setItem(ARCHIVE_KEY, '{"kept":true}')
|
||||
return draft
|
||||
}
|
||||
|
||||
it('holds the draft (engine_failure) and its archive, both untouched', () => {
|
||||
const draft = seed()
|
||||
const { index } = trappingSheet()
|
||||
const result = useReportStore.getState().restoreDraft(index)
|
||||
expect(result).toMatchObject({
|
||||
kind: 'held',
|
||||
held: [
|
||||
{ text: 'draft', reason: 'engine_failure' },
|
||||
{ text: 'archive', reason: 'companion' },
|
||||
],
|
||||
})
|
||||
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
|
||||
expect(sessionStorage.getItem(ARCHIVE_KEY)).toBe('{"kept":true}')
|
||||
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
|
||||
expect(useReportStore.getState().report).toBeNull()
|
||||
})
|
||||
|
||||
it('never reads the same pair again, except on the explicit retry', () => {
|
||||
seed()
|
||||
const { index, calls } = trappingSheet()
|
||||
const store = useReportStore.getState()
|
||||
store.restoreDraft(index)
|
||||
expect(store.restoreDraft(index)).toMatchObject({ kind: 'held' })
|
||||
expect(calls.n).toBe(1)
|
||||
store.restoreDraft(index, { retryTrapped: true })
|
||||
expect(calls.n).toBe(2)
|
||||
})
|
||||
|
||||
it('answers a new session HELD with the engine cause, without a second read', () => {
|
||||
seed()
|
||||
const { index, calls } = trappingSheet()
|
||||
const store = useReportStore.getState()
|
||||
store.restoreDraft(index)
|
||||
const draft = { practitioner: { name: 'p' } } as never
|
||||
expect(store.initReport(draft, sheet.sheet.ref, index)).toEqual({
|
||||
ok: false,
|
||||
reason: 'held',
|
||||
engine: true,
|
||||
})
|
||||
expect(store.hydrateImport({ report: minimalReport(sheet), archive: null }, index)).toEqual({
|
||||
ok: false,
|
||||
reason: 'held',
|
||||
engine: true,
|
||||
})
|
||||
expect(calls.n).toBe(1)
|
||||
})
|
||||
|
||||
it('reads again once the stored pair changed, or after a discard', () => {
|
||||
seed()
|
||||
const { index, calls } = trappingSheet()
|
||||
const store = useReportStore.getState()
|
||||
store.restoreDraft(index)
|
||||
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet, { conclusion: 'x' })))
|
||||
store.restoreDraft(index)
|
||||
expect(calls.n).toBe(2)
|
||||
store.discardSessionText('archive')
|
||||
store.restoreDraft(index)
|
||||
expect(calls.n).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('an unreadable archive beside a readable draft', () => {
|
||||
it('goes to its quarantine key while the draft restores', () => {
|
||||
sessionStorage.setItem(
|
||||
|
||||
Reference in new issue
Block a user