Study/web/src/features/Explain.tsx
Elijah c595e0ff2c
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
- Built-in Parallel web search (keyless; optional sign-in for higher limits and research)
  with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any
  MCP server, with token refresh and pre-registered client support
- Friendly tool steps (icon, name, status; details on click) and ids stripped from results;
  per-chat tool switches; taller thinking box
- Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only
  material for generation; class setting for what the groups are called
- Assistant can ask clarifying questions in an inline form before generating
- OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats
- Explain beside the quiz on wide screens, grounded in the cited source pages
- Quiz results: percentage ring coloured by score band, rainbow at 100
- Share links: assistant button like the owner's, hidden during quizzes; documents readable
  in the browser
- Live draft and library updates over server-sent events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:30:00 -07:00

177 lines
7.4 KiB
TypeScript

import { CornerDownLeft, PanelRightClose, Sparkles, Square } from 'lucide-react';
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { errorMessage, streamEvents } from '@/lib/api';
import type { ToolActivity } from '@/lib/types';
import { cx } from '@/lib/util';
import { GenUiContext, Markdown } from '@/ui/Markdown';
import { Button, Callout, IconButton, Spinner } from '@/ui';
import { ToolSteps } from './ToolSteps';
type ExplainBody =
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string; quizId?: string }
| { kind: 'card'; front: string; back: string }
| { kind: 'text'; text: string }
// On a share link the item is named by id; the server loads its content.
| { kind: 'question'; quizId: string; questionId: string; selected?: string[] }
| { kind: 'card'; deckId: string; cardId: string };
type Event = { type: 'text'; delta: string } | { type: 'tool'; tool: ToolActivity } | { type: 'error'; message: string } | { type: 'done' };
interface Turn {
ask?: string;
text: string;
tools: ToolActivity[];
}
/**
* Set by the quiz runner: on wide screens the explanation opens in the empty space to the right
* of the question instead of below it.
*/
export const ExplainSideContext = createContext(false);
/** Width available beside a centred 48rem column, or 0 when there is not enough room. */
function useSideRoom(enabled: boolean): number {
const measure = () => (typeof window === 'undefined' ? 0 : Math.floor((window.innerWidth - 768) / 2 - 44));
const [room, setRoom] = useState(measure);
useEffect(() => {
if (!enabled) return;
const onResize = () => setRoom(measure());
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, [enabled]);
return enabled && room >= 300 ? Math.min(room, 520) : 0;
}
/** "Explain with AI": streams a short explanation and accepts follow-up questions. */
export function Explain({ body, label = 'Explain with AI', className, url = '/api/ai/explain' }: { body: ExplainBody; label?: string; className?: string; url?: string }) {
const [open, setOpen] = useState(false);
const [turns, setTurns] = useState<Turn[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [ask, setAsk] = useState('');
const abort = useRef<AbortController | null>(null);
const key = JSON.stringify(body);
const sideWidth = useSideRoom(useContext(ExplainSideContext));
useEffect(() => {
// A different question: start over.
abort.current?.abort();
setOpen(false);
setTurns([]);
setError('');
setAsk('');
}, [key]);
useEffect(() => () => abort.current?.abort(), []);
const run = useCallback(
async (question?: string) => {
setOpen(true);
setBusy(true);
setError('');
setTurns((t) => [...t, { ask: question, text: '', tools: [] }]);
const controller = new AbortController();
abort.current = controller;
const patchLast = (fn: (t: Turn) => Turn) => setTurns((t) => t.map((x, i) => (i === t.length - 1 ? fn(x) : x)));
try {
await streamEvents<Event>(
url,
{ ...body, ask: question },
(e) => {
if (e.type === 'text') patchLast((x) => ({ ...x, text: x.text + e.delta }));
else if (e.type === 'tool') patchLast((x) => ({ ...x, tools: x.tools.some((t) => t.id === e.tool.id) ? x.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...x.tools, e.tool] }));
else if (e.type === 'error') setError(e.message);
},
controller.signal,
);
} catch (e) {
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
} finally {
setBusy(false);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[key, url],
);
const onSend = useCallback((text: string) => !busy && void run(text.slice(0, 500)), [busy, run]);
const genUi = useMemo(() => ({ streaming: busy, onSend }), [busy, onSend]);
if (!open) {
return (
<Button size="sm" variant="ghost" icon={<Sparkles />} className={className} onClick={() => (turns.length ? setOpen(true) : run())}>
{turns.length ? 'Show the explanation' : label}
</Button>
);
}
const panel: ReactNode = (
<div className={cx('rounded-xl border border-accent/25 p-4', sideWidth > 0 ? 'flex max-h-full flex-col bg-surface shadow-2' : 'bg-accent-soft/50')}>
<div className="eyebrow mb-2 flex shrink-0 items-center gap-1.5 text-accent">
<Sparkles className="size-3.5" /> <span className="flex-1">AI explanation</span>
{sideWidth > 0 && (
<IconButton label="Close the explanation" size="sm" onClick={() => setOpen(false)} className="-my-1 text-ink-3">
<PanelRightClose />
</IconButton>
)}
</div>
<GenUiContext.Provider value={genUi}>
<div className={cx('space-y-3', sideWidth > 0 && 'min-h-0 flex-1 overflow-y-auto pr-1')}>
{turns.map((t, i) => (
<div key={i} className="space-y-1.5">
{t.ask && <div className="mb-1 text-[13px] font-medium text-ink-2">{t.ask}</div>}
{t.tools.length > 0 && <ToolSteps tools={t.tools} compact />}
{t.text ? <Markdown className="text-[14.5px]">{t.text}</Markdown> : busy && i === turns.length - 1 && !t.tools.some((x) => x.status === 'running') ? <Spinner className="size-4" label="Thinking" /> : null}
</div>
))}
</div>
</GenUiContext.Provider>
{error && (
<Callout tone="bad" className="mt-3 py-2">
{error}
</Callout>
)}
<form
className="mt-3 flex shrink-0 gap-2"
onSubmit={(e) => {
e.preventDefault();
if (busy) return abort.current?.abort();
const question = ask.trim();
if (!question) return;
setAsk('');
void run(question);
}}
>
<input
value={ask}
onChange={(e) => setAsk(e.target.value)}
placeholder="Ask a follow-up…"
aria-label="Follow-up question"
className="h-9 min-w-0 flex-1 rounded-[9px] border border-line-strong bg-surface px-3 text-sm outline-none focus:border-accent"
/>
<Button type="submit" size="sm" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Ask'}>
{busy ? 'Stop' : 'Ask'}
</Button>
</form>
<p className="mt-2 shrink-0 text-[11px] text-ink-3">AI can be wrong. Check anything important against your course material.</p>
</div>
);
if (sideWidth > 0) {
// Wide screens: the explanation sits in the free space right of the question.
return (
<>
<div className={cx('flex items-center gap-1.5 text-[13px] text-ink-3', className)}>
<Sparkles className="size-3.5 text-accent" /> Explanation is open on the right
</div>
{createPortal(
<aside aria-label="AI explanation" className="fixed top-[72px] bottom-[84px] z-30 flex animate-in flex-col" style={{ right: 20, width: sideWidth }}>
{panel}
</aside>,
document.body,
)}
</>
);
}
return <div className={className}>{panel}</div>;
}