Spaces:
Running
Running
Tutor credit/budget guard, analytics, status banner (part 2)
Browse filesFiles changed (24)
- frontend/src/main.tsx+4
- frontend/src/pages/AboutPage.tsx+1
- frontend/src/pages/OnboardingPage.tsx+2
- frontend/src/pages/ReadPage.tsx+5-1
- frontend/src/pages/ServerLine.tsx+5-4
- frontend/src/pages/SessionSummaryView.tsx+3
- frontend/src/pages/Start.module.css+3
- frontend/src/pages/StartPage.tsx+4
- frontend/src/rail/AskTutor.tsx+2-1
- frontend/src/rail/DebriefPanel.tsx+23-9
- frontend/src/rail/Rail.module.css+3
- frontend/src/rail/debriefCopy.ts-1
- frontend/src/reference/ReferenceDrawer.tsx+2
- frontend/src/tutor/TutorNotice.module.cssAdded+12
- frontend/src/tutor/TutorNotice.tsxAdded+21
- frontend/src/tutor/health.tsAdded+22
- frontend/src/tutor/status.test.tsAdded+82
- frontend/src/tutor/status.tsAdded+78
- frontend/src/tutorial/Tutorial.tsx+2
- frontend/src/types/contracts.ts+20
- shared/contracts.py+12
- shared/schemas/api.json+478-52
- tests/e2e/general_use.spec.ts+6-5
- tests/e2e/tutor_status.spec.tsAdded+188
2 unmodified lines3456789101112132 unmodified linesimport './index.css';import { App } from './app/App';import { initApiMode } from './api/client';if (new URLSearchParams(location.search).get('projector') === '1') {document.documentElement.dataset.projector = '1';}// Decide real API vs synthetic mock before the first request (never throws).initApiMode().finally(() => {createRoot(document.getElementById('root')!).render(2 unmodified lines345678910111213141516172 unmodified linesimport './index.css';import { App } from './app/App';import { initApiMode } from './api/client';import { initAnalytics } from './analytics';if (new URLSearchParams(location.search).get('projector') === '1') {document.documentElement.dataset.projector = '1';}// Anonymous page-view and click counts (off on localhost and under automation; see analytics.ts).initAnalytics();// Decide real API vs synthetic mock before the first request (never throws).initApiMode().finally(() => {createRoot(document.getElementById('root')!).render(
147 unmodified lines148149150151152153147 unmodified linesand zoom trace for each film, with the name or code you gave, if any. This browser remembers a reader id soyou can pick up where you left off; “Start as someone new” on the first page clears it.</p></section><section className={s.ruled} data-testid="about-next">147 unmodified lines148149150151152153154147 unmodified linesand zoom trace for each film, with the name or code you gave, if any. This browser remembers a reader id soyou can pick up where you left off; “Start as someone new” on the first page clears it.</p><p data-testid="about-analytics">We count page views and clicks with an anonymous browser id. No names, marks or answers are sent.</p></section><section className={s.ruled} data-testid="about-next">
5 unmodified lines6789101116 unmodified lines2829303132335 unmodified linesimport { api, isGateError } from '../api/client';import { forgetLearner, loadRemembered, readPath, SAMPLE_NAME, sampleSessionCreate } from '../api/sessionOptions';import { PageShell } from '../app/Shell';import { SMALL_SCREEN_TEXT } from '../app/SmallScreen';import { useNarrow } from '../app/useMediaQuery';import { useTitle } from '../app/useTitle';16 unmodified linesmutationFn: () => api.createSession(sampleSessionCreate({ projector })),onSuccess: (r) => {setSession({ sessionId: r.session_id, learnerId: r.learner_id, displayName: SAMPLE_NAME, level: 'other', mode: 'practice' });navigate(readPath());},});5 unmodified lines678910111216 unmodified lines293031323334355 unmodified linesimport { api, isGateError } from '../api/client';import { forgetLearner, loadRemembered, readPath, SAMPLE_NAME, sampleSessionCreate } from '../api/sessionOptions';import { PageShell } from '../app/Shell';import { track } from '../analytics';import { SMALL_SCREEN_TEXT } from '../app/SmallScreen';import { useNarrow } from '../app/useMediaQuery';import { useTitle } from '../app/useTitle';16 unmodified linesmutationFn: () => api.createSession(sampleSessionCreate({ projector })),onSuccess: (r) => {setSession({ sessionId: r.session_id, learnerId: r.learner_id, displayName: SAMPLE_NAME, level: 'other', mode: 'practice' });track('session_start');navigate(readPath());},});
17 unmodified lines181920212223276 unmodified lines30030130230330430515 unmodified lines321322323324325326327113 unmodified lines44144244344444544617 unmodified linesimport { colorizeServerHeatmap, densityFromTelemetry, densityToDataUrl } from '../viewer/heatmap';import { TelemetryBuffer } from '../viewer/telemetry';import { Footer, Nav, SyntheticBadge } from '../app/Shell';import { SessionSummaryView } from './SessionSummaryView';import { KeysHelp } from '../read/KeysHelp';import { caseLabel } from '../read/keys';276 unmodified linessetHeatmapUrl(url);}setResult(r);prefetchNext();},});15 unmodified lines}, [read, submitM, result, telemetry, hints.length]);const askHint = useCallback(() => {if (hintsEnabled && hintsLeft > 0 && !hintM.isPending && !result) hintM.mutate();}, [hintsEnabled, hintsLeft, hintM, result]);const callNormal = useCallback(() => {113 unmodified lines</div><aside className={shell.rail} aria-label="Your read and feedback"><div className={shell.railBody}>{!result ? (<ReadRailread={read}17 unmodified lines1819202122232425276 unmodified lines30230330430530630730815 unmodified lines324325326327328329330113 unmodified lines44444544644744844945017 unmodified linesimport { colorizeServerHeatmap, densityFromTelemetry, densityToDataUrl } from '../viewer/heatmap';import { TelemetryBuffer } from '../viewer/telemetry';import { Footer, Nav, SyntheticBadge } from '../app/Shell';import { track } from '../analytics';import { TutorNotice } from '../tutor/TutorNotice';import { SessionSummaryView } from './SessionSummaryView';import { KeysHelp } from '../read/KeysHelp';import { caseLabel } from '../read/keys';276 unmodified linessetHeatmapUrl(url);}setResult(r);track('film_submitted');prefetchNext();},});15 unmodified lines}, [read, submitM, result, telemetry, hints.length]);const askHint = useCallback(() => {if (hintsEnabled && hintsLeft > 0 && !hintM.isPending && !result) { track('hint'); hintM.mutate(); }}, [hintsEnabled, hintsLeft, hintM, result]);const callNormal = useCallback(() => {113 unmodified lines</div><aside className={shell.rail} aria-label="Your read and feedback"><div className={shell.railBody}><TutorNotice className={rail.tutorNotice} />{!result ? (<ReadRailread={read}
12345678910111213141516// One quiet line about the film library. It only gets loud when something is wrong, and then says what to do.import { useQuery } from '@tanstack/react-query';import { api, apiMode } from '../api/client';export function ServerLine({ className }: { className?: string }) {const health = useQuery({ queryKey: ['health'], queryFn: api.health, retry: false });const mock = apiMode().mode === 'mock';return (<p className={className} data-testid="health">{health.isPending ? 'Checking the film library…': mock ? 'The film library is not reachable, so you are seeing synthetic practice shapes, not radiographs. Reload the page to try the library again.': health.data?.ok? `Library: ${health.data.cases.toLocaleString()} chest films with radiologist outlines.${health.data.offline ? ' The tutor is offline, so explanations are the built-in ones.' : ''}`: 'The film library is not answering. Check your connection, then reload the page.'}</p>);1234567891011121314151617// One quiet line about the film library. It only gets loud when something is wrong, and then says what to do.// (The tutor's own state is the TutorNotice banner above the form.)import { apiMode } from '../api/client';import { useHealth } from '../tutor/health';export function ServerLine({ className }: { className?: string }) {const health = useHealth();const mock = apiMode().mode === 'mock';return (<p className={className} data-testid="health">{health.isPending ? 'Checking the film library…': mock ? 'The film library is not reachable, so you are seeing synthetic practice shapes, not radiographs. Reload the page to try the library again.': health.data?.ok? `Library: ${health.data.cases.toLocaleString()} chest films with radiologist outlines.`: 'The film library is not answering. Check your connection, then reload the page.'}</p>);
7 unmodified lines891011121335 unmodified lines4950515253547 unmodified linesimport { markTestDone } from '../api/sessionOptions';import { PageShell } from '../app/Shell';import { useTitle } from '../app/useTitle';import { MissBreakdown } from '../dashboard/charts/MissBreakdown';import { SummaryStats } from '../dashboard/charts/SummaryStats';import { MISS_NAME } from '../dashboard/palette';35 unmodified linesconst mode = sm?.mode ?? session.mode;const test = isAssessment(mode as SessionInfo['mode']);useTitle(test ? 'Test results' : sm && !sm.complete ? 'Set in progress' : 'Set complete');// A finished test set moves this learner on to the other set next time.useEffect(() => {if (sm && test && sm.complete && session.learnerId) markTestDone(session.learnerId, mode);7 unmodified lines89101112131435 unmodified lines50515253545556577 unmodified linesimport { markTestDone } from '../api/sessionOptions';import { PageShell } from '../app/Shell';import { useTitle } from '../app/useTitle';import { track } from '../analytics';import { MissBreakdown } from '../dashboard/charts/MissBreakdown';import { SummaryStats } from '../dashboard/charts/SummaryStats';import { MISS_NAME } from '../dashboard/palette';35 unmodified linesconst mode = sm?.mode ?? session.mode;const test = isAssessment(mode as SessionInfo['mode']);useTitle(test ? 'Test results' : sm && !sm.complete ? 'Set in progress' : 'Set complete');// The end-of-set page opened (counted once per set, not per render).useEffect(() => { track('set_complete'); }, [sid]);// A finished test set moves this learner on to the other set next time.useEffect(() => {if (sm && test && sm.complete && session.learnerId) markTestDone(session.learnerId, mode);
69 unmodified lines70717269 unmodified lines.primary:disabled { background: #a7b0b8; cursor: default; }.error { padding: 10px 12px; background: #e7ecef; border-left: 3px solid var(--grease-amber); border-radius: 0 4px 4px 0; font-size: var(--fs-1); margin: 0 0 14px; }.health { color: var(--report-ink-muted); font-size: 14px; line-height: 1.45; margin: 14px 0 0; }69 unmodified lines70717273747569 unmodified lines.primary:disabled { background: #a7b0b8; cursor: default; }.error { padding: 10px 12px; background: #e7ecef; border-left: 3px solid var(--grease-amber); border-radius: 0 4px 4px 0; font-size: var(--fs-1); margin: 0 0 14px; }.health { color: var(--report-ink-muted); font-size: 14px; line-height: 1.45; margin: 14px 0 0; }/* Tutor status, when the AI tutor is not live: above the form, with the form's own rhythm. */.tutorNotice { margin: 4px 0 12px; }
10 unmodified lines11121314151639 unmodified lines56575859606117 unmodified lines79808182838410 unmodified linestype Count, type Practice, type StartForm,} from '../api/sessionOptions';import { PageShell } from '../app/Shell';import { useTitle } from '../app/useTitle';import { useSession } from '../state/session';import { HALF_NORMAL } from './OnboardingPage';39 unmodified linesonSuccess: (r, form) => {const typed = form.name.trim();remember(r.learner_id, typed);setSession({sessionId: r.session_id, learnerId: r.learner_id, displayName: typed, level: 'other', mode: r.mode,drillLabel: r.mode === 'drill' ? form.finding : undefined,17 unmodified linesreturn (<PageShell><h1 className={p.h1}>Start reading</h1><form onSubmit={(e) => { e.preventDefault(); if (!begin.isPending) begin.mutate({ name, practice: chosen, finding, count }); }} data-testid="start-form"><section className={s.block} aria-labelledby="who-q"><h2 id="who-q" className={s.q}>Who is reading?</h2>10 unmodified lines111213141516171839 unmodified lines5859606162636417 unmodified lines8283848586878810 unmodified linestype Count, type Practice, type StartForm,} from '../api/sessionOptions';import { PageShell } from '../app/Shell';import { track } from '../analytics';import { TutorNotice } from '../tutor/TutorNotice';import { useTitle } from '../app/useTitle';import { useSession } from '../state/session';import { HALF_NORMAL } from './OnboardingPage';39 unmodified linesonSuccess: (r, form) => {const typed = form.name.trim();remember(r.learner_id, typed);track('session_start');setSession({sessionId: r.session_id, learnerId: r.learner_id, displayName: typed, level: 'other', mode: r.mode,drillLabel: r.mode === 'drill' ? form.finding : undefined,17 unmodified linesreturn (<PageShell><h1 className={p.h1}>Start reading</h1><TutorNotice className={s.tutorNotice} /><form onSubmit={(e) => { e.preventDefault(); if (!begin.isPending) begin.mutate({ name, practice: chosen, finding, count }); }} data-testid="start-form"><section className={s.block} aria-labelledby="who-q"><h2 id="who-q" className={s.q}>Who is reading?</h2>
1 unmodified line23456710 unmodified lines181920212223241 unmodified lineimport { useState } from 'react';import { useMutation } from '@tanstack/react-query';import { api } from '../api/client';import s from './Rail.module.css';export function AskTutor({ attemptId }: { attemptId: string }) {10 unmodified lines});const send = () => {const question = q.trim();if (question && remaining > 0 && !m.isPending) m.mutate(question);};return (<section className={s.section} aria-labelledby="ask-h" data-testid="ask">1 unmodified line234567810 unmodified lines192021222324251 unmodified lineimport { useState } from 'react';import { useMutation } from '@tanstack/react-query';import { api } from '../api/client';import { track } from '../analytics';import s from './Rail.module.css';export function AskTutor({ attemptId }: { attemptId: string }) {10 unmodified lines});const send = () => {const question = q.trim();if (question && remaining > 0 && !m.isPending) { track('ask'); m.mutate(question); }};return (<section className={s.section} aria-labelledby="ask-h" data-testid="ask">
12345678910111213141516171810 unmodified lines293031323334353637383910 unmodified lines5051525354555640 unmodified lines979899100101102103104// Tutor debrief (SPEC §8, §13): polls GET /attempts/{id}/debrief every 700 ms until ready/failed.import { useEffect, useState } from 'react';import { useQuery } from '@tanstack/react-query';import { api } from '../api/client';import type { DebriefResponse, RevealFinding } from '../types/contracts';import { openReference } from '../reference/store';import { plainText } from './copy';import { BUSY, PROVENANCE, SOURCE, SOURCE_TITLE } from './debriefCopy';import s from './Rail.module.css';const SLOW_MS = 15_000;export function DebriefPanel({ attemptId, findings, disabled }: { attemptId: string; findings: RevealFinding[]; disabled: boolean }) {const [slow, setSlow] = useState(false);const [flagged, setFlagged] = useState(false);const q = useQuery({queryKey: ['debrief', attemptId],queryFn: () => api.debrief(attemptId),10 unmodified linesreturn () => clearTimeout(t);}, []);if (disabled || q.data?.status === 'disabled') return null;const d = q.data;const failed = q.isError || d?.status === 'failed';// Rate-limited or failed: say so plainly, and still show any built-in explanation the server sent.const busy = failed || d?.error === 'rate_limited';const flag = () => {setFlagged(true);10 unmodified lines</span>)}</div>{busy && <p className={s.notice} data-testid="debrief-busy">{BUSY}</p>}{failed && !d?.debrief ? null : !d || d.status === 'pending' ? (<p className={s.muted} data-testid="debrief-pending">{slow ? 'The tutor is taking longer than usual. The facts above are complete.' : 'Writing your debrief…'}</p>) : d.debrief ? (40 unmodified lines)}</div></div>) : busy ? null : (<p className={s.notice} data-testid="debrief-busy">{BUSY}</p>)}</section>);1234567891011121314151617181920212210 unmodified lines33343536373839404142434445464748495051525310 unmodified lines6465666768697040 unmodified lines111112113114115116117118// Tutor debrief (SPEC §8, §13): polls GET /attempts/{id}/debrief every 700 ms until ready/failed.import { useEffect, useRef, useState } from 'react';import { useQuery, useQueryClient } from '@tanstack/react-query';import { api } from '../api/client';import { track } from '../analytics';import { debriefErrorText, debriefHadError } from '../tutor/status';import type { DebriefResponse, RevealFinding } from '../types/contracts';import { openReference } from '../reference/store';import { plainText } from './copy';import { PROVENANCE, SOURCE, SOURCE_TITLE } from './debriefCopy';import s from './Rail.module.css';const SLOW_MS = 15_000;export function DebriefPanel({ attemptId, findings, disabled }: { attemptId: string; findings: RevealFinding[]; disabled: boolean }) {const qc = useQueryClient();const [slow, setSlow] = useState(false);const [flagged, setFlagged] = useState(false);const counted = useRef(false);const q = useQuery({queryKey: ['debrief', attemptId],queryFn: () => api.debrief(attemptId),10 unmodified linesreturn () => clearTimeout(t);}, []);const d = q.data;const failed = q.isError || d?.status === 'failed';const settled = failed || d?.status === 'ready';// Once the debrief settles: count which kind arrived, and after a tutor problem re-check the tutor status so the// banner catches up without waiting for the next poll.useEffect(() => {if (!settled || counted.current || disabled) return;counted.current = true;if (d?.status === 'ready' && d.debrief) track(d.source === 'template' ? 'debrief_template' : 'debrief_live');if (debriefHadError(d, failed)) qc.invalidateQueries({ queryKey: ['health'] });}, [settled, d, failed, disabled, qc]);if (disabled || d?.status === 'disabled') return null;// Not the live tutor's words: say why in one plain sentence, and still show any built-in explanation the server sent.const problem = settled ? debriefErrorText(d, failed) : null;const flag = () => {setFlagged(true);10 unmodified lines</span>)}</div>{problem && <p className={s.notice} data-testid="debrief-busy">{problem}</p>}{failed && !d?.debrief ? null : !d || d.status === 'pending' ? (<p className={s.muted} data-testid="debrief-pending">{slow ? 'The tutor is taking longer than usual. The facts above are complete.' : 'Writing your debrief…'}</p>) : d.debrief ? (40 unmodified lines)}</div></div>) : problem ? null : (<p className={s.notice} data-testid="debrief-busy">{debriefErrorText({ status: 'failed' }, true)}</p>)}</section>);
309 unmodified lines310311312309 unmodified lines.normalOn .btn { margin-top: 4px; }.submitHelp { color: var(--report-ink); font-size: 14px; margin: 8px 0 0; line-height: 1.4; }.read :is(button, input, a):focus-visible, .result :is(button, input, a):focus-visible { outline: 2px solid #9a6200; outline-offset: 2px; }309 unmodified lines310311312313314315309 unmodified lines.normalOn .btn { margin-top: 4px; }.submitHelp { color: var(--report-ink); font-size: 14px; margin: 8px 0 0; line-height: 1.4; }.read :is(button, input, a):focus-visible, .result :is(button, input, a):focus-visible { outline: 2px solid #9a6200; outline-offset: 2px; }/* Tutor status banner at the top of the rail (TutorNotice). */.tutorNotice { margin: 12px 0 2px; }
9 unmodified lines101112139 unmodified linescache: 'Written by Claude earlier for the same facts; the saved text is shown.',template: 'A fixed explanation filled from the computed facts.',};export const BUSY = 'The tutor is busy. Showing the built-in explanation instead.';9 unmodified lines1011129 unmodified linescache: 'Written by Claude earlier for the same facts; the saved text is shown.',template: 'A fixed explanation filled from the computed facts.',};
2 unmodified lines345678155 unmodified lines1641651661671681692 unmodified lines// cyan. It never says anything about the case being read, so it is available before submit.// Mount <ReferenceDrawer /> once on a page; open it from anywhere with openReference(label) or <InfoButton />.import { useEffect, useRef, useState } from 'react';import { useQuery } from '@tanstack/react-query';import { assetUrl } from '../api/client';import { fetchReference } from '../api/reference';155 unmodified linesuseEffect(() => () => useReference.getState().close(), []);// Focus moves into the drawer when it opens and returns to where it was when it closes.const open = !!label;useEffect(() => {if (!open) return;const prev = document.activeElement as HTMLElement | null;2 unmodified lines3456789155 unmodified lines1651661671681691701712 unmodified lines// cyan. It never says anything about the case being read, so it is available before submit.// Mount <ReferenceDrawer /> once on a page; open it from anywhere with openReference(label) or <InfoButton />.import { useEffect, useRef, useState } from 'react';import { track } from '../analytics';import { useQuery } from '@tanstack/react-query';import { assetUrl } from '../api/client';import { fetchReference } from '../api/reference';155 unmodified linesuseEffect(() => () => useReference.getState().close(), []);// Focus moves into the drawer when it opens and returns to where it was when it closes.const open = !!label;useEffect(() => { if (open) track('reference_open'); }, [open]);useEffect(() => {if (!open) return;const prev = document.activeElement as HTMLElement | null;
123456789101112/* Amber outline = something about the learner's session, not the expert read; never a red alert (SPEC §14.1). */.notice { border: 1.5px solid #c98a17; border-radius: var(--radius); background: rgba(240, 169, 46, 0.08); padding: 8px 12px; font-size: var(--fs-1); line-height: 1.45; color: var(--report-ink);}.text { margin: 0; }.spend { margin: 4px 0 0; font-size: 13px; color: var(--report-ink-muted); font-variant-numeric: tabular-nums; }123456789101112131415161718192021// The tutor status banner: a calm, amber-outlined line at the top of the reading-room rail and on the start page,// shown only while the AI tutor is not live. Health is polled every 60 s; a debrief that ends in an error asks for a// fresh poll (DebriefPanel). Reviewers (server-set review cookie) also see today's spend when the server reports it.import { useHealth, useIsReviewer } from './health';import { bannerText, spendText, tutorStatus } from './status';import s from './TutorNotice.module.css';
export function TutorNotice({ className }: { className?: string }) { const health = useHealth(); const reviewer = useIsReviewer(); const t = tutorStatus(health.data); const text = bannerText(t); if (!text) return null; const spend = reviewer ? spendText(t) : null; return ( <div className={`${s.notice} ${className ?? ''}`} role="status" data-testid="tutor-notice" data-mode={t?.mode}> <p className={s.text}>{text}</p> {spend && <p className={s.spend} data-testid="tutor-spend">{spend}</p>} </div> );}12345678910111213141516171819202122// Shared health and access queries. Health is polled every 60 s while any page shows it (ServerLine, TutorNotice);// DebriefPanel invalidates it after a debrief ends in a tutor problem.import { useQuery } from '@tanstack/react-query';import { api } from '../api/client';
export const HEALTH_POLL_MS = 60_000;
export function useHealth() { return useQuery({ queryKey: ['health'], queryFn: api.health, retry: false, refetchInterval: HEALTH_POLL_MS, refetchOnWindowFocus: true });}
/** Is this browser a reviewer (review code configured and its cookie accepted)? False in mock mode and on error. */export function useIsReviewer(): boolean { const q = useQuery({ queryKey: ['access-status'], queryFn: api.access, retry: false, staleTime: 5 * 60_000, select: (a) => !!a.review_required && !!a.review_granted, }); return q.data === true;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import { describe, expect, it } from 'vitest';import { bannerText, debriefErrorText, resumeText, spendText, tutorStatus } from './status';
const now = new Date('2026-10-06T15:00:00');
describe('tutorStatus', () => { it('uses tutor when present, else falls back to offline', () => { expect(tutorStatus({ ok: true, offline: false, cases: 1, tutor: { mode: 'paused_rate' } })?.mode).toBe('paused_rate'); expect(tutorStatus({ ok: true, offline: true, cases: 1 })?.mode).toBe('offline'); expect(tutorStatus({ ok: true, offline: false, cases: 1 })?.mode).toBe('live'); expect(tutorStatus(null)).toBeNull(); });});
describe('bannerText', () => { it('is quiet when live', () => { expect(bannerText({ mode: 'live' })).toBeNull(); }); it.each([ ['offline', 'The AI tutor is off. You still get the built-in explanation after every film.'], ['paused_credits', 'The AI tutor is paused (account credits ran out). Built-in explanations continue.'], ['paused_rate', 'The AI tutor is busy; trying again shortly.'], ['paused_error', 'The AI tutor is unavailable right now. Built-in explanations continue.'], ['paused_budget', 'The AI tutor has reached its spending limit for now. Built-in explanations continue.'], ] as const)('%s', (mode, text) => { expect(bannerText({ mode })).toBe(text); }); it('adds the local resume time for a budget pause', () => { const t = new Date('2026-10-06T16:30:00').toISOString(); const text = bannerText({ mode: 'paused_budget', resume_at: t }, now)!; expect(text.startsWith('The AI tutor has reached its spending limit for now. Built-in explanations continue. Back around ')).toBe(true); expect(text).toContain(resumeText(t, now)!); expect(text).toMatch(/\d:30/); }); it('never shows a raw code', () => { expect(bannerText({ mode: 'something_new' as never })).toBe('The AI tutor is unavailable right now. Built-in explanations continue.'); });});
describe('resumeText', () => { it('names the weekday when the time is on another day, and copes with junk', () => { expect(resumeText(new Date('2026-10-08T09:05:00').toISOString(), now)).toMatch(/^\w{3} .*9:05/); expect(resumeText('not a date', now)).toBeNull(); expect(resumeText(null, now)).toBeNull(); });});
describe('spendText', () => { it('reads spend_usd.day', () => { expect(spendText({ mode: 'live', spend_usd: { day: 1.2345, hour: 0.1 } })).toBe('Spend today $1.23'); expect(spendText({ mode: 'live', spend_usd: { hour: 0.1 } })).toBeNull(); expect(spendText({ mode: 'live' })).toBeNull(); expect(spendText(null)).toBeNull(); });});
describe('debriefErrorText', () => { const d = { status: 'ready' as const, debrief: { headline: 'x' } as never }; it.each([ ['offline', 'The AI tutor is off. Showing the built-in explanation instead.'], ['credits_depleted', 'The AI tutor is paused (account credits ran out). Showing the built-in explanation instead.'], ['rate_limited', 'The AI tutor is busy. Showing the built-in explanation instead.'], ['budget_exceeded', 'The AI tutor has reached its spending limit for now. Showing the built-in explanation instead.'], ['unavailable', 'The AI tutor is unavailable right now. Showing the built-in explanation instead.'], ['auth', 'The AI tutor could not sign in to its service. Showing the built-in explanation instead.'], ['validator_failed', "The AI tutor's draft did not pass our checks. Showing the built-in explanation instead."], ['timeout', 'The AI tutor took too long. Showing the built-in explanation instead.'], ['internal_error', 'Something went wrong while writing the AI debrief. Showing the built-in explanation instead.'], ])('%s', (code, text) => { expect(debriefErrorText({ ...d, error: code }, false)).toBe(text); }); it('is silent for a clean debrief and never leaks an unknown code', () => { expect(debriefErrorText({ ...d, error: null }, false)).toBeNull(); expect(debriefErrorText({ ...d, error: 'LiveCallError' }, false)).toBe('The AI tutor is unavailable right now. Showing the built-in explanation instead.'); expect(debriefErrorText({ status: 'failed', error: 'LiveCallError' }, true)).toBe('The AI tutor is unavailable right now. The facts above are complete.'); expect(debriefErrorText({ status: 'failed', error: 'LiveCallError' }, true)).not.toContain('LiveCallError'); expect(debriefErrorText(undefined, true)).toBe('The AI tutor is unavailable right now. The facts above are complete.'); }); it('says the facts are complete when a known code comes with no explanation', () => { expect(debriefErrorText({ status: 'failed', error: 'timeout' }, true)).toBe('The AI tutor took too long. The facts above are complete.'); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778// Tutor status (GET /api/health → tutor.mode) and the per-debrief error codes, turned into plain sentences. Pure// functions; the hook and banner live in TutorNotice.tsx. Raw codes never reach the screen.import type { DebriefResponse, Health } from '../types/contracts';
export type TutorMode = NonNullable<Health['tutor']>['mode'];export type TutorStatus = NonNullable<Health['tutor']>;
const CONTINUES = 'Built-in explanations continue.';
/** The mode, with a fallback for servers that only say `offline`. */export function tutorStatus(h: Health | null | undefined): TutorStatus | null { if (!h) return null; if (h.tutor) return h.tutor; return { mode: h.offline ? 'offline' : 'live' };}
/** "3:45 PM" today, "Tue 3:45 PM" on another day; null when the time is missing or unreadable. */export function resumeText(iso: string | null | undefined, now: Date = new Date()): string | null { if (!iso) return null; const t = new Date(iso); if (Number.isNaN(t.getTime())) return null; const sameDay = t.toDateString() === now.toDateString(); const time = t.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); return sameDay ? time : `${t.toLocaleDateString([], { weekday: 'short' })} ${time}`;}
/** The banner sentence for a mode other than live; null when the tutor is live. */export function bannerText(t: TutorStatus | null, now: Date = new Date()): string | null { if (!t) return null; switch (t.mode) { case 'live': return null; case 'offline': return 'The AI tutor is off. You still get the built-in explanation after every film.'; case 'paused_credits': return `The AI tutor is paused (account credits ran out). ${CONTINUES}`; case 'paused_budget': { const back = resumeText(t.resume_at, now); return `The AI tutor has reached its spending limit for now. ${CONTINUES}${back ? ` Back around ${back}.` : ''}`; } case 'paused_rate': return 'The AI tutor is busy; trying again shortly.'; case 'paused_error': return `The AI tutor is unavailable right now. ${CONTINUES}`; default: return `The AI tutor is unavailable right now. ${CONTINUES}`; }}
/** "Spend today $1.23" for reviewers; null when the server did not say. */export function spendText(t: TutorStatus | null): string | null { const day = t?.spend_usd?.day; if (typeof day !== 'number' || !Number.isFinite(day)) return null; return `Spend today $${day.toFixed(2)}`;}
const SHOWING = 'Showing the built-in explanation instead.';const DEBRIEF_ERRORS: Record<string, string> = { offline: `The AI tutor is off. ${SHOWING}`, credits_depleted: `The AI tutor is paused (account credits ran out). ${SHOWING}`, rate_limited: `The AI tutor is busy. ${SHOWING}`, budget_exceeded: `The AI tutor has reached its spending limit for now. ${SHOWING}`, unavailable: `The AI tutor is unavailable right now. ${SHOWING}`, auth: `The AI tutor could not sign in to its service. ${SHOWING}`, validator_failed: `The AI tutor's draft did not pass our checks. ${SHOWING}`, timeout: `The AI tutor took too long. ${SHOWING}`, internal_error: `Something went wrong while writing the AI debrief. ${SHOWING}`,};const DEBRIEF_FAILED = 'The AI tutor is unavailable right now. The facts above are complete.';
/** * The one line above a debrief that did not come from the live tutor. `failed` = the request itself failed or the * server said status "failed" (then there may be no explanation to show at all). Unknown codes get the generic line. */export function debriefErrorText(d: Pick<DebriefResponse, 'status' | 'error' | 'debrief'> | null | undefined, failed: boolean): string | null { const code = (d?.error ?? '').trim().toLowerCase(); if (code && DEBRIEF_ERRORS[code]) return d?.debrief || !failed ? DEBRIEF_ERRORS[code] : DEBRIEF_ERRORS[code].replace(SHOWING, 'The facts above are complete.'); if (code || failed) return d?.debrief ? DEBRIEF_ERRORS.unavailable : DEBRIEF_FAILED; return null;}
/** Did this debrief resolve with a tutor problem worth re-checking the tutor status for? */export const debriefHadError = (d: Pick<DebriefResponse, 'status' | 'error'> | null | undefined, failed: boolean): boolean => failed || !!d?.error || d?.status === 'failed';1 unmodified line23456719 unmodified lines2728293031321 unmodified line// control and puts a small card beside it — never a full-screen overlay, so the film and every control stay usable// while it runs. Next / Back / Skip; ← → and Esc work while the card has focus.import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { availableSteps, markTutorialDone, placeCard, tourStep, type Rect, type Step } from './steps';import s from './Tutorial.module.css';19 unmodified linesconst end = (finished: boolean) => {markTutorialDone();onClose(finished);};const endRef = useRef(end);1 unmodified line234567819 unmodified lines282930313233341 unmodified line// control and puts a small card beside it — never a full-screen overlay, so the film and every control stay usable// while it runs. Next / Back / Skip; ← → and Esc work while the card has focus.import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { track } from '../analytics';import { availableSteps, markTutorialDone, placeCard, tourStep, type Rect, type Step } from './steps';import s from './Tutorial.module.css';19 unmodified linesconst end = (finished: boolean) => {markTutorialDone();if (finished) track('tutorial_done');onClose(finished);};const endRef = useRef(end);
9 unmodified lines1011121314159 unmodified linesoffline: boolean;cases: number;version?: string | null;}export interface SessionCreate {9 unmodified lines10111213141516171819202122232425262728293031323334359 unmodified linesoffline: boolean;cases: number;version?: string | null;tutor?: {mode: "live" | "offline" | "paused_credits" | "paused_budget" | "paused_rate" | "paused_error";reason?: string | null;/*** ISO time when live calls will be retried, if paused*/resume_at?: string | null;/*** hour, day, total (estimates from token counts)*/spend_usd?: {[k: string]: number;} | null;/*** hour, day, total limits*/budget_usd?: {[k: string]: number;} | null;} | null;}export interface SessionCreate {
405 unmodified lines406407408409410411412413414415416405 unmodified lines# --------------------------------------------------------------------------- api.jsonclass Health(_Strict):ok: booloffline: boolcases: intversion: str | None = Noneclass SessionCreate(_Strict):405 unmodified lines406407408409410411412413414415416417418419420421422423424425426427428405 unmodified lines# --------------------------------------------------------------------------- api.jsonTutorMode = Literal["live", "offline", "paused_credits", "paused_budget", "paused_rate", "paused_error"]class TutorStatus(_Strict):mode: TutorModereason: str | None = Noneresume_at: str | None = Nonespend_usd: dict[str, float] | None = Nonebudget_usd: dict[str, float] | None = Noneclass Health(_Strict):ok: booloffline: boolcases: intversion: str | None = Nonetutor: TutorStatus | None = Noneclass SessionCreate(_Strict):
1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263641 unmodified line"$schema": "https://json-schema.org/draft/2020-12/schema","$id": "https://blindspot.local/schemas/api.json","title": "BlindspotApi","description": "Smaller request/response shapes for the /api routes not covered by their own file. See docs/SPEC.md §13.","$defs": {"Level": {"type": "string", "enum": ["MS1", "MS2", "MS3", "MS4", "intern", "resident", "PA/NP student", "other"]},"Mode": {"type": "string", "enum": ["practice", "drill", "assess_A", "assess_B", "review"]},"Health": {"type": "object", "additionalProperties": false, "required": ["ok", "offline", "cases"],"properties": {"ok": {"type": "boolean"}, "offline": {"type": "boolean"}, "cases": {"type": "integer"}, "version": {"type": ["string", "null"], "default": null}}},"SessionCreate": {"type": "object", "additionalProperties": false, "required": ["display_name", "level", "mode"],"properties": {"display_name": {"type": "string", "minLength": 1, "maxLength": 80},"level": {"$ref": "#/$defs/Level"},"participant_code": {"type": ["string", "null"], "default": null},"mode": {"$ref": "#/$defs/Mode"},"settings": {"type": "object", "additionalProperties": true, "default": {},"description": "drill: {label}; practice: {prevalence_abnormal}; any: {projector: bool}"}}},"SessionCreated": {"type": "object", "additionalProperties": false, "required": ["session_id", "learner_id", "mode"],"properties": {"session_id": {"type": "string"}, "learner_id": {"type": "string"}, "mode": {"$ref": "#/$defs/Mode"}}},"NextCase": {"type": "object", "additionalProperties": false, "required": ["attempt_id", "case", "index"],"description": "INVARIANT: never contains ground truth (findings, is_normal, zones, masks, difficulty).","properties": {"attempt_id": {"type": "string"},"case": {"type": "object", "additionalProperties": false, "required": ["case_id", "image_url", "width", "height"],"properties": {"case_id": {"type": "string"}, "image_url": {"type": "string"}, "width": {"type": "integer"}, "height": {"type": "integer"}}},"index": {"type": "integer"},"total": {"type": ["integer", "null"], "default": null},"hints_enabled": {"type": "boolean", "default": true},"done": {"type": "boolean", "default": false}}},"HintRequest": {"type": "object", "additionalProperties": false, "required": ["marks", "telemetry"],"properties": {"marks": {"type": "array", "items": {"$ref": "attempt_submit.json#/$defs/Mark"}}, "telemetry": {"type": "array", "items": {"$ref": "telemetry_event.json"}}}},"HintResponse": {"type": "object", "additionalProperties": false, "required": ["level", "text", "remaining"],"properties": {"level": {"type": "integer", "minimum": 1, "maximum": 3}, "text": {"type": "string"}, "remaining": {"type": "integer", "minimum": 0}}},"AskRequest": {"type": "object", "additionalProperties": false, "required": ["question"],"properties": {"question": {"type": "string", "minLength": 1, "maxLength": 500}}},"AskResponse": {"type": "object", "additionalProperties": false, "required": ["answer", "remaining"],"properties": {"answer": {"type": "string"}, "remaining": {"type": "integer"}, "source": {"type": "string", "enum": ["live", "template"], "default": "live"}}},"AssessmentRecorded": {"type": "object", "additionalProperties": false, "required": ["recorded"],"properties": {"recorded": {"type": "boolean", "const": true}, "index": {"type": "integer"}, "total": {"type": "integer"}}},"AssessmentSummary": {"type": "object", "additionalProperties": true, "required": ["session_id", "mode", "n_cases", "sensitivity", "specificity", "localization_fraction", "false_positives_per_image", "miss_type_mix", "score_mean"],"properties": {"session_id": {"type": "string"}, "mode": {"$ref": "#/$defs/Mode"}, "n_cases": {"type": "integer"},"sensitivity": {"type": ["number", "null"]}, "specificity": {"type": ["number", "null"]},"localization_fraction": {"type": ["number", "null"]}, "false_positives_per_image": {"type": "number"},"miss_type_mix": {"type": "object", "additionalProperties": {"type": "integer"}},"score_mean": {"type": "number"},"cases": {"type": "array", "items": {"type": "object", "additionalProperties": true}}}},"ReviewRating": {"type": "object", "additionalProperties": false, "required": ["reviewer", "role", "item_type", "item_id", "accuracy", "teaching", "safety_flag"],"properties": {"reviewer": {"type": "string"}, "role": {"type": "string"},"item_type": {"type": "string", "enum": ["debrief", "card"]}, "item_id": {"type": "string"},"accuracy": {"type": "integer", "minimum": 1, "maximum": 5}, "teaching": {"type": "integer", "minimum": 1, "maximum": 5},"safety_flag": {"type": "boolean"}, "comment": {"type": ["string", "null"], "default": null},"card_edits": {"type": ["object", "null"], "additionalProperties": true, "default": null}}},"SusSubmit": {"type": "object", "additionalProperties": false, "required": ["learner_id", "answers"],"properties": {"learner_id": {"type": "string"}, "answers": {"type": "array", "items": {"type": "integer", "minimum": 1, "maximum": 5}, "minItems": 10, "maxItems": 10}}},"SusResult": {"type": "object", "additionalProperties": false, "required": ["score"], "properties": {"score": {"type": "number"}}}}}1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894901 unmodified line"$schema": "https://json-schema.org/draft/2020-12/schema","$id": "https://blindspot.local/schemas/api.json","title": "BlindspotApi","description": "Smaller request/response shapes for the /api routes not covered by their own file. See docs/SPEC.md \u00a713.","$defs": {"Level": {"type": "string","enum": ["MS1","MS2","MS3","MS4","intern","resident","PA/NP student","other"]},"Mode": {"type": "string","enum": ["practice","drill","assess_A","assess_B","review"]},"Health": {"type": "object","additionalProperties": false,"required": ["ok","offline","cases"],"properties": {"ok": {"type": "boolean"},"offline": {"type": "boolean"},"cases": {"type": "integer"},"version": {"type": ["string","null"],"default": null},"tutor": {"type": ["object","null"],"default": null,"additionalProperties": false,"required": ["mode"],"properties": {"mode": {"type": "string","enum": ["live","offline","paused_credits","paused_budget","paused_rate","paused_error"]},"reason": {"type": ["string","null"],"default": null},"resume_at": {"type": ["string","null"],"default": null,"description": "ISO time when live calls will be retried, if paused"},"spend_usd": {"type": ["object","null"],"default": null,"additionalProperties": {"type": "number"},"description": "hour, day, total (estimates from token counts)"},"budget_usd": {"type": ["object","null"],"default": null,"additionalProperties": {"type": "number"},"description": "hour, day, total limits"}}}}},"SessionCreate": {"type": "object","additionalProperties": false,"required": ["display_name","level","mode"],"properties": {"display_name": {"type": "string","minLength": 1,"maxLength": 80},"level": {"$ref": "#/$defs/Level"},"participant_code": {"type": ["string","null"],"default": null},"mode": {"$ref": "#/$defs/Mode"},"settings": {"type": "object","additionalProperties": true,"default": {},"description": "drill: {label}; practice: {prevalence_abnormal}; any: {projector: bool}"}}},"SessionCreated": {"type": "object","additionalProperties": false,"required": ["session_id","learner_id","mode"],"properties": {"session_id": {"type": "string"},"learner_id": {"type": "string"},"mode": {"$ref": "#/$defs/Mode"}}},"NextCase": {"type": "object","additionalProperties": false,"required": ["attempt_id","case","index"],"description": "INVARIANT: never contains ground truth (findings, is_normal, zones, masks, difficulty).","properties": {"attempt_id": {"type": "string"},"case": {"type": "object","additionalProperties": false,"required": ["case_id","image_url","width","height"],"properties": {"case_id": {"type": "string"},"image_url": {"type": "string"},"width": {"type": "integer"},"height": {"type": "integer"}}},"index": {"type": "integer"},"total": {"type": ["integer","null"],"default": null},"hints_enabled": {"type": "boolean","default": true},"done": {"type": "boolean","default": false}}},"HintRequest": {"type": "object","additionalProperties": false,"required": ["marks","telemetry"],"properties": {"marks": {"type": "array","items": {"$ref": "attempt_submit.json#/$defs/Mark"}},"telemetry": {"type": "array","items": {"$ref": "telemetry_event.json"}}}},"HintResponse": {"type": "object","additionalProperties": false,"required": ["level","text","remaining"],"properties": {"level": {"type": "integer","minimum": 1,"maximum": 3},"text": {"type": "string"},"remaining": {"type": "integer","minimum": 0}}},"AskRequest": {"type": "object","additionalProperties": false,"required": ["question"],"properties": {"question": {"type": "string","minLength": 1,"maxLength": 500}}},"AskResponse": {"type": "object","additionalProperties": false,"required": ["answer","remaining"],"properties": {"answer": {"type": "string"},"remaining": {"type": "integer"},"source": {"type": "string","enum": ["live","template"],"default": "live"}}},"AssessmentRecorded": {"type": "object","additionalProperties": false,"required": ["recorded"],"properties": {"recorded": {"type": "boolean","const": true},"index": {"type": "integer"},"total": {"type": "integer"}}},"AssessmentSummary": {"type": "object","additionalProperties": true,"required": ["session_id","mode","n_cases","sensitivity","specificity","localization_fraction","false_positives_per_image","miss_type_mix","score_mean"],"properties": {"session_id": {"type": "string"},"mode": {"$ref": "#/$defs/Mode"},"n_cases": {"type": "integer"},"sensitivity": {"type": ["number","null"]},"specificity": {"type": ["number","null"]},"localization_fraction": {"type": ["number","null"]},"false_positives_per_image": {"type": "number"},"miss_type_mix": {"type": "object","additionalProperties": {"type": "integer"}},"score_mean": {"type": "number"},"cases": {"type": "array","items": {"type": "object","additionalProperties": true}}}},"ReviewRating": {"type": "object","additionalProperties": false,"required": ["reviewer","role","item_type","item_id","accuracy","teaching","safety_flag"],"properties": {"reviewer": {"type": "string"},"role": {"type": "string"},"item_type": {"type": "string","enum": ["debrief","card"]},"item_id": {"type": "string"},"accuracy": {"type": "integer","minimum": 1,"maximum": 5},"teaching": {"type": "integer","minimum": 1,"maximum": 5},"safety_flag": {"type": "boolean"},"comment": {"type": ["string","null"],"default": null},"card_edits": {"type": ["object","null"],"additionalProperties": true,"default": null}}},"SusSubmit": {"type": "object","additionalProperties": false,"required": ["learner_id","answers"],"properties": {"learner_id": {"type": "string"},"answers": {"type": "array","items": {"type": "integer","minimum": 1,"maximum": 5},"minItems": 10,"maxItems": 10}}},"SusResult": {"type": "object","additionalProperties": false,"required": ["score"],"properties": {"score": {"type": "number"}}}}}
295 unmodified lines2962972982993003013023033043055 unmodified lines311312313314315316317318295 unmodified lines};const TAG_CASES = [{ name: 'live + student reviewed', body: { status: 'ready', source: 'live', provenance: 'student_reviewed', debrief: DEBRIEF }, source: 'Claude debrief', prov: 'Student reviewed', busy: false },{ name: 'cache + radiologist reviewed', body: { status: 'ready', source: 'cache', provenance: 'radiologist_reviewed', debrief: DEBRIEF }, source: 'Claude (cached)', prov: 'Radiologist reviewed', busy: false },{ name: 'rate limited → built-in', body: { status: 'ready', source: 'template', provenance: 'ai_draft', error: 'rate_limited', debrief: DEBRIEF }, source: 'Built-in', prov: 'AI draft — not yet reviewed', busy: true },{ name: 'failed', body: { status: 'failed', error: 'LiveCallError' }, source: null, prov: null, busy: true },];for (const c of TAG_CASES) {5 unmodified linesif (c.source) await expect(panel.getByTestId('debrief-source')).toHaveText(c.source);else await expect(panel.getByTestId('debrief-source')).toHaveCount(0);if (c.prov) await expect(panel.getByTestId('provenance')).toHaveText(c.prov);if (c.busy) await expect(panel.getByTestId('debrief-busy')).toHaveText('The tutor is busy. Showing the built-in explanation instead.');else await expect(panel.getByTestId('debrief-busy')).toHaveCount(0);if (c.body.debrief) await expect(panel).toContainText('Check both apices');if (c.name.startsWith('live')) {await page.waitForTimeout(1400); // let the reveal settle so the shot shows outlines and the full rail295 unmodified lines2962972982993003013023033043055 unmodified lines311312313314315316317318319295 unmodified lines};const TAG_CASES = [{ name: 'live + student reviewed', body: { status: 'ready', source: 'live', provenance: 'student_reviewed', debrief: DEBRIEF }, source: 'Claude debrief', prov: 'Student reviewed', busy: null },{ name: 'cache + radiologist reviewed', body: { status: 'ready', source: 'cache', provenance: 'radiologist_reviewed', debrief: DEBRIEF }, source: 'Claude (cached)', prov: 'Radiologist reviewed', busy: null },{ name: 'rate limited → built-in', body: { status: 'ready', source: 'template', provenance: 'ai_draft', error: 'rate_limited', debrief: DEBRIEF }, source: 'Built-in', prov: 'AI draft — not yet reviewed', busy: 'The AI tutor is busy. Showing the built-in explanation instead.' },{ name: 'failed', body: { status: 'failed', error: 'LiveCallError' }, source: null, prov: null, busy: 'The AI tutor is unavailable right now. The facts above are complete.' },];for (const c of TAG_CASES) {5 unmodified linesif (c.source) await expect(panel.getByTestId('debrief-source')).toHaveText(c.source);else await expect(panel.getByTestId('debrief-source')).toHaveCount(0);if (c.prov) await expect(panel.getByTestId('provenance')).toHaveText(c.prov);if (c.busy) await expect(panel.getByTestId('debrief-busy')).toHaveText(c.busy);else await expect(panel.getByTestId('debrief-busy')).toHaveCount(0);await expect(panel).not.toContainText('LiveCallError');if (c.body.debrief) await expect(panel).toContainText('Check both apices');if (c.name.startsWith('live')) {await page.waitForTimeout(1400); // let the reveal settle so the shot shows outlines and the full rail
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188// Tutor status banner and per-debrief tutor lines. Author: frontend-engineer (qa-reviewer owns this directory).// Always the real API (?mock=0): /api/health is mocked per mode with page.route (page.route only sees real network// calls), everything else reaches the throwaway API. Also checks that nothing analytics-shaped leaves an automated// browser (navigator.webdriver is set under Playwright).import { expect, test, type Page, type Route } from '@playwright/test';
const SHOTS = 'tests/e2e/__screenshots__';const shot = (page: Page, name: string) => page.screenshot({ path: `${process.cwd().endsWith('frontend') ? '../' : ''}${SHOTS}/live-tutor-${name}.png` });
test.use({ viewport: { width: 1280, height: 800 } });
const json = (route: Route, status: number, body: unknown) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
type Tutor = { mode: string; reason?: string | null; resume_at?: string | null; spend_usd?: Record<string, number> | null };
/** Serve /api/health with the given tutor block; everything else passes through to the real API. */async function mockHealth(page: Page, tutor: Tutor | null, extra: Record<string, unknown> = {}) { await page.route((url) => url.pathname.endsWith('/api/health'), (route) => json(route, 200, { ok: true, offline: tutor?.mode !== 'live', cases: 3000, version: 'e2e', tutor, ...extra }));}
async function filmReady(page: Page) { await expect(page.getByTestId('film')).toBeVisible(); await page.waitForFunction(() => { const img = document.querySelector<HTMLImageElement>('[data-testid=film]'); return !!img && img.complete && img.naturalWidth > 0; });}
async function startPractice(page: Page) { await page.goto('/start?mock=0'); await page.getByTestId('name').fill('E2E tutor status (test)'); await page.getByTestId('start').click(); await filmReady(page);}
async function submitNormal(page: Page) { await page.mouse.move(2, 400); await page.keyboard.press('n'); await page.keyboard.press('3'); await page.getByTestId('submit').click(); await expect(page.getByTestId('outcomes')).toBeVisible();}
const MODES: { mode: string; text: string; resume_at?: string }[] = [ { mode: 'offline', text: 'The AI tutor is off. You still get the built-in explanation after every film.' }, { mode: 'paused_credits', text: 'The AI tutor is paused (account credits ran out). Built-in explanations continue.' }, { mode: 'paused_budget', text: 'The AI tutor has reached its spending limit for now. Built-in explanations continue.' }, { mode: 'paused_rate', text: 'The AI tutor is busy; trying again shortly.' }, { mode: 'paused_error', text: 'The AI tutor is unavailable right now. Built-in explanations continue.' },];
for (const m of MODES) { test(`start page banner: ${m.mode}`, async ({ page }) => { await mockHealth(page, { mode: m.mode, reason: 'e2e' }); await page.goto('/start?mock=0'); const notice = page.getByTestId('tutor-notice'); await expect(notice).toHaveText(m.text); await expect(notice).toHaveAttribute('data-mode', m.mode); // Not a reviewer: no spend line, and the raw mode never shows as text. await expect(page.getByTestId('tutor-spend')).toHaveCount(0); await expect(notice).not.toContainText(m.mode); // The start button is still usable: the banner blocks nothing. await expect(page.getByTestId('start')).toBeEnabled(); if (m.mode === 'paused_credits') await shot(page, 'start-paused-credits'); });}
test('live: no banner anywhere; the library line stays', async ({ page }) => { await mockHealth(page, { mode: 'live' }); await page.goto('/start?mock=0'); await expect(page.getByTestId('health')).toContainText('Library: 3,000 chest films'); await expect(page.getByTestId('tutor-notice')).toHaveCount(0); await page.getByTestId('name').fill('E2E tutor live (test)'); await page.getByTestId('start').click(); await filmReady(page); await expect(page.getByTestId('tutor-notice')).toHaveCount(0);});
test('a health without a tutor block falls back to the offline flag', async ({ page }) => { await mockHealth(page, null, { offline: true }); await page.goto('/start?mock=0'); await expect(page.getByTestId('tutor-notice')).toHaveText('The AI tutor is off. You still get the built-in explanation after every film.');});
test('paused_budget says when it is back, in local time', async ({ page }) => { const resume = new Date(Date.now() + 90 * 60_000); await mockHealth(page, { mode: 'paused_budget', resume_at: resume.toISOString() }); await page.goto('/start?mock=0'); const expected = await page.evaluate((iso) => new Date(iso).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }), resume.toISOString()); await expect(page.getByTestId('tutor-notice')).toHaveText( `The AI tutor has reached its spending limit for now. Built-in explanations continue. Back around ${expected}.`, );});
test('reading room: the banner sits at the top of the rail, before and after submit; reviewers see the spend', async ({ page }) => { await mockHealth(page, { mode: 'paused_budget', reason: 'day budget', spend_usd: { hour: 0.12, day: 1.5, total: 9.87 }, budget_usd: { day: 1.5 } }); await page.route((url) => url.pathname.endsWith('/api/access') && !url.pathname.includes('review'), (route) => route.request().method() === 'GET' ? json(route, 200, { access_required: false, access_granted: true, review_required: true, review_granted: true, base_path: '' }) : route.fallback()); await startPractice(page); const rail = page.getByRole('complementary', { name: 'Your read and feedback' }); const notice = rail.getByTestId('tutor-notice'); await expect(notice).toContainText('The AI tutor has reached its spending limit for now. Built-in explanations continue.'); await expect(notice.getByTestId('tutor-spend')).toHaveText('Spend today $1.50'); // Above "Your read": the first thing in the rail body. const order = await rail.evaluate((el) => { const n = el.querySelector('[data-testid=tutor-notice]')!; const h = el.querySelector('h2')!; return n.compareDocumentPosition(h) & Node.DOCUMENT_POSITION_FOLLOWING ? 'notice-first' : 'heading-first'; }); expect(order).toBe('notice-first'); await shot(page, 'reading-room-paused-budget'); await submitNormal(page); await expect(rail.getByTestId('tutor-notice')).toBeVisible(); await expect(rail.getByRole('heading', { name: 'The expert read' })).toBeVisible();});
test('reading room: no spend line without the review cookie', async ({ page }) => { await mockHealth(page, { mode: 'paused_error', spend_usd: { day: 2 } }); await startPractice(page); await expect(page.getByTestId('tutor-notice')).toHaveText('The AI tutor is unavailable right now. Built-in explanations continue.'); await expect(page.getByTestId('tutor-spend')).toHaveCount(0);});
const DEBRIEF = { headline: 'You called this film normal.', verdict: 'correct_normal', findings: [], overcalls: [], search_coaching: 'Check both apices before you call a film normal.', calibration_note: '', next_step: 'Keep reading.', fact_ids: [],};
const DEBRIEF_LINES: [string, string][] = [ ['credits_depleted', 'The AI tutor is paused (account credits ran out). Showing the built-in explanation instead.'], ['budget_exceeded', 'The AI tutor has reached its spending limit for now. Showing the built-in explanation instead.'], ['offline', 'The AI tutor is off. Showing the built-in explanation instead.'], ['timeout', 'The AI tutor took too long. Showing the built-in explanation instead.'], ['auth', 'The AI tutor could not sign in to its service. Showing the built-in explanation instead.'], ['validator_failed', "The AI tutor's draft did not pass our checks. Showing the built-in explanation instead."],];
for (const [code, line] of DEBRIEF_LINES) { test(`debrief line: ${code}`, async ({ page }) => { let healthCalls = 0; await page.route((url) => url.pathname.endsWith('/api/health'), (route) => { healthCalls += 1; return json(route, 200, { ok: true, offline: false, cases: 3000, tutor: { mode: 'live' } }); }); await page.route('**/api/attempts/*/debrief', (route) => json(route, 200, { status: 'ready', source: 'template', provenance: 'ai_draft', error: code, debrief: DEBRIEF })); await startPractice(page); const before = healthCalls; await submitNormal(page); const panel = page.getByTestId('debrief'); await expect(panel.getByTestId('debrief-busy')).toHaveText(line); await expect(panel.getByTestId('debrief-source')).toHaveText('Built-in'); await expect(panel).toContainText('Check both apices'); await expect(panel).not.toContainText(code); // A debrief that ended in a tutor problem re-checks the tutor status right away. await expect.poll(() => healthCalls).toBeGreaterThan(before); if (code === 'credits_depleted') { await page.waitForTimeout(1400); // let the reveal settle so the rail is in the shot await panel.scrollIntoViewIfNeeded(); await shot(page, 'debrief-credits-depleted'); } });}
test('an unknown error code never reaches the screen', async ({ page }) => { await page.route('**/api/attempts/*/debrief', (route) => json(route, 200, { status: 'ready', source: 'template', provenance: 'ai_draft', error: 'SomeNewInternalCode', debrief: DEBRIEF })); await startPractice(page); await submitNormal(page); const panel = page.getByTestId('debrief'); await expect(panel.getByTestId('debrief-busy')).toHaveText('The AI tutor is unavailable right now. Showing the built-in explanation instead.'); await expect(panel).not.toContainText('SomeNewInternalCode');});
test('analytics: nothing leaves an automated browser, and About says what is counted', async ({ page }) => { const hits: string[] = []; page.on('request', (r) => { if (r.url().includes('/analytics/')) hits.push(r.url()); }); await startPractice(page); await page.goto('/about?mock=0'); await expect(page.getByTestId('about-analytics')).toHaveText('We count page views and clicks with an anonymous browser id. No names, marks or answers are sent.'); expect(hits).toEqual([]); expect(await page.evaluate(() => localStorage.getItem('ys-analytics-id'))).toBeNull();});frontend/src/main.tsx+4
frontend/src/pages/AboutPage.tsx+1
frontend/src/pages/OnboardingPage.tsx+2
frontend/src/pages/ReadPage.tsx+5-1
frontend/src/pages/ServerLine.tsx+5-4
frontend/src/pages/SessionSummaryView.tsx+3
frontend/src/pages/Start.module.css+3
frontend/src/pages/StartPage.tsx+4
frontend/src/rail/AskTutor.tsx+2-1
frontend/src/rail/DebriefPanel.tsx+23-9
frontend/src/rail/Rail.module.css+3
frontend/src/rail/debriefCopy.ts-1
frontend/src/reference/ReferenceDrawer.tsx+2
frontend/src/tutor/TutorNotice.module.cssAdded+12
frontend/src/tutor/TutorNotice.tsxAdded+21
frontend/src/tutor/health.tsAdded+22
frontend/src/tutor/status.test.tsAdded+82
frontend/src/tutor/status.tsAdded+78
frontend/src/tutorial/Tutorial.tsx+2
frontend/src/types/contracts.ts+20
shared/contracts.py+12
shared/schemas/api.json+478-52
tests/e2e/general_use.spec.ts+6-5
tests/e2e/tutor_status.spec.tsAdded+188