pediatric-ai-scribe-v3/client/src/pages/SickVisit.tsx
Daniel e6d0e5ef8c feat(notes): editable AI output + automatic correction tracking
Restores two pieces of vanilla behavior the React port silently dropped:

1. The output divs were contenteditable in vanilla — clinicians fix
   AI mistakes inline before saving the encounter or copying out.
   The early React port rendered the output as a read-only div, so
   any edit forced a copy-paste workflow.

2. correctionTracker.js (public/js/correctionTracker.js) saved every
   meaningful inline edit to user_memories under category
   correction_<section> so the AI learns user preferences. Settings
   → Corrections still showed them, but nothing in React was *writing*
   them — the loop was broken.

New EditableResult component wraps the result body in a textarea,
captures the AI baseline on first render / after refine|shorten, and
on blur posts to /api/memories/correction (only when the edit clears
the noise threshold from vanilla — wordDiff ≥ 2 OR charDiff ≥ 20 on
outputs > 100 chars).

Wired into all 7 note pages:
  Encounter   → section: 'encounter'
  Dictation   → section: 'hpi'
  SOAP        → section: 'soap'
  SickVisit   → section: 'sickvisit'
  WellVisit   → section: 'wellvisit'
  HospitalCourse → section: null   (server enum has no correction_hospital)
  ChartReview    → section: null   (server enum has no correction_chart)

Tests:
  shared/clinical/correction-tracker.ts (+ .test.ts) — pure heuristic
  with vectors covering the noise floor (single-word swap on long
  text → skipped; new sentence → tracked; large char diff → tracked).
  Lives in shared/ so the root vitest config picks it up; the React
  component imports from there.
2026-04-24 05:24:09 +02:00

147 lines
6.2 KiB
TypeScript

// ============================================================
// SICK VISIT — /api/sick-visit/note
// ============================================================
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import type { VisitNoteOk } from '@/shared/types';
import { SickVisitRequestSchema, type SickVisitRequest } from '@/shared/schemas';
import Recorder from '@/components/Recorder';
import EncounterToolbar from '@/components/EncounterToolbar';
import EditableResult from '@/components/EditableResult';
const TYPE = 'sickvisit' as const;
export default function SickVisit() {
const [label, setLabel] = useState('');
const [patientAge, setPatientAge] = useState('');
const [patientGender, setPatientGender] = useState('');
const [chiefComplaint, setChiefComplaint] = useState('');
const [transcript, setTranscript] = useState('');
const [interim, setInterim] = useState('');
const [result, setResult] = useState<string | null>(null);
const [validationError, setValidationError] = useState<string | null>(null);
const [recError, setRecError] = useState<string | null>(null);
const generate = useMutation<VisitNoteOk, Error, SickVisitRequest>({
mutationFn: (body) => api.post<VisitNoteOk>('/api/sick-visit/note', body),
onSuccess: (data) => setResult(data.note),
});
function submit(e: React.FormEvent) {
e.preventDefault();
setValidationError(null);
const body: SickVisitRequest = { patientAge, patientGender, chiefComplaint, transcript: (interim || transcript).trim() };
const parsed = SickVisitRequestSchema.safeParse(body);
if (!parsed.success) {
setValidationError(parsed.error.issues.map((i: { message: string }) => i.message).join(', '));
return;
}
setResult(null);
generate.mutate(parsed.data);
}
const input = 'w-full rounded-md border border-input bg-background px-3 py-2 text-sm';
const displayedTranscript = interim || transcript;
return (
<div className="max-w-4xl mx-auto p-6 space-y-4">
<header>
<h1 className="text-2xl font-semibold">Sick Visit</h1>
<p className="text-sm text-muted-foreground">
Chief complaint + transcript structured sick-visit note.
</p>
</header>
<EncounterToolbar
type={TYPE}
label={label} setLabel={setLabel}
transcript={transcript} generatedNote={result || ''}
partialData={{ age: patientAge, gender: patientGender, chiefComplaint }}
onLoad={(enc) => {
setTranscript(enc.transcript || '');
setInterim('');
setResult(enc.generated_note || null);
try {
const pd = enc.partial_data ? JSON.parse(enc.partial_data) : null;
if (pd?.age) setPatientAge(pd.age);
if (pd?.gender) setPatientGender(pd.gender);
if (pd?.chiefComplaint) setChiefComplaint(pd.chiefComplaint);
} catch { /* ignore */ }
setLabel(enc.label || '');
}}
onClear={() => {
setTranscript(''); setInterim(''); setResult(null); setValidationError(null);
setPatientAge(''); setPatientGender(''); setChiefComplaint('');
}}
/>
<form onSubmit={submit} className="space-y-4">
<div className="grid grid-cols-3 gap-3">
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Age</span>
<input className={input} placeholder="e.g. 4 years" value={patientAge} onChange={(e) => setPatientAge(e.target.value)} />
</label>
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Gender</span>
<select className={input} value={patientGender} onChange={(e) => setPatientGender(e.target.value)}>
<option value="">Select</option>
<option>Male</option>
<option>Female</option>
</select>
</label>
<label className="flex flex-col gap-1 col-span-3 md:col-span-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Chief complaint</span>
<input className={input} placeholder="e.g. Fever x 2 days" value={chiefComplaint} onChange={(e) => setChiefComplaint(e.target.value)} />
</label>
</div>
<Recorder
module="sickvisit"
onTranscript={(text, meta) => {
setTranscript((prev) => (meta.appended ? (prev ? prev + ' ' + text : text) : text));
setInterim('');
setRecError(null);
}}
onInterim={(t) => setInterim(t ? (transcript ? transcript + ' ' + t : t) : '')}
onError={(msg) => setRecError(msg)}
/>
{recError && <div className="text-sm text-destructive">{recError}</div>}
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Transcript / dictation</span>
<textarea
className={input + ' min-h-[200px] font-mono text-sm'}
placeholder="Click Start recording, or type / paste encounter narrative."
value={displayedTranscript}
onChange={(e) => { setTranscript(e.target.value); setInterim(''); }}
/>
</label>
{validationError && <div className="text-sm text-destructive">{validationError}</div>}
{generate.error && <div className="text-sm text-destructive">{(generate.error as ApiError).message}</div>}
<button
type="submit"
disabled={generate.isPending || !chiefComplaint.trim()}
className="rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium disabled:opacity-50"
>
{generate.isPending ? 'Generating…' : 'Generate Note'}
</button>
</form>
{result !== null && (
<EditableResult
text={result}
onChange={setResult}
section="sickvisit"
title="Sick Visit Note"
exportLabel="sick-visit-note"
exportType="sick-visit"
sourceContext={displayedTranscript}
/>
)}
</div>
);
}