feat(app): R2 switch — the application runs its domain rules in the Rust core

Consumers now fed by the core (crates/core through @faunosteo/core-wasm):
- the sheet: the bundled payload is parsed and indexed by the core
  (SheetHandle, SheetIndexData); SheetIndex reads precomputed tables only;
- the store: new report, add / remove / move observation, draft restore
  (v2 migration + rebase) through the core, actions answering { ok };
- the editor click chain (zone.click), laterality and vertebra pickers
  (zone.add_sides, vertebra.initial / sync / select), the findings picker
  (finding.toggle by clicked leaf position), zone removal;
- the import: engine byte scan (TypeScript until R4), then the core's
  layered reading and rebase in one call; the export: the core builds the
  sheet snapshot, the frozen TypeScript engine writes the PDF (R4).
Lazy core: Home and the new-report form read the sheet availability from
the bundle and load the module on import / submit only; the auth shell
never references it. Degraded states (core_unavailable, invalid_sheet)
show the validated notice with a retry and never redirect or touch the
draft; an unreadable draft or archive is set aside under
osteo:quarantine:* (only content kinds; a failed write keeps it in place
and the editor stays), a rebase that flags items keeps the raw pre-rebase
draft. Four strings, wording validated by the owner.
Deleted: services/zoneInteraction.ts and its suite (13 cases ported to
cargo), the TypeScript Finding builder and vertebra selection rules of the
pickers, store rules, persistence parsing, hydrateReport. ESLint forbids
@faunosteo/domain in apps/app/src; the report:compare CLI keeps the frozen
domain until R4 (scripts/compare/sheet.ts). App suite 313/313 on the real
core (24 new tests: quarantine, degraded editor, core failures, N-1
reader); step6 goldens and the frozen envelopes unchanged.
This commit is contained in:
bchanot committed 2026-10-14 00:41:34 +02:00
1 parent 794dfd9d0b
commit 74fcb37564
65 files changed
+2227 -1678

No files matched your search

