Study/web/src/features/SharedAssistant.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

152 lines
7 KiB
TypeScript

import { CornerDownLeft, Sparkles, Square, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
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, Tooltip } from '@/ui';
import { ToolSteps } from './ToolSteps';
type Event = { type: 'text'; delta: string } | { type: 'tool'; tool: ToolActivity } | { type: 'error'; message: string } | { type: 'done' };
interface Turn {
role: 'user' | 'assistant';
text: string;
tools?: ToolActivity[];
}
/**
* The visitor-facing assistant on a share link (when the owner allows it). It answers from the
* shared material only; the conversation lives in this tab and is never saved on the server.
* `hidden` tucks it away (during a quiz or flashcard session) without losing the conversation.
*/
export function SharedAssistant({ token, title, item, hidden }: { token: string; title: string; item?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string }; hidden?: boolean }) {
const [open, setOpen] = useState(false);
const [turns, setTurns] = useState<Turn[]>([]);
const [input, setInput] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const abort = useRef<AbortController | null>(null);
const list = useRef<HTMLDivElement>(null);
useEffect(() => () => abort.current?.abort(), []);
useEffect(() => {
const el = list.current;
if (el) el.scrollTop = el.scrollHeight;
}, [turns, open]);
const send = useCallback(
async (text: string) => {
if (busy) return;
// The server accepts the last 16 turns; older ones are dropped from the request.
const history: Turn[] = [...turns, { role: 'user' as const, text }].slice(-15);
setTurns([...turns, { role: 'user', text }, { role: 'assistant', text: '', tools: [] }]);
setBusy(true);
setError('');
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>(
`/api/public/${token}/chat`,
{ messages: history.filter((t) => t.text.trim()).map((t) => ({ role: t.role, text: t.text })), item },
(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);
// Drop an empty reply so the next request stays valid.
setTurns((t) => (t[t.length - 1]?.role === 'assistant' && !t[t.length - 1].text ? t.slice(0, -1) : t));
}
},
[busy, turns, token, item],
);
const genUi = useMemo(() => ({ streaming: busy, onSend: (text: string) => void send(text.slice(0, 4000)) }), [busy, send]);
if (hidden) return null;
if (!open) {
// The same round sparkle button the owner sees in the app.
return (
<Tooltip label="Ask the assistant" side="left">
<button
type="button"
aria-label="Open the assistant"
onClick={() => setOpen(true)}
className="fixed right-5 bottom-[max(1.25rem,env(safe-area-inset-bottom))] z-40 grid size-11 place-items-center rounded-full border border-line-strong bg-surface/90 text-ink-2 shadow-1 backdrop-blur transition-colors hover:border-ink-3 hover:text-ink"
>
<Sparkles className="size-[19px]" />
</button>
</Tooltip>
);
}
return (
<section aria-label="Study assistant" className="fixed right-4 bottom-4 z-40 flex h-[min(620px,calc(100dvh-2rem))] w-[min(440px,calc(100vw-2rem))] animate-in flex-col overflow-hidden rounded-[18px] border border-line bg-surface shadow-3 sm:right-6">
<header className="flex items-center gap-2 border-b border-line px-3 py-2.5">
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-ink text-marker">
<Sparkles className="size-4" />
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold">Assistant</div>
<div className="truncate text-xs text-ink-3">{title}</div>
</div>
<IconButton label="Close" size="sm" onClick={() => setOpen(false)}>
<X />
</IconButton>
</header>
<div ref={list} className="flex-1 space-y-4 overflow-y-auto px-4 py-3">
{turns.length === 0 && <p className="text-[13.5px] text-ink-2">Ask a question about this material: what something means, why an answer is right, or for a quick recap.</p>}
<GenUiContext.Provider value={genUi}>
{turns.map((t, i) =>
t.role === 'user' ? (
<div key={i} className="flex justify-end">
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2 text-[14px] whitespace-pre-wrap text-paper">{t.text}</div>
</div>
) : (
<div key={i} className="space-y-2">
{t.tools && t.tools.length > 0 && <ToolSteps tools={t.tools} compact />}
{t.text ? (
<Markdown className="text-[14px]">{t.text}</Markdown>
) : busy && i === turns.length - 1 && !t.tools?.some((x) => x.status === 'running') ? (
<Spinner className="size-4" label="Thinking" />
) : null}
</div>
),
)}
</GenUiContext.Provider>
{error && (
<Callout tone="bad" className="py-2">
{error}
</Callout>
)}
</div>
<form
className="flex gap-2 border-t border-line p-3"
onSubmit={(e) => {
e.preventDefault();
if (busy) return abort.current?.abort();
const text = input.trim();
if (!text) return;
setInput('');
void send(text.slice(0, 4000));
}}
>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Ask a question…"
aria-label="Your question"
className={cx('h-10 min-w-0 flex-1 rounded-[10px] border border-line-strong bg-paper px-3 text-sm outline-none focus:border-accent')}
/>
<Button type="submit" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Send'}>
{busy ? 'Stop' : 'Send'}
</Button>
</form>
<p className="px-4 pb-2.5 text-[11px] text-ink-3">AI can be wrong. Nothing you type here is saved.</p>
</section>
);
}