+103 -58
View File
@@ -3,7 +3,10 @@ import { useNavigate } from 'react-router-dom'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import DetailModal from '@/components/canvas/DetailModal'
import ObservationList from '@/components/observation/ObservationList'
import ObservationPickers from '@/components/observation/ObservationPickers'
import ObservationPickers, {
type LateralTarget,
type VertebraTarget,
} from '@/components/observation/ObservationPickers'
import ConclusionPanel from '@/components/report/ConclusionPanel'
import ReportHeader from '@/components/report/ReportHeader'
import EditInfosDialog, {
@@ -11,25 +14,22 @@ import EditInfosDialog, {
type Identity,
} from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import Button from '@/components/ui/Button'
import { useReportStore } from '@/state/reportStore'
import {
useReportStore,
type ActionResult,
type RestoreResult,
} from '@/state/reportStore'
import { writeCachedPractitioner } from '@/state/practitionerCache'
import { useLocaleStore } from '@/state/localeStore'
import { useSheet } from '@/sheets/useSheet'
import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
import {
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
toggleZone,
type ZoneRef,
} from '@/services/zoneInteraction'
import type { SheetIndex } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import type { ViewStates } from '@/anatomy/drawing'
import { exportReportToPdf } from '@/pdf/export'
import type { ExportWarning } from '@faunosteo/pdf'
import type { RebaseOutcome } from '@faunosteo/domain'
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
@@ -45,6 +45,19 @@ function unresolvedCountOf(outcome: RebaseOutcome): number {
return outcome.unresolvedZones + outcome.unresolvedFindings
}
/** The alert of a restore, if any: a rebase on another sheet or a draft set aside. */
function restoreAlert(
result: RestoreResult,
t: ReturnType<typeof useT>,
): string | null {
if (result.kind === 'quarantined') return t('editor.draft_quarantined')
if (result.kind === 'restored' && result.rebase.rebased) {
const count = String(unresolvedCountOf(result.rebase))
return t('editor.draft_rebased').replace('{count}', count)
}
return null
}
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
export default function EditorRoute() {
const navigate = useNavigate()
@@ -56,8 +69,14 @@ export default function EditorRoute() {
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
const [detailViewId, setDetailViewId] = useState<string | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
const [lateralTarget, setLateralTarget] = useState<ZoneRef | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
null,
)
const [lateralTarget, setLateralTarget] = useState<LateralTarget | null>(
null,
)
// The core failed while reading the draft: stay here, keep the draft, offer a retry.
const [restoreFailed, setRestoreFailed] = useState(false)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
const [editDraft, setEditDraft] = useState<Identity | null>(null)
@@ -69,15 +88,24 @@ export default function EditorRoute() {
}, [])
// No report in memory: restore the per-tab draft once the sheet is known.
// A draft rebased on another sheet is announced with its unresolved count.
// 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).
useEffect(() => {
if (report) return
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet')
return
if (sheet.status === 'ready') {
const outcome = store.restoreDraft(sheet.index)
if (outcome?.rebased && !rebaseAlerted.current) {
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') {
setRestoreFailed(true)
return
}
const alert = result ? restoreAlert(result, t) : null
if (alert && !rebaseAlerted.current) {
rebaseAlerted.current = true
const count = String(unresolvedCountOf(outcome))
window.alert(t('editor.draft_rebased').replace('{count}', count))
window.alert(alert)
}
}
if (sheet.status !== 'loading' && !useReportStore.getState().report)
@@ -111,42 +139,56 @@ export default function EditorRoute() {
if (sheet.status !== 'ready' || !report) return
const activeObs =
activeIndex >= 0 ? report.observations[activeIndex] : undefined
const index = sheet.index
const annotation = index.annotation(annotationId)
const decision = decideZoneClick(annotation, activeObs)
if (!annotation) return
switch (decision.kind) {
case 'ignore':
return
const outcome = sheet.index.ops.zoneClick(activeObs ?? null, annotationId)
if (!outcome.ok) return window.alert(t('core.action_failed'))
const click = outcome.value
if (click.observation) store.updateObservation(activeIndex, click.observation)
switch (click.kind) {
case 'open_view':
return setDetailViewId(decision.viewId)
return setDetailViewId(click.viewId ?? null)
case 'activate_fallback':
return store.setActiveObservation(report.observations.length - 1)
case 'open_vertebra_picker': {
const { observation, index: zoneIndex } = ensureZone(
activeObs!,
annotation,
)
store.updateObservation(activeIndex, observation)
return setVertebraTarget(zoneIndex)
}
case 'open_vertebra_picker':
return setVertebraTarget({
zoneIndex: click.zoneIndex ?? 0,
initial: click.vertebrae ?? [],
})
case 'open_laterality_picker':
return setLateralTarget(refOf(annotation))
case 'remove_both_sides':
return store.updateObservation(
activeIndex,
removeAllSides(activeObs!, refOf(annotation)),
)
case 'toggle':
return store.updateObservation(
activeIndex,
toggleZone(activeObs!, annotation),
)
return setLateralTarget({
annotationId,
sidesPresent: click.sidesPresent ?? [],
})
default:
return
}
},
[sheet, store],
[sheet, store, t],
)
/** A store action the core ran: the practitioner hears about a failure. */
const guarded = useCallback(
(result: ActionResult) => {
if (!result.ok) window.alert(t('core.action_failed'))
},
[t],
)
/** The vertebra picker opened from a zone chip: the core computes its selection. */
function openVertebraPicker(index: SheetIndex, zoneIndex: number) {
if (!activeObs) return
const outcome = index.ops.vertebraInitial(activeObs, zoneIndex)
if (!outcome.ok) return window.alert(t('core.action_failed'))
setVertebraTarget({ zoneIndex, initial: outcome.value })
}
function removeZone(index: SheetIndex, i: number, zoneIndex: number) {
const obs = report?.observations[i]
if (!obs) return
const outcome = index.ops.removeZoneAt(obs, zoneIndex)
if (outcome.ok) store.updateObservation(i, outcome.value)
else window.alert(t('core.action_failed'))
}
function acknowledgeDisclaimer() {
sessionStorage?.setItem(DISCLAIMER_FLAG, '1')
setDisclaimer(null)
@@ -190,6 +232,12 @@ export default function EditorRoute() {
}
}
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet') {
return <CoreUnavailable onRetry={sheet.retry} />
}
if (restoreFailed) {
return <CoreUnavailable onRetry={() => window.location.reload()} />
}
if (!report) return null
if (sheet.status === 'loading') {
return (
@@ -218,7 +266,7 @@ export default function EditorRoute() {
<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
index={index}
viewId={index.mainView.id}
viewId={index.mainViewId}
states={states}
onZoneClick={onZoneClick}
className="flex-1"
@@ -241,19 +289,16 @@ export default function EditorRoute() {
onToggle={(i) =>
store.setActiveObservation(activeIndex === i ? -1 : i)
}
onAdd={store.addObservation}
onDelete={store.removeObservation}
onMoveUp={store.moveObservationUp}
onMoveDown={store.moveObservationDown}
onAdd={() => guarded(store.addObservation())}
onDelete={(i) => guarded(store.removeObservation(i))}
onMoveUp={(i) => guarded(store.moveObservationUp(i))}
onMoveDown={(i) => guarded(store.moveObservationDown(i))}
sheet={index}
onChange={store.updateObservation}
onOpenVertebraPicker={(_i, zoneIndex) =>
setVertebraTarget(zoneIndex)
openVertebraPicker(index, zoneIndex)
}
onRemoveZone={(i, zoneIndex) => {
const obs = report.observations[i]
if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex))
}}
onRemoveZone={(i, zoneIndex) => removeZone(index, i, zoneIndex)}
/>
<ConclusionPanel
conclusion={report.conclusion}
+21 -17
View File
@@ -1,18 +1,21 @@
import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react'
import {
rebaseReportOnSheet,
type ArchiveReadOutcome,
type RebaseOutcome,
} from '@faunosteo/domain'
import type {
ArchiveReadOutcome,
RebaseOutcome,
} from '@faunosteo/core-wasm/types'
import AppHeader from '@/components/brand/AppHeader'
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
import {
importAttachment,
ImportError,
MAX_PDF_BYTES,
readAttachment,
} from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT'
@@ -100,6 +103,8 @@ function importErrorMessage(err: unknown, t: Translate): string {
return t('home.import.error_attachment_stripped')
case 'no_attachment':
return t('home.import.error_no_attachment')
case 'core_unavailable':
return t('home.import.error_core_unavailable')
}
}
@@ -107,22 +112,21 @@ export default function HomeRoute() {
const navigate = useNavigate()
const fileRef = useRef<HTMLInputElement | null>(null)
const hydrateImport = useReportStore((s) => s.hydrateImport)
const sheet = useSheet(DEFAULT_SPECIES_ID)
// The page only needs to know a sheet exists; the core loads when a file is picked.
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const t = useT()
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File, index: SheetIndex) {
async function importFile(file: File) {
// The engine refuses the same size; checking first keeps a huge file out of memory.
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
const rebase = rebaseReportOnSheet(
outcome.report,
index,
outcome.archive?.sheetSnapshot ?? null,
)
const attachment = await readAttachment(bytes)
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 lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
@@ -135,7 +139,7 @@ export default function HomeRoute() {
setBusy(true)
setError(null)
try {
await importFile(file, sheet.index)
await importFile(file)
} catch (err) {
setError(importErrorMessage(err, t))
} finally {
+16 -9
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm'
import AppHeader from '@/components/brand/AppHeader'
@@ -13,7 +13,8 @@ import {
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import { useSheetAvailability } from '@/sheets/useSheet'
import { coreRuntime } from '@/core/runtime'
import { useT } from '@/i18n/useT'
/** The one species this build ships a sheet for. */
@@ -23,7 +24,8 @@ export default function NewReportRoute() {
const navigate = useNavigate()
const initReport = useReportStore((s) => s.initReport)
const t = useT()
const sheet = useSheet(DEFAULT_SPECIES_ID)
// The form needs the sheet's reference and name only; the core loads on submit.
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
const [practitioner, setPractitioner] = useState<Practitioner>({ name: '' })
const [animal, setAnimal] = useState<Animal>({
@@ -44,10 +46,14 @@ export default function NewReportRoute() {
owner.name.trim() &&
sheet.status === 'ready'
function submit() {
async function submit() {
if (!canSubmit || sheet.status !== 'ready') return
writeCachedPractitioner(practitioner)
initReport(
if (!(await coreRuntime().ready())) {
window.alert(t('sheet.core_unavailable'))
return
}
const created = initReport(
{
date,
practitioner,
@@ -57,9 +63,10 @@ export default function NewReportRoute() {
conclusion: '',
recommendations: '',
},
sheet.index.sheet.ref,
sheet.sheet.ref,
)
navigate('/editor')
if (created.ok) navigate('/editor')
else window.alert(t('core.action_failed'))
}
return (
@@ -91,8 +98,8 @@ export default function NewReportRoute() {
sheet.status === 'ready'
? [
{
id: sheet.index.sheet.speciesId,
name: sheet.index.sheet.document.name,
id: sheet.sheet.speciesId,
name: sheet.sheet.name,
},
]
: [