Third revision: web search, MCP sign-in, exams, intelligent UI, clarifying questions
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s

- 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>
This commit is contained in:
Elijah 2026-11-15 20:30:00 -07:00
parent 60cf2322f7
commit c595e0ff2c
54 changed files with 4710 additions and 387 deletions

View file

@ -6,11 +6,11 @@ import { toast } from 'sonner';
import { CLASS_COLORS, type ClassColor } from '@shared/content';
import { api, errorMessage } from '@/lib/api';
import { assistant, useAssistantState } from '@/lib/assistantStore';
import { qk, useClasses, useOverview, useRefresh } from '@/lib/queries';
import { qk, useClasses, useLiveChanges, useOverview, useRefresh } from '@/lib/queries';
import type { ClassInfo, SearchHit } from '@/lib/types';
import { cx, useDebounced, useHotkeys, useIsDesktop, useTheme, type ThemeChoice } from '@/lib/util';
import { Brand } from '@/pages/Auth';
import { Button, ClassDot, Dialog, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea, Tooltip } from '@/ui';
import { Button, ClassDot, Dialog, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea, Tooltip, Select } from '@/ui';
import { SidebarDrafts, useDraftNotifications } from '@/features/DraftsTray';
const AssistantPanel = lazy(() => import('@/features/AssistantPanel'));
@ -24,6 +24,7 @@ export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; o
const [code, setCode] = useState('');
const [description, setDescription] = useState('');
const [color, setColor] = useState<ClassColor | null>(null);
const [groupLabel, setGroupLabel] = useState('Exam');
const [busy, setBusy] = useState(false);
useEffect(() => {
@ -32,6 +33,7 @@ export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; o
setCode(existing?.code ?? '');
setDescription(existing?.description ?? '');
setColor(existing?.color ?? null);
setGroupLabel(existing?.groupLabel ?? 'Exam');
}, [open, existing]);
const save = async () => {
@ -39,10 +41,10 @@ export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; o
setBusy(true);
try {
if (existing) {
await api.patch(`/api/classes/${existing.id}`, { name, code, description, color: color ?? existing.color });
await api.patch(`/api/classes/${existing.id}`, { name, code, description, color: color ?? existing.color, groupLabel });
toast.success('Class updated');
} else {
const res = await api.post<{ class: ClassInfo }>('/api/classes', { name, code, description, color: color ?? undefined });
const res = await api.post<{ class: ClassInfo }>('/api/classes', { name, code, description, color: color ?? undefined, groupLabel });
navigate(`/classes/${res.class.id}`);
}
await refresh();
@ -89,6 +91,15 @@ export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; o
<Field label="Description" optional>
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} rows={2} maxLength={2000} />
</Field>
<Field label="Divided into" hint="Each one keeps its own documents, quizzes and flashcards, and generating uses only its material.">
<Select value={groupLabel} onChange={(e) => setGroupLabel(e.target.value)}>
{['Exam', 'Unit', 'Module', 'Week', 'Topic', 'Folder'].map((l) => (
<option key={l} value={l}>
{l}s
</option>
))}
</Select>
</Field>
<div>
<div className="mb-2 text-[13px] font-medium">Colour</div>
<div className="flex flex-wrap gap-2" role="radiogroup" aria-label="Class colour">
@ -530,6 +541,7 @@ export function Shell() {
const location = useLocation();
const { open: assistantOpen, seed } = useAssistantState();
useDraftNotifications();
useLiveChanges();
const onAssistantPage = location.pathname.startsWith('/assistant');
// Study screens lay themselves out edge to edge and bring their own header and footer.
const immersive = location.pathname === '/review' || /^\/decks\/[^/]+\/cram$/.test(location.pathname);

View file

@ -0,0 +1,154 @@
import { Check, CircleHelp, CornerDownLeft } from 'lucide-react';
import { useMemo, useState } from 'react';
import type { AskQuestion, UiItem } from '@/lib/types';
import { cx } from '@/lib/util';
import { Button, Input } from '@/ui';
type Answer = { picked: string[]; typed: string };
function initial(q: AskQuestion): Answer {
if (q.input === 'choice') {
const labels = new Set((q.options ?? []).map((o) => o.label));
const picked = (q.defaults ?? []).filter((d) => labels.has(d));
return { picked: q.multi ? picked : picked.slice(0, 1), typed: '' };
}
return { picked: [], typed: q.defaults?.[0] ?? '' };
}
function answerText(q: AskQuestion, a: Answer): string {
const parts = [...a.picked, ...(a.typed.trim() ? [a.typed.trim()] : [])];
return parts.length ? parts.join(', ') : 'no preference';
}
/**
* Clarifying questions from the assistant, as a small inline form. The answers go back as the
* user's next message. Once the conversation moves on, the card folds to a quiet summary.
*/
export function AskCard({ item, answerable, onSend }: { item: Extract<UiItem, { type: 'questions' }>; answerable: boolean; onSend: (text: string) => void }) {
const [answers, setAnswers] = useState<Answer[]>(() => item.questions.map(initial));
const [sent, setSent] = useState(false);
const open = answerable && !sent;
const ready = useMemo(() => answers.some((a) => a.picked.length > 0 || a.typed.trim()), [answers]);
const set = (i: number, next: Partial<Answer>) => setAnswers((all) => all.map((a, j) => (j === i ? { ...a, ...next } : a)));
const toggle = (i: number, q: AskQuestion, label: string) => {
const a = answers[i];
if (q.multi) set(i, { picked: a.picked.includes(label) ? a.picked.filter((l) => l !== label) : [...a.picked, label] });
// A single choice replaces a typed answer, and picking it again clears it.
else set(i, { picked: a.picked[0] === label ? [] : [label], typed: '' });
};
const submit = () => {
setSent(true);
onSend(item.questions.map((q, i) => (item.questions.length === 1 ? answerText(q, answers[i]) : `${q.question} → ${answerText(q, answers[i])}`)).join('\n'));
};
const skip = () => {
setSent(true);
onSend('No preference — use your best judgment.');
};
if (!open) {
return (
<div className="rounded-[14px] border border-line bg-surface/60 px-3.5 py-2.5 text-[13px] text-ink-3">
<div className="flex items-center gap-1.5 font-medium text-ink-2">
<CircleHelp className="size-3.5" /> {item.questions.length === 1 ? 'Asked you' : `Asked you ${item.questions.length} questions`}
</div>
<ul className="mt-1 space-y-0.5">
{item.questions.map((q) => (
<li key={q.id} className="truncate">
{q.question}
</li>
))}
</ul>
</div>
);
}
return (
<form
className="tool-pop rounded-[16px] border border-accent/40 bg-surface p-3.5 shadow-1"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<div className="flex items-start gap-2.5">
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-accent-soft text-accent">
<CircleHelp className="size-4" />
</span>
<div className="min-w-0 pt-1 text-sm font-semibold">{item.intro || (item.questions.length === 1 ? 'A quick question first' : 'A few quick questions first')}</div>
</div>
<div className="mt-3 space-y-4">
{item.questions.map((q, i) => {
const a = answers[i];
const name = `ask-${item.id}-${q.id}`;
return (
<fieldset key={q.id} className="min-w-0">
<legend className="mb-1.5 text-[13.5px] font-medium text-ink">
{q.question}
{q.multi && <span className="ml-1.5 text-xs font-normal text-ink-3">Choose any</span>}
</legend>
{q.input === 'choice' && q.options ? (
<>
<div role={q.multi ? 'group' : 'radiogroup'} aria-label={q.question} className="flex flex-wrap gap-1.5">
{q.options.map((o) => {
const on = a.picked.includes(o.label);
return (
<button
key={o.label}
type="button"
role={q.multi ? 'checkbox' : 'radio'}
aria-checked={on}
title={o.description}
onClick={() => toggle(i, q, o.label)}
className={cx(
'flex min-h-9 max-w-full items-center gap-1.5 rounded-full border px-3 py-1.5 text-left text-[13px] transition-colors',
on ? 'border-accent bg-accent-soft font-medium text-ink' : 'border-line bg-surface text-ink-2 hover:border-ink-3 hover:text-ink',
)}
>
{on && <Check className="size-3.5 shrink-0 text-accent" />}
<span className="min-w-0">
<span className="block truncate">{o.label}</span>
{o.description && <span className="block truncate text-[11.5px] font-normal text-ink-3">{o.description}</span>}
</span>
</button>
);
})}
</div>
<Input
aria-label={`${q.question} (your own answer)`}
value={a.typed}
onChange={(e) => set(i, { typed: e.target.value, ...(q.multi || !e.target.value ? {} : { picked: [] }) })}
placeholder={q.placeholder || 'Or type your own'}
className="mt-2 h-9 text-[13px]"
maxLength={300}
/>
</>
) : (
<Input
id={name}
aria-label={q.question}
type={q.input === 'number' ? 'number' : 'text'}
inputMode={q.input === 'number' ? 'numeric' : undefined}
min={q.input === 'number' ? 1 : undefined}
value={a.typed}
onChange={(e) => set(i, { typed: e.target.value })}
placeholder={q.placeholder}
className={cx('h-9 text-[13px]', q.input === 'number' && 'max-w-32')}
maxLength={300}
/>
)}
</fieldset>
);
})}
</div>
<div className="mt-4 flex flex-wrap items-center gap-2">
<Button type="submit" size="sm" variant="primary" disabled={!ready} icon={<CornerDownLeft />}>
Send answers
</Button>
<Button type="button" size="sm" variant="ghost" onClick={skip}>
Skip, you decide
</Button>
</div>
</form>
);
}

View file

@ -1,14 +1,16 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowUp, BookOpen, Brain, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Search, Sparkles, Square, Trash2, X } from 'lucide-react';
import { ArrowUp, BookOpen, Brain, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, Globe, History, Layers, NotebookPen, Play, Plug, Plus, Search, SlidersHorizontal, Sparkles, Square, Trash2, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Link, useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api, errorMessage, streamEvents } from '@/lib/api';
import { assistant, ITEM_DRAG_TYPE, useAssistantState } from '@/lib/assistantStore';
import { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
import type { AssistantEvent, ChatMessage, Mentionable, MessagePart, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
import { qk, useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
import type { AssistantEvent, ChatMessage, ChatToolSource, Mentionable, MessagePart, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
import { cx, plural, timeAgo, useDebounced, useLocalStorage } from '@/lib/util';
import { citedSources, Markdown, type Citation } from '@/ui/Markdown';
import { citedSources, GenUiContext, Markdown, type Citation } from '@/ui/Markdown';
import { AskCard } from './AskCard';
import { ToolSteps } from './ToolSteps';
import { Badge, Button, Callout, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Popover, Spinner } from '@/ui';
@ -61,18 +63,6 @@ const DRAFT_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />
/* ------------------------------ message parts ------------------------------ */
function ToolLine({ tool }: { tool: ToolActivity }) {
return (
<div className="flex items-center gap-2 text-[13px] text-ink-2">
{tool.status === 'running' ? <LoaderCircle className="size-3.5 shrink-0 animate-spin text-accent" /> : tool.status === 'error' ? <CircleAlert className="size-3.5 shrink-0 text-bad" /> : <Check className="size-3.5 shrink-0 text-good" />}
<span className="min-w-0 truncate">
{tool.label}
{tool.summary && <span className={cx('ml-1.5', tool.status === 'error' ? 'text-bad' : 'text-ink-3')}>· {tool.summary}</span>}
</span>
</div>
);
}
function DraftCard({ item, onNavigate }: { item: Extract<UiItem, { type: 'draft' }>; onNavigate: () => void }) {
const gone = item.status === 'discarded';
const saved = item.status === 'saved';
@ -165,7 +155,7 @@ function ReasoningBox({ text, live }: { text: string; live: boolean }) {
const el = e.currentTarget;
follow.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
}}
className="mt-1.5 max-h-32 overflow-y-auto rounded-[10px] border border-line bg-sunken/60 px-3 py-2 text-[12.5px] leading-relaxed whitespace-pre-wrap text-ink-3"
className="mt-1.5 max-h-48 overflow-y-auto rounded-[10px] border border-line bg-sunken/60 px-3 py-2 text-[12.5px] leading-relaxed whitespace-pre-wrap text-ink-3"
>
{shown}
</div>
@ -174,32 +164,7 @@ function ReasoningBox({ text, live }: { text: string; live: boolean }) {
);
}
/** Tool steps that ran back to back: running ones listed, finished ones folded into one line. */
function ToolGroup({ tools }: { tools: ToolActivity[] }) {
const [open, setOpen] = useState(false);
const running = tools.filter((t) => t.status === 'running');
const finished = tools.filter((t) => t.status !== 'running');
return (
<div className="space-y-1">
{finished.length > 0 && (
<div>
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="flex items-center gap-1 text-xs font-medium text-ink-3 hover:text-ink-2">
<ChevronRight className={cx('size-3.5 transition-transform', open && 'rotate-90')} />
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
{finished.length === 1 && finished[0].summary ? <span className="ml-1 truncate font-normal">· {finished[0].summary}</span> : null}
{finished.some((t) => t.status === 'error') && <CircleAlert className="size-3.5 text-bad" />}
</button>
{open && <div className="mt-1.5 space-y-1 border-l-2 border-line pl-3">{finished.map((t) => <ToolLine key={t.id} tool={t} />)}</div>}
</div>
)}
{running.map((t) => (
<ToolLine key={t.id} tool={t} />
))}
</div>
);
}
function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMessage; onNavigate: () => void; onAction: (actionId: string, status: string, result: string) => void }) {
function AssistantMessage({ message, onNavigate, onAction, onSend, answerable = false }: { message: ChatMessage; onNavigate: () => void; onAction: (actionId: string, status: string, result: string) => void; onSend: (text: string) => void; answerable?: boolean }) {
const navigate = useNavigate();
const citations = useMemo<Citation[]>(() => message.ui.flatMap((u) => (u.type === 'sources' ? u.items : [])), [message.ui]);
const cited = useMemo(() => citedSources(message.text, citations), [message.text, citations]);
@ -218,7 +183,7 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
if (p.text.trim()) blocks.push({ kind: 'text', text: p.text });
} else if (p.kind === 'tool') {
const tool = message.tools.find((t) => t.id === p.id);
if (!tool) continue;
if (!tool || (tool.name === 'ask_user' && tool.status === 'done')) continue;
const last = blocks[blocks.length - 1];
if (last?.kind === 'tools') last.tools.push(tool);
else blocks.push({ kind: 'tools', tools: [tool] });
@ -228,7 +193,9 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
}
}
const genUi = useMemo(() => ({ streaming: Boolean(message.pending), onSend }), [message.pending, onSend]);
return (
<GenUiContext.Provider value={genUi}>
<div className="space-y-2.5">
{message.reasoning && <ReasoningBox text={message.reasoning} live={Boolean(message.pending) && !message.text} />}
{blocks.map((b, i) =>
@ -237,11 +204,13 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
{b.text}
</Markdown>
) : b.kind === 'tools' ? (
<ToolGroup key={i} tools={b.tools} />
<ToolSteps key={i} tools={b.tools} />
) : b.item.type === 'draft' ? (
<DraftCard key={i} item={b.item} onNavigate={onNavigate} />
) : b.item.type === 'action' ? (
<ActionCard key={i} item={b.item} onResolved={(status, result) => onAction((b.item as Extract<UiItem, { type: 'action' }>).actionId, status, result)} />
) : b.item.type === 'questions' ? (
<AskCard key={b.item.id} item={b.item} answerable={answerable && !message.pending} onSend={onSend} />
) : b.item.type === 'link' ? (
<Link key={i} to={`/${ITEM_URL[b.item.kind]}/${b.item.id}`} onClick={onNavigate} className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1 hover:border-ink-3">
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-marker text-marker-ink">
@ -274,6 +243,7 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
</Callout>
)}
</div>
</GenUiContext.Provider>
);
}
@ -354,6 +324,63 @@ function useMentionables(classId: string | null, query: string, enabled: boolean
return (q.data ?? []).filter((i) => !needle || i.title.toLowerCase().includes(needle) || (i.folderName ?? '').toLowerCase().includes(needle)).slice(0, 40);
}
/* ------------------------------ per-chat tools ------------------------------ */
/** Switches for the web search and MCP servers in this conversation, beside the + button. */
function ToolsPicker({ off, onChange }: { off: string[]; onChange: (off: string[]) => void }) {
const sources = useQuery({ queryKey: ['ai', 'chat-tools'], queryFn: () => api.get<{ sources: ChatToolSource[] }>('/api/ai/chat-tools').then((r) => r.sources), staleTime: 60_000 });
const list = sources.data ?? [];
if (list.length === 0) return null;
const offCount = list.filter((s) => off.includes(s.id)).length;
return (
<Popover
align="end"
className="w-72 p-2"
trigger={
<IconButton label="Tools for this chat" size="sm" className="relative mb-0.5" tooltip={false}>
<SlidersHorizontal />
{offCount > 0 && <span className="absolute top-1 right-1 size-1.5 rounded-full bg-warn" aria-hidden />}
</IconButton>
}
>
<div className="px-2 pt-1 pb-2">
<div className="text-sm font-semibold">Tools in this chat</div>
<div className="text-[12px] text-ink-3">Switch sources off for this conversation only.</div>
</div>
<div className="space-y-0.5">
{list.map((s) => {
const on = !off.includes(s.id);
return (
<button
key={s.id}
type="button"
role="switch"
aria-checked={on}
onClick={() => onChange(on ? [...off, s.id] : off.filter((x) => x !== s.id))}
className="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-left hover:bg-ink/5"
>
<span className={cx('grid size-7 shrink-0 place-items-center rounded-md [&>svg]:size-3.5', on ? 'bg-accent-soft text-accent' : 'bg-sunken text-ink-3')}>{s.kind === 'web' ? <Globe /> : <Plug />}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm">{s.name}</span>
<span className="block text-[11px] text-ink-3">{s.kind === 'web' ? 'Search and read web pages' : 'MCP server'}</span>
</span>
<span className={cx('relative h-5 w-9 shrink-0 rounded-full transition-colors', on ? 'bg-accent' : 'bg-ink/20')}>
<span className={cx('absolute top-0.5 size-4 rounded-full bg-white shadow-1 transition-transform', on ? 'translate-x-[18px]' : 'translate-x-0.5')} />
</span>
</button>
);
})}
</div>
<div className="mt-1.5 border-t border-line px-2 pt-1.5 text-[11px] text-ink-3">
Manage them in{' '}
<Link to="/settings/web" className="font-medium text-accent hover:underline">
Settings
</Link>
</div>
</Popover>
);
}
/* ------------------------------ panel ------------------------------ */
export default function AssistantPanel({
@ -387,6 +414,8 @@ export default function AssistantPanel({
const [pickerQuery, setPickerQuery] = useState('');
const [dropping, setDropping] = useState(false);
const [modelId, setModelId] = useLocalStorage('sd.assistant.model', '');
/** Web search and MCP servers switched off in this conversation (saved with it). */
const [toolsOff, setToolsOff] = useState<string[]>([]);
/** The connection to the running turn. Aborting it only detaches: the turn continues on the server. */
const stream = useRef<AbortController | null>(null);
const stopRequested = useRef(false);
@ -452,6 +481,8 @@ export default function AssistantPanel({
}
}
if (e.type === 'done') finished = true;
// A draft card means the drafts list changed.
if (e.type === 'ui' && e.item.type === 'draft') void qc.invalidateQueries({ queryKey: qk.drafts });
applyEvent(pendingId, e);
});
} catch (e) {
@ -486,8 +517,9 @@ export default function AssistantPanel({
stream.current?.abort();
setLoadingHistory(true);
try {
const res = await api.get<{ conversation: { id: string; running?: boolean }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
const res = await api.get<{ conversation: { id: string; running?: boolean; toolsOff?: string[] }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
setConversation(id);
setToolsOff(res.conversation.toolsOff ?? []);
stick.current = true;
if (!res.conversation.running) {
setMessages(res.messages);
@ -534,6 +566,7 @@ export default function AssistantPanel({
setMessages([]);
setFocusDocs([]);
setTags([]);
setToolsOff([]);
onConversationChange?.(null);
setTimeout(() => inputRef.current?.focus(), 30);
}, [onConversationChange, setConversation]);
@ -570,8 +603,10 @@ export default function AssistantPanel({
conversationId: convo,
message,
modelId: effectiveModelId || undefined,
toolsOff,
context: {
classId: opts.classId !== undefined ? opts.classId : context.classId,
folderId: opts.classId !== undefined && opts.classId !== context.classId ? null : (context.folderId ?? null),
documentIds: opts.documentIds ?? activeDocs,
items: sentTags.map((t) => ({ kind: t.kind, id: t.id })),
},
@ -581,8 +616,10 @@ export default function AssistantPanel({
),
);
},
[busy, tags, follow, effectiveModelId, context.classId, activeDocs],
[busy, tags, follow, effectiveModelId, context.classId, context.folderId, activeDocs, toolsOff],
);
/** Buttons and suggestion chips inside a reply send their text as the next message. */
const sendFromBlock = useCallback((text: string) => void send(text), [send]);
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
useEffect(() => {
@ -627,7 +664,7 @@ export default function AssistantPanel({
return ['What should I study today?', 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', 'Explain the difference between left-sided and right-sided heart failure', 'Start a practice session with the questions I miss most'];
}, [activeDocs.length, className]);
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className;
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : context.folderId && context.label ? context.label : className;
const options = useMentionables(context.classId, mention?.query ?? '', mention !== null);
const pickable = options.filter((o) => !tags.some((t) => t.kind === o.kind && t.id === o.id));
@ -776,7 +813,7 @@ export default function AssistantPanel({
</div>
) : (
<div className="mx-auto max-w-2xl space-y-6">
{messages.map((m) =>
{messages.map((m, mi) =>
m.role === 'user' ? (
<div key={m.id} className="flex justify-end">
<div className="max-w-[88%] rounded-[16px] rounded-br-md bg-ink px-3.5 py-2.5 text-[15px] whitespace-pre-wrap text-paper">
@ -791,7 +828,7 @@ export default function AssistantPanel({
</div>
</div>
) : (
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} />
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} onSend={sendFromBlock} answerable={mi === messages.length - 1 && !busy} />
),
)}
</div>
@ -900,6 +937,7 @@ export default function AssistantPanel({
aria-label="Message the assistant"
className="max-h-44 min-h-9 flex-1 resize-none bg-transparent px-2.5 py-1.5 text-[15px] outline-none placeholder:text-ink-3"
/>
<ToolsPicker off={toolsOff} onChange={setToolsOff} />
<Popover
open={pickerOpen}
onOpenChange={(o) => {

View file

@ -1,28 +1,58 @@
import { CornerDownLeft, Sparkles, Square } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
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 { Markdown } from '@/ui/Markdown';
import { Button, Callout, Spinner } from '@/ui';
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 }
| { 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: 'error'; message: string } | { type: 'done' };
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<{ ask?: string; text: string }[]>([]);
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.
@ -34,80 +64,114 @@ export function Explain({ body, label = 'Explain with AI', className, url = '/ap
}, [key]);
useEffect(() => () => abort.current?.abort(), []);
const run = async (question?: string) => {
setOpen(true);
setBusy(true);
setError('');
setTurns((t) => [...t, { ask: question, text: '' }]);
const controller = new AbortController();
abort.current = controller;
try {
await streamEvents<Event>(
url,
{ ...body, ask: question },
(e) => {
if (e.type === 'text') setTurns((t) => t.map((x, i) => (i === t.length - 1 ? { ...x, text: x.text + e.delta } : x)));
else if (e.type === 'error') setError(e.message);
},
controller.signal,
);
} catch (e) {
if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e));
} finally {
setBusy(false);
}
};
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={() => run()}>
{label}
<Button size="sm" variant="ghost" icon={<Sparkles />} className={className} onClick={() => (turns.length ? setOpen(true) : run())}>
{turns.length ? 'Show the explanation' : label}
</Button>
);
}
return (
<div className={className}>
<div className="rounded-xl border border-accent/25 bg-accent-soft/50 p-4">
<div className="eyebrow mb-2 flex items-center gap-1.5 text-accent">
<Sparkles className="size-3.5" /> AI explanation
</div>
<div className="space-y-3">
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}>
<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.text ? <Markdown className="text-[14.5px]">{t.text}</Markdown> : busy && i === turns.length - 1 ? <Spinner className="size-4" label="Thinking" /> : null}
{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>
{error && (
<Callout tone="bad" className="mt-3 py-2">
{error}
</Callout>
)}
<form
className="mt-3 flex 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 text-[11px] text-ink-3">AI can be wrong. Check anything important against your course material.</p>
</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>;
}

View file

@ -46,8 +46,13 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
const [templateId, setTemplateId] = useState('');
const [verify, setVerify] = useLocalStorage('sd.generate.verify', true);
const [busy, setBusy] = useState(false);
/** The exam (folder) this draft is for: its documents are the only ones offered, and the draft is saved there. */
const [examId, setExamId] = useState<string | null>(folderId ?? null);
const exams = cls.data?.folders ?? [];
const groupLabel = cls.data?.class.groupLabel ?? 'Exam';
const docs = useMemo(() => (cls.data?.items.filter((i): i is DocumentItem => i.kind === 'document') ?? []).filter((d) => d.status === 'ready' && d.tokenCount > 0), [cls.data]);
const allDocs = useMemo(() => (cls.data?.items.filter((i): i is DocumentItem => i.kind === 'document') ?? []).filter((d) => d.status === 'ready' && d.tokenCount > 0), [cls.data]);
const docs = useMemo(() => (examId ? allDocs.filter((d) => d.folderId === examId) : allDocs), [allDocs, examId]);
const fixedSource = Boolean(preset?.deckId || preset?.quizId || preset?.noteId);
useEffect(() => {
@ -67,7 +72,15 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
setSata(30);
setCardStyle('concise');
setNoteStyle('study_guide');
}, [open, preset]);
setExamId(folderId ?? null);
}, [open, preset, folderId]);
// Inside an exam, start with all of its documents selected.
useEffect(() => {
if (!open || preset?.documentIds?.length || !cls.isSuccess) return;
setDocIds(examId ? docs.map((d) => d.id) : []);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, examId, cls.isSuccess]);
// With no usable documents, default to describing a topic.
useEffect(() => {
@ -103,7 +116,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
else if (mode === 'documents') source.documentIds = docIds;
else if (mode === 'text') source.text = text;
else if (mode === 'weak') source.weakAreas = true;
const body: Record<string, unknown> = { kind, classId, folderId: folderId ?? null, source, focus: focus.trim() || undefined, instructions: instructions.trim() || undefined, modelId: modelId || undefined };
const body: Record<string, unknown> = { kind, classId, folderId: examId, source, focus: focus.trim() || undefined, instructions: instructions.trim() || undefined, modelId: modelId || undefined };
if (kind === 'quiz') Object.assign(body, { count, format, style: 'nclex', difficulty, sataShare: sata / 100, verify });
else if (kind === 'deck') Object.assign(body, { count, cardStyle });
else Object.assign(body, { noteStyle });
@ -161,6 +174,19 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
<div className="space-y-5">
{!preset?.kind && <Segmented label="What to create" value={kind} onChange={(k) => (setKind(k), setCount(k === 'deck' ? 30 : 15), setTemplateId(''))} options={kinds} className="w-full" />}
{exams.length > 0 && (
<Field label={groupLabel} hint={examId ? `Uses only this ${groupLabel.toLowerCase()}'s material, and the draft is saved in it.` : `Uses material from the whole class.`}>
<Select value={examId ?? ''} onChange={(e) => setExamId(e.target.value || null)}>
<option value="">Whole class</option>
{exams.map((f) => (
<option key={f.id} value={f.id}>
{f.name}
</option>
))}
</Select>
</Field>
)}
{fixedSource ? (
<Callout icon={preset?.deckId ? <Layers /> : preset?.quizId ? <BookOpen /> : <NotebookPen />}>
Source: <strong className="text-ink">{preset?.sourceLabel}</strong>

View file

@ -1,5 +1,6 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { CircleAlert, CircleCheck, Plug, Plus, Trash2 } from 'lucide-react';
import { CircleAlert, CircleCheck, LogIn, LogOut, Plug, Plus, ShieldCheck, Trash2 } from 'lucide-react';
import { timeAgo } from '@/lib/util';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
@ -8,7 +9,7 @@ import { Badge, Button, Dialog, Field, Input, Section, Switch, Textarea, useConf
type McpArea = 'chat' | 'explain' | 'generate' | 'check' | 'share';
type McpAreas = Record<McpArea, boolean>;
const AREAS: { key: McpArea; label: string; description: string }[] = [
export const AREAS: { key: McpArea; label: string; description: string }[] = [
{ key: 'chat', label: 'Assistant chat', description: 'The sidebar and full-page assistant.' },
{ key: 'explain', label: 'Explain this', description: 'Help on a quiz question, flashcard or passage.' },
{ key: 'generate', label: 'Generating material', description: 'Writing quizzes, flashcards and study guides.' },
@ -17,19 +18,30 @@ const AREAS: { key: McpArea; label: string; description: string }[] = [
];
const DEFAULT_AREAS: McpAreas = { chat: true, explain: true, generate: false, check: false, share: false };
interface McpServer {
export interface McpServer {
id: string;
name: string;
url: string;
enabled: boolean;
builtin: 'web' | null;
instructions: string;
areas: McpAreas;
headerNames: string[];
oauth: { connected: boolean; connectedAt: number | null; expiresAt: number | null; refreshable: boolean };
clientId: string;
hasClientSecret: boolean;
options: { research: boolean };
lastTestAt: number | null;
lastTestOk: boolean | null;
lastTestMessage: string | null;
}
/** Sends the browser to the server's sign-in page; it comes back to `returnTo`. */
export async function startMcpSignIn(id: string, returnTo: string): Promise<void> {
const { url } = await api.post<{ url: string }>(`/api/ai/mcp/${id}/oauth/start`, { origin: window.location.origin, returnTo });
window.location.href = url;
}
interface TestResult {
ok: boolean;
message: string;
@ -54,6 +66,8 @@ function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; exi
const [headers, setHeaders] = useState('');
const [instructions, setInstructions] = useState('');
const [areas, setAreas] = useState<McpAreas>(DEFAULT_AREAS);
const [clientId, setClientId] = useState('');
const [clientSecret, setClientSecret] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
@ -63,13 +77,23 @@ function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; exi
setHeaders('');
setInstructions(existing?.instructions ?? '');
setAreas({ ...DEFAULT_AREAS, ...existing?.areas });
setClientId(existing?.clientId ?? '');
setClientSecret('');
}, [open, existing]);
const canSave = name.trim() && /^https?:\/\/\S+$/i.test(url.trim());
const save = async () => {
setBusy(true);
try {
const body = { name: name.trim(), url: url.trim(), instructions: instructions.trim(), areas, ...(headers.trim() ? { headers: parseHeaders(headers) } : existing ? {} : { headers: {} }) };
const body = {
name: name.trim(),
url: url.trim(),
instructions: instructions.trim(),
areas,
clientId: clientId.trim(),
...(clientSecret.trim() ? { clientSecret: clientSecret.trim() } : {}),
...(headers.trim() ? { headers: parseHeaders(headers) } : existing ? {} : { headers: {} }),
};
const res = existing ? await api.patch<{ server: McpServer }>(`/api/ai/mcp/${existing.id}`, body) : await api.post<{ server: McpServer }>('/api/ai/mcp', body);
onSaved(res.server);
onClose();
@ -122,6 +146,18 @@ function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; exi
<Field label="HTTP headers" optional hint={existing?.headerNames.length ? `Stored: ${existing.headerNames.join(', ')}. Entering anything here replaces them.` : 'One per line, as Name: value. Encrypted on the server and never shown again.'}>
<Textarea rows={2} value={headers} onChange={(e) => setHeaders(e.target.value)} placeholder="Authorization: Bearer …" spellCheck={false} className="num text-[13px]" />
</Field>
<details className="rounded-xl border border-line px-3.5 py-2.5">
<summary className="cursor-pointer text-sm font-medium text-ink">Sign-in app (advanced)</summary>
<p className="mt-2 mb-3 text-xs text-ink-3">Most servers that need an account register this app automatically when you choose Sign in. Fill these in only if the server asks for a pre-registered OAuth app; use the redirect URL {window.location.origin}/api/ai/mcp/oauth/callback.</p>
<div className="space-y-3">
<Field label="Client ID" optional>
<Input value={clientId} onChange={(e) => setClientId(e.target.value)} spellCheck={false} className="num text-[13px]" />
</Field>
<Field label="Client secret" optional hint={existing?.hasClientSecret ? 'Stored. Entering a new one replaces it.' : 'Encrypted on the server and never shown again.'}>
<Input type="password" value={clientSecret} onChange={(e) => setClientSecret(e.target.value)} autoComplete="off" className="num text-[13px]" />
</Field>
</div>
</details>
<button type="submit" hidden />
</form>
</Dialog>
@ -132,6 +168,20 @@ function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () =
const confirm = useConfirm();
const [testing, setTesting] = useState(false);
const [tools, setTools] = useState<TestResult['tools'] | null>(null);
const [signingIn, setSigningIn] = useState(false);
const signIn = async () => {
setSigningIn(true);
await startMcpSignIn(server.id, '/settings/ai').catch((e) => toast.error(errorMessage(e)));
setSigningIn(false);
};
const signOut = async () => {
try {
await api.del(`/api/ai/mcp/${server.id}/oauth`);
reload();
} catch (e) {
toast.error(errorMessage(e));
}
};
const test = async () => {
setTesting(true);
@ -182,6 +232,11 @@ function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () =
{!AREAS.some((a) => server.areas[a.key]) && <span className="text-xs text-ink-3">Not used anywhere</span>}
</div>
{server.instructions && <p className="mt-1.5 line-clamp-2 text-xs text-ink-2">{server.instructions}</p>}
{server.oauth.connected && (
<div className="mt-1 flex items-center gap-1 text-xs text-good">
<ShieldCheck className="size-3.5 shrink-0" /> Signed in{server.oauth.connectedAt ? ` ${timeAgo(server.oauth.connectedAt)}` : ''}
</div>
)}
{server.lastTestAt && (
<div className={`mt-1 flex items-center gap-1 text-xs ${server.lastTestOk ? 'text-good' : 'text-bad'}`}>
{server.lastTestOk ? <CircleCheck className="size-3.5 shrink-0" /> : <CircleAlert className="size-3.5 shrink-0" />}
@ -195,6 +250,15 @@ function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () =
<Button size="sm" variant="secondary" loading={testing} onClick={test}>
Test and list tools
</Button>
{server.oauth.connected ? (
<Button size="sm" variant="ghost" icon={<LogOut />} onClick={signOut}>
Sign out
</Button>
) : (
<Button size="sm" variant="ghost" icon={<LogIn />} loading={signingIn} onClick={signIn}>
Sign in
</Button>
)}
<Button size="sm" variant="ghost" onClick={onEdit}>
Edit
</Button>
@ -243,7 +307,7 @@ export function McpSettings() {
) : (
<div className="card p-4 text-sm text-ink-2">No MCP servers yet. Connect one to give the assistant extra tools, such as a drug reference or your own notes system.</div>
)}
<p className="mt-2.5 text-xs text-ink-3">Streamable HTTP servers only. Each server's tools are offered only in the places you allow, with your instructions on when to use them. Headers are encrypted and never sent back to the browser.</p>
<p className="mt-2.5 text-xs text-ink-3">Streamable HTTP servers only. Each server's tools are offered only in the places you allow, with your instructions on when to use them. Servers that need an account: choose Sign in (OAuth). Headers and sign-in tokens are encrypted and never sent back to the browser. Web search has its own section.</p>
<ServerDialog
open={dialog.open}
existing={dialog.existing}

View file

@ -1,21 +1,25 @@
import { CornerDownLeft, MessageCircleQuestion, Sparkles, Square, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
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 { Markdown } from '@/ui/Markdown';
import { Button, Callout, IconButton, Spinner } from '@/ui';
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: 'error'; message: string } | { type: 'done' };
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 }: { token: string; title: string; item?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string } }) {
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('');
@ -30,71 +34,90 @@ export function SharedAssistant({ token, title, item }: { token: string; title:
if (el) el.scrollTop = el.scrollHeight;
}, [turns, open]);
const send = async (text: string) => {
// 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: '' }]);
setBusy(true);
setError('');
const controller = new AbortController();
abort.current = controller;
try {
await streamEvents<Event>(
`/api/public/${token}/chat`,
{ messages: history.filter((t) => t.text.trim()), item },
(e) => {
if (e.type === 'text') setTurns((t) => t.map((x, i) => (i === t.length - 1 ? { ...x, text: x.text + e.delta } : x)));
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));
}
};
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 (
<button
type="button"
onClick={() => setOpen(true)}
className="fixed right-4 bottom-28 z-40 flex h-11 items-center gap-2 rounded-full bg-ink px-4 text-sm font-semibold text-paper shadow-2 hover:bg-ink/90 sm:right-6"
>
<MessageCircleQuestion className="size-[18px]" /> Ask about this
</button>
<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(560px,calc(100dvh-2rem))] w-[min(420px,calc(100vw-2rem))] flex-col overflow-hidden rounded-[18px] border border-line bg-surface shadow-2 sm:right-6">
<header className="flex items-center gap-2 border-b border-line px-4 py-2.5">
<Sparkles className="size-4 text-accent" />
<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">Ask about this</div>
<div className="text-sm font-semibold">Assistant</div>
<div className="truncate text-xs text-ink-3">{title}</div>
</div>
<IconButton label="Close" onClick={() => setOpen(false)}>
<IconButton label="Close" size="sm" onClick={() => setOpen(false)}>
<X />
</IconButton>
</header>
<div ref={list} className="flex-1 space-y-3 overflow-y-auto px-4 py-3">
<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>}
{turns.map((t, i) =>
t.role === 'user' ? (
<div key={i} className="ml-8 rounded-[14px] bg-accent-soft px-3 py-2 text-[14px] whitespace-pre-wrap">
{t.text}
</div>
) : t.text ? (
<Markdown key={i} className="text-[14px]">
{t.text}
</Markdown>
) : busy && i === turns.length - 1 ? (
<Spinner key={i} className="size-4" label="Thinking" />
) : null,
)}
<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}

View file

@ -0,0 +1,199 @@
/**
* Tool steps in a conversation: one quiet line per step with a status mark (spinner, check or
* cross) and a friendly name ("Searched the web for: sepsis bundle"). Clicking a line opens its
* details: the pages it found, what it was asked and what it returned.
*/
import {
BarChart3,
BookMarked,
BookOpenText,
Check,
ChevronRight,
CircleHelp,
FileSearch,
FileText,
Globe,
Library,
ListChecks,
LoaderCircle,
PencilLine,
Play,
Plug,
Search,
Sparkles,
Telescope,
Terminal,
X,
} from 'lucide-react';
import { useState, type ReactNode } from 'react';
import type { ToolActivity } from '@/lib/types';
import { cx } from '@/lib/util';
const BUILTIN_ICON: Record<string, ReactNode> = {
search_documents: <FileSearch />,
read_document: <BookOpenText />,
search_library: <Search />,
list_materials: <Library />,
list_classes: <Library />,
get_quiz: <ListChecks />,
get_deck: <ListChecks />,
read_note: <BookOpenText />,
get_performance: <BarChart3 />,
generate_quiz: <Sparkles />,
generate_flashcards: <Sparkles />,
write_study_guide: <Sparkles />,
improve_questions: <Sparkles />,
create_draft: <PencilLine />,
run_python: <Terminal />,
start_practice: <Play />,
propose_changes: <ListChecks />,
organize: <Library />,
read_sources: <BookMarked />,
ask_user: <CircleHelp />,
};
function iconFor(tool: ToolActivity): ReactNode {
switch (tool.kind) {
case 'web_search':
return <Globe className={cx(tool.status === 'running' && 'tool-spin-slow')} />;
case 'web_fetch':
return <FileText />;
case 'web_research':
return <Telescope />;
case 'mcp':
return <Plug />;
default:
return BUILTIN_ICON[tool.name] ?? <Sparkles />;
}
}
/** The line's text: what is happening while it runs, what happened once it is done. */
export function toolTitle(tool: ToolActivity): ReactNode {
const subject = tool.subject ? <span className="text-ink-2">{tool.subject}</span> : null;
if (tool.status === 'running') return tool.label;
const failed = tool.status === 'error';
switch (tool.kind) {
case 'web_search':
return failed ? 'Web search failed' : subject ? <>Searched the web for: {subject}</> : 'Searched the web';
case 'web_fetch':
return failed ? 'Could not read the page' : <>Read {subject ?? 'web pages'}</>;
case 'web_research':
return failed ? 'Web research failed' : subject ? <>Researched: {subject}</> : 'Researched on the web';
case 'mcp':
return failed ? `${tool.label} failed` : tool.label.replace(/^([^:]+): /, '$1 · ');
default:
return failed ? `${tool.label} (failed)` : tool.label;
}
}
function hostOf(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, '');
} catch {
return url;
}
}
function Details({ tool }: { tool: ToolActivity }) {
return (
<div className="mt-1.5 mb-1 ml-[9px] space-y-2.5 border-l-2 border-line pt-0.5 pb-1 pl-4 text-[12.5px]">
{tool.sources && tool.sources.length > 0 && (
<ul className="space-y-1">
{tool.sources.map((s) => (
<li key={s.url}>
<a href={s.url} target="_blank" rel="noreferrer noopener" className="group flex min-w-0 items-baseline gap-2 hover:text-ink">
<span className="min-w-0 truncate font-medium text-ink group-hover:underline">{s.title}</span>
<span className="shrink-0 text-[11.5px] text-ink-3">{hostOf(s.url)}</span>
</a>
</li>
))}
</ul>
)}
{tool.summary && <div className={cx(tool.status === 'error' ? 'text-bad' : 'text-ink-2')}>{tool.summary}</div>}
{tool.server && <div className="text-ink-3">From the {tool.server} server</div>}
{tool.input && tool.input !== '{}' && (
<div>
<div className="eyebrow mb-1">Request</div>
<pre className="max-h-40 overflow-auto rounded-lg bg-sunken px-2.5 py-2 font-mono text-[11.5px] whitespace-pre-wrap text-ink-2">{tool.input}</pre>
</div>
)}
{tool.output && (
<div>
<div className="eyebrow mb-1">Result</div>
<pre className="max-h-48 overflow-auto rounded-lg bg-sunken px-2.5 py-2 font-mono text-[11.5px] whitespace-pre-wrap text-ink-2">{tool.output}</pre>
</div>
)}
{!tool.sources?.length && !tool.summary && !tool.input && !tool.output && <div className="text-ink-3">{tool.status === 'running' ? 'Working…' : 'No details.'}</div>}
</div>
);
}
function Mark({ tool }: { tool: ToolActivity }) {
return (
<span className="relative grid size-[18px] shrink-0 place-items-center text-ink-3 [&>svg]:size-[15px]">
{iconFor(tool)}
{tool.status === 'running' ? (
<LoaderCircle className="absolute -inset-[3px] !size-[24px] animate-spin text-accent/70" strokeWidth={1.5} />
) : (
<span className={cx('tool-pop absolute -right-1 -bottom-1 grid size-[11px] place-items-center rounded-full ring-2 ring-paper', tool.status === 'error' ? 'bg-bad text-white' : 'bg-good text-white')}>
{tool.status === 'error' ? <X className="!size-[8px]" strokeWidth={3.5} /> : <Check className="!size-[8px]" strokeWidth={3.5} />}
</span>
)}
</span>
);
}
export function ToolStep({ tool, compact }: { tool: ToolActivity; compact?: boolean }) {
const [open, setOpen] = useState(false);
return (
<div className="min-w-0">
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className={cx('group flex max-w-full min-w-0 items-center gap-2.5 rounded-lg py-1 pr-2 text-left', compact ? 'text-[12.5px]' : 'text-[13.5px]')}>
<Mark tool={tool} />
<span className={cx('min-w-0 truncate', tool.status === 'running' ? 'tool-shimmer font-medium' : tool.status === 'error' ? 'text-bad' : 'text-ink-2 group-hover:text-ink')}>{toolTitle(tool)}</span>
{tool.status === 'done' && tool.sources && tool.sources.length > 0 && <span className="num shrink-0 text-[11.5px] text-ink-3">{tool.sources.length} {tool.sources.length === 1 ? 'page' : 'pages'}</span>}
<ChevronRight className={cx('size-3.5 shrink-0 text-ink-3 opacity-0 transition group-hover:opacity-100', open && 'rotate-90 opacity-100')} />
</button>
{open && <Details tool={tool} />}
</div>
);
}
/** Steps that ran back to back. More than three finished steps fold into one line. */
export function ToolSteps({ tools, compact }: { tools: ToolActivity[]; compact?: boolean }) {
const [open, setOpen] = useState(false);
const running = tools.some((t) => t.status === 'running');
if (tools.length <= 3 || running) {
return (
<div className="space-y-0.5">
{tools.map((t) => (
<ToolStep key={t.id} tool={t} compact={compact} />
))}
</div>
);
}
const failed = tools.filter((t) => t.status === 'error').length;
return (
<div>
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className={cx('group flex items-center gap-2.5 rounded-lg py-1 pr-2 text-left text-ink-2 hover:text-ink', compact ? 'text-[12.5px]' : 'text-[13.5px]')}>
<span className="flex -space-x-1.5">
{tools.slice(0, 3).map((t) => (
<span key={t.id} className="grid size-[20px] place-items-center rounded-full bg-sunken text-ink-3 ring-2 ring-paper [&>svg]:size-[12px]">
{iconFor({ ...t, status: 'done' })}
</span>
))}
</span>
<span>
{tools.length} steps{failed ? <span className="text-bad"> · {failed} failed</span> : null}
</span>
<ChevronRight className={cx('size-3.5 text-ink-3 transition', open && 'rotate-90')} />
</button>
{open && (
<div className="mt-0.5 space-y-0.5 pl-1">
{tools.map((t) => (
<ToolStep key={t.id} tool={t} compact={compact} />
))}
</div>
)}
</div>
);
}

View file

@ -0,0 +1,159 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { CircleAlert, CircleCheck, Globe, LogIn, LogOut, ShieldCheck } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { timeAgo } from '@/lib/util';
import { Badge, Button, Callout, Field, Section, Switch, Textarea, useConfirm } from '@/ui';
import { AREAS, startMcpSignIn, type McpServer } from './McpSettings';
const KEY = ['ai', 'web-search'];
/** The built-in web search (Parallel): on or off, where it is used, guidance, and an optional account. */
export function WebSearchSettings() {
const qc = useQueryClient();
const confirm = useConfirm();
const q = useQuery({ queryKey: KEY, queryFn: () => api.get<{ webSearch: McpServer }>('/api/ai/web-search').then((r) => r.webSearch) });
const [instructions, setInstructions] = useState('');
const [testing, setTesting] = useState(false);
const [signingIn, setSigningIn] = useState(false);
const [tools, setTools] = useState<string[] | null>(null);
const ws = q.data;
useEffect(() => {
if (ws) setInstructions(ws.instructions);
}, [ws?.instructions]); // eslint-disable-line react-hooks/exhaustive-deps
const patch = async (body: Record<string, unknown>) => {
try {
const res = await api.patch<{ webSearch: McpServer }>('/api/ai/web-search', body);
qc.setQueryData(KEY, res.webSearch);
void qc.invalidateQueries({ queryKey: ['ai', 'chat-tools'] });
} catch (e) {
toast.error(errorMessage(e));
}
};
const test = async () => {
setTesting(true);
try {
const res = await api.post<{ result: { ok: boolean; message: string; tools: { name: string }[] }; webSearch: McpServer }>('/api/ai/web-search/test');
qc.setQueryData(KEY, res.webSearch);
if (res.result.ok) {
toast.success(res.result.message);
setTools(res.result.tools.map((t) => t.name));
} else toast.error(res.result.message);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setTesting(false);
}
};
const signOut = async () => {
if (!(await confirm({ title: 'Sign out of Parallel?', message: 'Web search keeps working on the free tier, with lower limits.', confirmLabel: 'Sign out' }))) return;
try {
await api.del(`/api/ai/mcp/${ws?.id}/oauth`);
void qc.invalidateQueries({ queryKey: KEY });
} catch (e) {
toast.error(errorMessage(e));
}
};
if (!ws) return null;
const signedIn = ws.oauth.connected;
return (
<>
<Section title="Web search">
<div className="card p-4 sm:p-5">
<div className="flex items-start gap-3.5">
<span className="grid size-11 shrink-0 place-items-center rounded-[12px] bg-accent-soft text-accent">
<Globe className="size-5" />
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-[15px] font-semibold">Search the web</h3>
{ws.enabled ? <Badge tone="good">On</Badge> : <Badge>Off</Badge>}
</div>
<p className="mt-0.5 text-[13.5px] text-ink-2">Lets the AI look up current guidelines, drug information and anything your own material doesn't cover, then cite the pages it used. Searches run through Parallel and work without an account.</p>
</div>
<Switch checked={ws.enabled} onChange={(v) => patch({ enabled: v })} label={<span className="sr-only">Use web search</span>} />
</div>
{ws.lastTestAt && (
<div className={`mt-3 flex items-center gap-1.5 text-xs ${ws.lastTestOk ? 'text-good' : 'text-bad'}`}>
{ws.lastTestOk ? <CircleCheck className="size-3.5 shrink-0" /> : <CircleAlert className="size-3.5 shrink-0" />}
<span className="min-w-0 break-words">{ws.lastTestMessage}</span>
</div>
)}
<div className="mt-4 flex flex-wrap gap-2">
<Button size="sm" variant="secondary" loading={testing} onClick={test}>
Test the connection
</Button>
</div>
{tools && <p className="mt-2 text-xs text-ink-3">Tools available: {tools.join(', ')}</p>}
</div>
</Section>
<Section title="Parallel account">
<div className="card p-4 sm:p-5">
{signedIn ? (
<div className="flex flex-wrap items-center gap-3">
<ShieldCheck className="size-5 shrink-0 text-good" />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">Signed in</div>
<div className="text-[13px] text-ink-3">Higher rate limits{ws.oauth.connectedAt ? ` · connected ${timeAgo(ws.oauth.connectedAt)}` : ''}. Usage counts against your Parallel account.</div>
</div>
<Button size="sm" variant="ghost" icon={<LogOut />} onClick={signOut}>
Sign out
</Button>
</div>
) : (
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">Free tier, no account</div>
<div className="text-[13px] text-ink-3">Sign in with a Parallel account for higher rate limits and in-depth research.</div>
</div>
<Button
size="sm"
variant="primary"
icon={<LogIn />}
loading={signingIn}
onClick={async () => {
setSigningIn(true);
await startMcpSignIn(ws.id, '/settings/web').catch((e) => toast.error(errorMessage(e)));
setSigningIn(false);
}}
>
Sign in to Parallel
</Button>
</div>
)}
<div className="mt-4 border-t border-line pt-4">
<Switch
checked={ws.options.research}
disabled={!signedIn}
onChange={(v) => patch({ research: v })}
label="Allow in-depth research"
description={signedIn ? 'The AI may run a slower research call for hard questions. Each one uses your Parallel credits.' : 'Needs a signed-in account.'}
/>
</div>
</div>
</Section>
<Section title="When and where to use it">
<div className="card space-y-5 p-4 sm:p-5">
<Field label="Your guidance for the AI" optional hint="For example: Only for current drug information and guidelines. Never for questions my course material answers.">
<Textarea rows={3} value={instructions} maxLength={2000} onChange={(e) => setInstructions(e.target.value)} onBlur={() => instructions !== ws.instructions && patch({ instructions })} placeholder="Use the web for…" />
</Field>
<fieldset className="space-y-3">
<legend className="mb-2 text-sm font-medium text-ink">Where it can be used</legend>
{AREAS.map((a) => (
<Switch key={a.key} checked={ws.areas[a.key]} onChange={(v) => patch({ areas: { [a.key]: v } })} label={a.label} description={a.key === 'share' ? 'Explain and Ask on links you share, when those are on. Searches run through your account if you are signed in.' : a.description} />
))}
</fieldset>
</div>
<Callout tone="neutral" className="mt-3 text-[13px]">
Only the search words and page addresses the AI writes are sent to Parallel, never your documents. You can switch web search off for a single conversation from the assistant's tools button.
</Callout>
</Section>
</>
);
}

View file

@ -154,7 +154,7 @@ export function MoveDialog({ target, onClose }: { target: { kind: EditableKind;
</Field>
<Field label="Folder">
<Select value={folderId} onChange={(e) => setFolderId(e.target.value)} disabled={detail.isLoading}>
<option value="">No folder</option>
<option value="">{`Not in a${/^[aeiou]/i.test(detail.data?.class.groupLabel ?? 'folder') ? 'n' : ''} ${(detail.data?.class.groupLabel ?? 'folder').toLowerCase()}`}</option>
{(detail.data?.folders ?? []).map((f) => (
<option key={f.id} value={f.id}>
{f.name}
@ -169,7 +169,7 @@ export function MoveDialog({ target, onClose }: { target: { kind: EditableKind;
/* ------------------------------ new item ------------------------------ */
export function NewItemDialog({ kind, classId, folderId, onClose }: { kind: 'quiz' | 'deck' | 'note' | 'folder' | null; classId: string; folderId?: string | null; onClose: () => void }) {
export function NewItemDialog({ kind, classId, folderId, onClose, groupLabel = 'Folder' }: { kind: 'quiz' | 'deck' | 'note' | 'folder' | null; classId: string; folderId?: string | null; onClose: () => void; groupLabel?: string }) {
const refresh = useRefresh();
const navigate = useNavigate();
const [title, setTitle] = useState('');
@ -219,8 +219,8 @@ export function NewItemDialog({ kind, classId, folderId, onClose }: { kind: 'qui
}
};
const labels = { quiz: 'New quiz', deck: 'New flashcard deck', note: 'New note', folder: 'New folder' };
const placeholders = { quiz: 'Cardiac medications', deck: 'Lab values', note: 'Exam 2 review', folder: 'Unit 3' };
const labels = { quiz: 'New quiz', deck: 'New flashcard deck', note: 'New note', folder: `New ${groupLabel.toLowerCase()}` };
const placeholders = { quiz: 'Cardiac medications', deck: 'Lab values', note: 'Exam 2 review', folder: `${groupLabel} 3` };
return (
<Dialog
open={kind !== null}
@ -280,7 +280,7 @@ const SHARE_BLURB: Record<ShareKind, string> = {
deck: 'Anyone with the link can study these flashcards. They cannot change them.',
note: 'Anyone with the link can read this note.',
document: 'Anyone with the link can view and download this file.',
folder: 'Anyone with the link can study the quizzes, decks and notes in this folder and view or download its documents.',
folder: 'Anyone with the link can study the quizzes, decks and notes in this exam (or folder) and read or download its documents.',
class: 'Anyone with the link can study every quiz, deck and note in this class and view or download its documents.',
};

View file

@ -5,7 +5,7 @@ import type { AnswerState, SnapshotQuestion } from '@/lib/types';
import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Badge, Button, Dialog, IconButton, Input, ProgressBar, Segmented, useConfirm } from '@/ui';
import { Ring } from './charts';
import { ExplainSideContext } from './Explain';
/* ------------------------------ option list ------------------------------ */
@ -398,7 +398,7 @@ export function QuizRunner(p: RunnerProps) {
<Markdown className="text-[15px]">{question.rationale}</Markdown>
</div>
)}
{p.renderExtra?.(question, answerTexts(question, selected))}
<ExplainSideContext.Provider value>{p.renderExtra?.(question, answerTexts(question, selected))}</ExplainSideContext.Provider>
</div>
)}
</div>
@ -482,6 +482,80 @@ export function QuizRunner(p: RunnerProps) {
/* ------------------------------ results ------------------------------ */
type ScoreTier = 'perfect' | 'a' | 'b' | 'c' | 'fail';
/** Bands of the 7-point scale: 93+ green, 85-92 blue, 77-84 yellow, below 77 (failing) red; 100% is a rainbow. */
export function scoreTier(percent: number): ScoreTier {
const p = Math.round(percent);
return p >= 100 ? 'perfect' : p >= 93 ? 'a' : p >= 85 ? 'b' : p >= 77 ? 'c' : 'fail';
}
const TIER_COLOR: Record<Exclude<ScoreTier, 'perfect'>, string> = { a: 'var(--good)', b: 'var(--accent)', c: 'var(--score-yellow)', fail: 'var(--bad)' };
/** The result ring: fills up and counts to the score; a perfect score cycles through a rainbow. */
function ScoreRing({ percent, size = 136, stroke = 12 }: { percent: number; size?: number; stroke?: number }) {
const tier = scoreTier(percent);
const [shown, setShown] = useState(0);
useEffect(() => {
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return setShown(percent);
let frame = 0;
const started = performance.now();
const tick = (now: number) => {
const t = Math.min(1, (now - started) / 1100);
setShown(Math.round(percent * (1 - (1 - t) ** 3)));
if (t < 1) frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, [percent]);
const r = (size - stroke) / 2;
const c = 2 * Math.PI * r;
const gid = `score-${size}`;
return (
<div className="relative shrink-0" style={{ width: size, height: size }} role="img" aria-label={`Score ${percent} percent`}>
<svg width={size} height={size} className={cx('-rotate-90', tier === 'perfect' && 'ring-rainbow')} aria-hidden>
{tier === 'perfect' && (
<defs>
<linearGradient id={gid} x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#ff4d6d" />
<stop offset="20%" stopColor="#ff9f1c" />
<stop offset="40%" stopColor="#ffd60a" />
<stop offset="60%" stopColor="#2ec27e" />
<stop offset="80%" stopColor="#3a86ff" />
<stop offset="100%" stopColor="#9b5de5" />
</linearGradient>
</defs>
)}
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line)" strokeWidth={stroke} />
<circle
cx={size / 2}
cy={size / 2}
r={r}
fill="none"
stroke={tier === 'perfect' ? `url(#${gid})` : TIER_COLOR[tier]}
strokeWidth={stroke}
strokeLinecap="round"
strokeDasharray={c}
strokeDashoffset={c * (1 - shown / 100)}
/>
</svg>
<div className="absolute inset-0 grid place-items-center">
<span className="num display text-[38px] leading-none font-medium">
{shown}
<span className="text-[20px] text-ink-3">%</span>
</span>
</div>
{tier === 'perfect' && shown === 100 && (
<span className="pointer-events-none absolute inset-0" aria-hidden>
{[0, 1, 2, 3, 4, 5, 6, 7].map((i) => (
<span key={i} className="score-spark absolute top-1/2 left-1/2 size-2 rounded-full" style={{ ['--a' as string]: `${i * 45}deg`, background: ['#ff4d6d', '#ff9f1c', '#ffd60a', '#2ec27e', '#3a86ff', '#9b5de5', '#ff4d6d', '#2ec27e'][i] }} />
))}
</span>
)}
</div>
);
}
export interface ResultsProps {
title: string;
mode: 'practice' | 'exam';
@ -517,8 +591,6 @@ export function QuizResults(p: ResultsProps) {
const partial = scored.filter((r) => !r.correct && r.score > 0).length;
const wrong = scored.length - right - partial;
const skipped = rows.length - scored.length;
const tone = gradeToneFor(percent);
const grade = letterGrade(percent);
const topics = useMemo(() => {
const map = new Map<string, { n: number; s: number }>();
@ -533,7 +605,8 @@ export function QuizResults(p: ResultsProps) {
}, [scored]);
const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id)));
const headline = { A: 'Excellent work', B: 'Strong result', C: 'Passing', D: 'Just below passing', F: 'Worth another pass' }[grade];
const tier = scoreTier(percent);
const headline = { perfect: 'Perfect score!', a: 'Excellent work', b: 'Strong result', c: 'Passing', fail: 'Worth another pass' }[tier];
return (
<div className="min-h-dvh bg-paper">
@ -548,14 +621,9 @@ export function QuizResults(p: ResultsProps) {
<main className="mx-auto max-w-3xl animate-in px-4 pt-8 pb-24 sm:px-5">
<section className="card p-6 sm:p-8">
<div className="flex flex-col items-center gap-6 text-center sm:flex-row sm:text-left">
<Ring value={percent / 100} size={128} stroke={11} tone={tone}>
<div className="flex flex-col items-center leading-none">
<span className="display text-[40px] font-medium">{grade}</span>
<span className="num mt-1 text-[13px] font-medium text-ink-3">{percent}%</span>
</div>
</Ring>
<ScoreRing percent={percent} />
<div className="min-w-0 flex-1">
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'} · grade {grade}</div>
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
<h1 className="display text-[30px]">{headline}</h1>
<p className="mt-1.5 text-[15px] text-ink-2">
<span className="num font-semibold text-ink">{fmtPoints(points)}</span> of <span className="num font-semibold text-ink">{scored.length}</span> points

View file

@ -0,0 +1,54 @@
/** One interactive block from a reply, rendered with OpenUI's streaming renderer. Loaded lazily. */
import { BuiltinActionType, Renderer, type ActionEvent, type ParseResult } from '@openuidev/react-lang';
import { Code2, LayoutTemplate } from 'lucide-react';
import { Component, useState, type ReactNode } from 'react';
import { genUiLibrary } from './library';
class Boundary extends Component<{ fallback: ReactNode; children: ReactNode }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
return this.state.failed ? this.props.fallback : this.props.children;
}
}
function Fallback({ source }: { source: string }) {
const [open, setOpen] = useState(false);
return (
<div className="rounded-[12px] border border-dashed border-line-strong px-3.5 py-2.5 text-[13px] text-ink-3">
<button type="button" onClick={() => setOpen(!open)} className="flex items-center gap-1.5 hover:text-ink">
<Code2 className="size-3.5" /> This interactive part could not be shown. {open ? 'Hide' : 'Show'} its source
</button>
{open && <pre className="mt-2 max-h-60 overflow-auto rounded-lg bg-sunken p-2.5 text-[11.5px] whitespace-pre-wrap">{source}</pre>}
</div>
);
}
export default function GenUiBlock({ source, streaming, onSend }: { source: string; streaming: boolean; onSend?: (text: string) => void }) {
const [parsed, setParsed] = useState<ParseResult | null>(null);
const onAction = (event: ActionEvent) => {
if (event.type === BuiltinActionType.ContinueConversation) {
const message = event.humanFriendlyMessage?.trim();
if (message) onSend?.(message);
} else if (event.type === BuiltinActionType.OpenUrl) {
const url = String(event.params?.url ?? '');
if (/^https?:\/\//i.test(url)) window.open(url, '_blank', 'noopener,noreferrer');
}
};
const empty = !parsed?.root;
return (
<div className="genui not-prose my-3 animate-in">
{empty && streaming && (
<div className="flex h-16 items-center gap-2 rounded-[14px] border border-line bg-surface px-4 text-[13px] text-ink-3">
<LayoutTemplate className="size-4 animate-pulse text-accent" /> Building…
</div>
)}
{empty && !streaming && parsed !== null && <Fallback source={source} />}
<Boundary fallback={<Fallback source={source} />}>
<Renderer response={source} library={genUiLibrary} isStreaming={streaming} onAction={onAction} onParseResult={setParsed} />
</Boundary>
</div>
);
}

425
web/src/genui/charts.tsx Normal file
View file

@ -0,0 +1,425 @@
/**
* Charts for generated replies: plain SVG, sized to the chat column, drawn with the app's
* categorical series tokens (--series-1…8, validated for colour-vision deficiency in both themes).
* Every chart has a hover read-out and a table view, so no value depends on colour alone.
*/
import { Table2 } from 'lucide-react';
import { useId, useMemo, useState, type ReactNode } from 'react';
import { cx } from '@/lib/util';
export interface ChartSeries {
name: string;
values: (number | null)[];
}
const W = 560;
const SERIES_MAX = 8;
const color = (i: number) => `var(--series-${(i % SERIES_MAX) + 1})`;
const fmt = (v: number, unit?: string) => {
const abs = Math.abs(v);
const n = abs >= 10_000 ? `${(v / 1000).toLocaleString(undefined, { maximumFractionDigits: 1 })}K` : v.toLocaleString(undefined, { maximumFractionDigits: abs < 10 ? 2 : 1 });
if (!unit) return n;
return unit === '%' ? `${n}%` : `${n} ${unit}`;
};
/** Clean tick values from 0 (or the minimum, when negative) to just above the maximum. */
function niceTicks(min: number, max: number, count = 4): number[] {
const lo = Math.min(0, min);
const hi = max <= lo ? lo + 1 : max;
const raw = (hi - lo) / count;
const mag = 10 ** Math.floor(Math.log10(raw));
const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;
const start = Math.floor(lo / step) * step;
const ticks: number[] = [];
for (let v = start; v <= hi + step * 0.001; v += step) ticks.push(Number(v.toFixed(10)));
if (ticks[ticks.length - 1] < hi) ticks.push(Number((ticks[ticks.length - 1] + step).toFixed(10)));
return ticks;
}
function Legend({ items }: { items: { name: string; i: number; value?: string }[] }) {
return (
<ul className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-[12px] text-ink-2">
{items.map((it) => (
<li key={it.i} className="flex items-center gap-1.5">
<span className="size-2.5 shrink-0 rounded-[3px]" style={{ background: color(it.i) }} aria-hidden />
{it.name}
{it.value && <span className="num text-ink-3">{it.value}</span>}
</li>
))}
</ul>
);
}
function ChartFrame({ title, children, table, legend }: { title?: string; children: ReactNode; table: { columns: string[]; rows: (string | number)[][] }; legend?: ReactNode }) {
const [asTable, setAsTable] = useState(false);
return (
<figure className="genui-chart rounded-[14px] border border-line bg-surface p-3.5">
<figcaption className="mb-2 flex items-center gap-2">
{title ? <span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold">{title}</span> : <span className="flex-1" />}
<button type="button" onClick={() => setAsTable(!asTable)} aria-pressed={asTable} className={cx('flex h-6 items-center gap-1 rounded-md px-1.5 text-[11px] font-medium', asTable ? 'bg-ink/8 text-ink' : 'text-ink-3 hover:text-ink')}>
<Table2 className="size-3.5" /> Table
</button>
</figcaption>
{asTable ? (
<div className="table-wrap md text-[13px]">
<table>
<thead>
<tr>
{table.columns.map((c, i) => (
<th key={i}>{c}</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((r, i) => (
<tr key={i}>
{r.map((v, j) => (
<td key={j} className={typeof v === 'number' ? 'num' : undefined}>
{v}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
) : (
<>
{children}
{legend}
</>
)}
</figure>
);
}
function Tooltip({ x, y, h, children }: { x: number; y: number; h: number; children: ReactNode }) {
// Positioned in viewBox units, converted to percentages so it follows the responsive SVG.
const left = Math.min(Math.max(x / W, 0.12), 0.88) * 100;
return (
<div className="pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-full rounded-lg border border-line bg-surface px-2.5 py-1.5 text-[12px] whitespace-nowrap shadow-2" style={{ left: `${left}%`, top: `${Math.max(0, (y / h) * 100)}%` }}>
{children}
</div>
);
}
/* ------------------------------ bar ------------------------------ */
export function BarChart({ labels, series, title, unit, stacked, horizontal }: { labels: string[]; series: ChartSeries[]; title?: string; unit?: string; stacked?: boolean; horizontal?: boolean }) {
const [hover, setHover] = useState<number | null>(null);
const shown = series.slice(0, SERIES_MAX);
const n = labels.length;
const totals = labels.map((_, i) => shown.reduce((s, x) => s + Math.max(0, x.values[i] ?? 0), 0));
const all = shown.flatMap((s) => s.values.filter((v): v is number => v !== null && Number.isFinite(v)));
const ticks = niceTicks(Math.min(0, ...all), stacked ? Math.max(0, ...totals) : Math.max(0, ...all));
const lo = ticks[0];
const hi = ticks[ticks.length - 1];
const table = { columns: ['', ...shown.map((s) => s.name)], rows: labels.map((l, i) => [l, ...shown.map((s) => s.values[i] ?? '')]) };
const legend = shown.length > 1 ? <Legend items={shown.map((s, i) => ({ name: s.name, i }))} /> : null;
if (horizontal) {
const rowH = Math.max(26, Math.min(40, 18 + shown.length * (stacked ? 0 : 10)));
const labelW = 150;
const H = n * rowH + 24;
const scale = (v: number) => labelW + ((v - lo) / (hi - lo)) * (W - labelW - 40);
return (
<ChartFrame title={title} table={table} legend={legend}>
<div className="relative">
<svg viewBox={`0 0 ${W} ${H}`} className="w-full" role="img" aria-label={title ?? 'Bar chart'}>
{ticks.map((t) => (
<g key={t}>
<line x1={scale(t)} x2={scale(t)} y1={0} y2={H - 20} className="stroke-line" strokeWidth={1} />
<text x={scale(t)} y={H - 6} textAnchor="middle" className="fill-ink-3 text-[11px]">
{fmt(t, unit === '%' ? '%' : undefined)}
</text>
</g>
))}
{labels.map((label, i) => {
const y = i * rowH + 4;
const inner = rowH - 10;
const barH = stacked ? Math.min(20, inner) : Math.min(20, (inner - (shown.length - 1) * 2) / shown.length);
let acc = 0;
return (
<g key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
<rect x={0} y={y - 2} width={W} height={rowH} fill="transparent" />
<text x={labelW - 8} y={y + inner / 2 + 4} textAnchor="end" className="fill-ink-2 text-[12px]">
{label.length > 22 ? `${label.slice(0, 21)}…` : label}
</text>
{shown.map((s, si) => {
const v = s.values[i] ?? 0;
const x0 = stacked ? scale(acc) : scale(Math.min(0, v));
const x1 = stacked ? scale(acc + Math.max(0, v)) : scale(Math.max(0, v));
if (stacked) acc += Math.max(0, v);
const by = stacked ? y + (inner - barH) / 2 : y + si * (barH + 2);
return <rect key={si} x={x0 + (stacked && si > 0 ? 1 : 0)} y={by} width={Math.max(0, x1 - x0 - (stacked && si > 0 ? 1 : 0))} height={barH} rx={3} fill={color(si)} opacity={hover === null || hover === i ? 1 : 0.45} />;
})}
{!stacked && shown.length === 1 && (
<text x={scale(Math.max(0, shown[0].values[i] ?? 0)) + 6} y={y + inner / 2 + 4} className="num fill-ink-2 text-[11px]">
{shown[0].values[i] !== null ? fmt(shown[0].values[i] as number, unit) : ''}
</text>
)}
</g>
);
})}
</svg>
{hover !== null && shown.length > 1 && (
<Tooltip x={W / 2} y={hover * rowH} h={H}>
<div className="font-semibold">{labels[hover]}</div>
{shown.map((s, si) => (
<div key={si} className="flex items-center gap-1.5">
<span className="size-2 rounded-[2px]" style={{ background: color(si) }} />
{s.name}: <span className="num">{s.values[hover] !== null ? fmt(s.values[hover] as number, unit) : '—'}</span>
</div>
))}
</Tooltip>
)}
</div>
</ChartFrame>
);
}
const H = 230;
const top = 12;
const bottom = 36;
const left = 44;
const plotW = W - left - 8;
const band = plotW / Math.max(1, n);
const y = (v: number) => top + (1 - (v - lo) / (hi - lo)) * (H - top - bottom);
const groupW = Math.min(band * 0.72, stacked ? 24 : 24 * shown.length + 2 * (shown.length - 1));
const barW = stacked ? groupW : (groupW - 2 * (shown.length - 1)) / shown.length;
const every = Math.ceil(n / Math.max(1, Math.floor(plotW / 64)));
return (
<ChartFrame title={title} table={table} legend={legend}>
<div className="relative">
<svg viewBox={`0 0 ${W} ${H}`} className="w-full" role="img" aria-label={title ?? 'Bar chart'}>
{ticks.map((t) => (
<g key={t}>
<line x1={left} x2={W - 4} y1={y(t)} y2={y(t)} className="stroke-line" strokeWidth={1} />
<text x={left - 6} y={y(t) + 4} textAnchor="end" className="num fill-ink-3 text-[11px]">
{fmt(t, unit === '%' ? '%' : undefined)}
</text>
</g>
))}
{labels.map((label, i) => {
const cx0 = left + band * i + band / 2;
let acc = 0;
return (
<g key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
<rect x={left + band * i} y={top} width={band} height={H - top - bottom} fill={hover === i ? 'var(--ink)' : 'transparent'} opacity={hover === i ? 0.04 : 1} />
{shown.map((s, si) => {
const v = s.values[i];
if (v === null || v === undefined) return null;
const x = stacked ? cx0 - groupW / 2 : cx0 - groupW / 2 + si * (barW + 2);
const y0 = stacked ? y(acc) : y(Math.max(0, v));
const y1 = stacked ? y(acc + Math.max(0, v)) : y(Math.min(0, v));
if (stacked) acc += Math.max(0, v);
const top0 = Math.min(y0, y1);
const h = Math.max(0, Math.abs(y1 - y0) - (stacked && si > 0 ? 2 : 0));
return <path key={si} d={roundedTop(x, top0, barW, h, Math.min(4, barW / 2, h))} fill={color(si)} opacity={hover === null || hover === i ? 1 : 0.45} />;
})}
{i % every === 0 && (
<text x={cx0} y={H - bottom + 16} textAnchor="middle" className="fill-ink-2 text-[11.5px]">
{label.length > 12 ? `${label.slice(0, 11)}…` : label}
</text>
)}
</g>
);
})}
</svg>
{hover !== null && (
<Tooltip x={left + band * hover + band / 2} y={y(stacked ? totals[hover] : Math.max(0, ...shown.map((s) => s.values[hover] ?? 0))) - 6} h={H}>
<div className="font-semibold">{labels[hover]}</div>
{shown.map((s, si) => (
<div key={si} className="flex items-center gap-1.5">
{shown.length > 1 && <span className="size-2 rounded-[2px]" style={{ background: color(si) }} />}
{shown.length > 1 ? `${s.name}: ` : ''}
<span className="num">{s.values[hover] !== null && s.values[hover] !== undefined ? fmt(s.values[hover] as number, unit) : '—'}</span>
</div>
))}
</Tooltip>
)}
</div>
</ChartFrame>
);
}
/** A bar with a rounded data end and a square baseline. */
function roundedTop(x: number, y: number, w: number, h: number, r: number): string {
if (h <= 0 || w <= 0) return '';
r = Math.max(0, Math.min(r, h));
return `M${x},${y + h} V${y + r} Q${x},${y} ${x + r},${y} H${x + w - r} Q${x + w},${y} ${x + w},${y + r} V${y + h} Z`;
}
/* ------------------------------ line ------------------------------ */
export function LineChart({ labels, series, title, unit, area }: { labels: string[]; series: ChartSeries[]; title?: string; unit?: string; area?: boolean }) {
const [hover, setHover] = useState<number | null>(null);
const gid = useId();
const shown = series.slice(0, SERIES_MAX);
const n = labels.length;
const all = shown.flatMap((s) => s.values.filter((v): v is number => v !== null && Number.isFinite(v)));
const minV = Math.min(...all, 0);
const maxV = Math.max(...all, 0);
// Values far from zero (blood pressures, weights) get an axis that starts near them.
const fromZero = minV >= 0 && (maxV === 0 || Math.min(...all) / maxV < 0.5);
const ticks = fromZero ? niceTicks(0, maxV) : niceTicks(Math.min(...all), maxV).filter((t, i, arr) => i === 0 || t > Math.min(...all) - (arr[1] - arr[0]));
const lo = fromZero ? 0 : Math.min(ticks[0], Math.min(...all));
const hi = ticks[ticks.length - 1];
const H = 230;
const top = 14;
const bottom = 36;
const left = 44;
const right = 14;
const x = (i: number) => left + (n <= 1 ? (W - left - right) / 2 : (i / (n - 1)) * (W - left - right));
const y = (v: number) => top + (1 - (v - lo) / (hi - lo || 1)) * (H - top - bottom);
const every = Math.ceil(n / Math.max(1, Math.floor((W - left - right) / 64)));
const table = { columns: ['', ...shown.map((s) => s.name)], rows: labels.map((l, i) => [l, ...shown.map((s) => s.values[i] ?? '')]) };
const legend = shown.length > 1 ? <Legend items={shown.map((s, i) => ({ name: s.name, i }))} /> : null;
const paths = useMemo(
() =>
shown.map((s) => {
let d = '';
let pen = false;
s.values.forEach((v, i) => {
if (v === null || v === undefined || !Number.isFinite(v)) {
pen = false;
return;
}
d += `${pen ? 'L' : 'M'}${x(i).toFixed(1)},${y(v).toFixed(1)} `;
pen = true;
});
return d;
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[series, lo, hi, n],
);
return (
<ChartFrame title={title} table={table} legend={legend}>
<div className="relative">
<svg
viewBox={`0 0 ${W} ${H}`}
className="w-full"
role="img"
aria-label={title ?? 'Line chart'}
onMouseMove={(e) => {
const r = e.currentTarget.getBoundingClientRect();
const px = ((e.clientX - r.left) / r.width) * W;
const i = n <= 1 ? 0 : Math.round(((px - left) / (W - left - right)) * (n - 1));
setHover(Math.max(0, Math.min(n - 1, i)));
}}
onMouseLeave={() => setHover(null)}
>
{ticks.map((t) => (
<g key={t}>
<line x1={left} x2={W - right} y1={y(t)} y2={y(t)} className="stroke-line" strokeWidth={1} />
<text x={left - 6} y={y(t) + 4} textAnchor="end" className="num fill-ink-3 text-[11px]">
{fmt(t, unit === '%' ? '%' : undefined)}
</text>
</g>
))}
{labels.map((l, i) =>
i % every === 0 || i === n - 1 ? (
<text key={i} x={x(i)} y={H - bottom + 16} textAnchor={i === 0 && n > 1 ? 'start' : i === n - 1 && n > 1 ? 'end' : 'middle'} className="fill-ink-2 text-[11.5px]">
{l.length > 12 ? `${l.slice(0, 11)}…` : l}
</text>
) : null,
)}
{hover !== null && <line x1={x(hover)} x2={x(hover)} y1={top} y2={H - bottom} className="stroke-ink-3" strokeWidth={1} />}
{shown.map((s, si) => (
<g key={si}>
{area && paths[si] && (
<>
<defs>
<linearGradient id={`${gid}-${si}`} x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stopColor={color(si)} stopOpacity={0.16} />
<stop offset="100%" stopColor={color(si)} stopOpacity={0.02} />
</linearGradient>
</defs>
<path d={`${paths[si]} L${x(lastIndex(s.values))},${y(lo)} L${x(firstIndex(s.values))},${y(lo)} Z`} fill={`url(#${gid}-${si})`} />
</>
)}
<path d={paths[si]} fill="none" stroke={color(si)} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" className="genui-draw" />
{s.values.map((v, i) =>
v !== null && v !== undefined && (i === lastIndex(s.values) || hover === i || n <= 12) ? (
<circle key={i} cx={x(i)} cy={y(v)} r={hover === i ? 5 : 4} fill={color(si)} className="stroke-surface" strokeWidth={2} />
) : null,
)}
</g>
))}
</svg>
{hover !== null && (
<Tooltip x={x(hover)} y={Math.min(...shown.map((s) => (s.values[hover] !== null && s.values[hover] !== undefined ? y(s.values[hover] as number) : H))) - 8} h={H}>
<div className="font-semibold">{labels[hover]}</div>
{shown.map((s, si) => (
<div key={si} className="flex items-center gap-1.5">
{shown.length > 1 && <span className="size-2 rounded-full" style={{ background: color(si) }} />}
{shown.length > 1 ? `${s.name}: ` : ''}
<span className="num">{s.values[hover] !== null && s.values[hover] !== undefined ? fmt(s.values[hover] as number, unit) : '—'}</span>
</div>
))}
</Tooltip>
)}
</div>
</ChartFrame>
);
}
const firstIndex = (v: (number | null)[]) => Math.max(0, v.findIndex((x) => x !== null && x !== undefined));
const lastIndex = (v: (number | null)[]) => {
for (let i = v.length - 1; i >= 0; i -= 1) if (v[i] !== null && v[i] !== undefined) return i;
return 0;
};
/* ------------------------------ pie ------------------------------ */
export function PieChart({ slices, title, unit, donut }: { slices: { label: string; value: number }[]; title?: string; unit?: string; donut?: boolean }) {
const [hover, setHover] = useState<number | null>(null);
const shown = slices.filter((s) => Number.isFinite(s.value) && s.value > 0).slice(0, SERIES_MAX);
const total = shown.reduce((s, x) => s + x.value, 0) || 1;
const size = 180;
const r = size / 2 - 4;
const inner = donut === false ? 0 : r * 0.58;
let angle = -Math.PI / 2;
const pct = (v: number) => `${Math.round((v / total) * 100)}%`;
const table = { columns: ['', 'Value', 'Share'], rows: shown.map((s) => [s.label, unit ? fmt(s.value, unit) : s.value, pct(s.value)]) };
return (
<ChartFrame title={title} table={table}>
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-center">
<svg viewBox={`0 0 ${size} ${size}`} className="w-40 shrink-0" role="img" aria-label={title ?? 'Pie chart'}>
{shown.map((s, i) => {
const sweep = (s.value / total) * Math.PI * 2;
const a0 = angle;
const a1 = angle + sweep;
angle = a1;
const c = size / 2;
const big = sweep > Math.PI ? 1 : 0;
const p = (rad: number, a: number) => `${c + rad * Math.cos(a)},${c + rad * Math.sin(a)}`;
const d =
shown.length === 1
? `M${c - r},${c} a${r},${r} 0 1,0 ${2 * r},0 a${r},${r} 0 1,0 ${-2 * r},0 ${inner ? `M${c - inner},${c} a${inner},${inner} 0 1,1 ${2 * inner},0 a${inner},${inner} 0 1,1 ${-2 * inner},0` : ''}`
: inner
? `M${p(r, a0)} A${r},${r} 0 ${big} 1 ${p(r, a1)} L${p(inner, a1)} A${inner},${inner} 0 ${big} 0 ${p(inner, a0)} Z`
: `M${c},${c} L${p(r, a0)} A${r},${r} 0 ${big} 1 ${p(r, a1)} Z`;
return <path key={i} d={d} fill={color(i)} fillRule="evenodd" className="stroke-surface" strokeWidth={2} opacity={hover === null || hover === i ? 1 : 0.5} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} />;
})}
{inner > 0 && (
<text x={size / 2} y={size / 2 + 5} textAnchor="middle" className="num fill-ink text-[15px] font-semibold">
{hover !== null ? pct(shown[hover].value) : unit ? fmt(total, unit) : total.toLocaleString()}
</text>
)}
</svg>
<ul className="w-full space-y-1.5 text-[13px]">
{shown.map((s, i) => (
<li key={i} className={cx('flex items-center gap-2 rounded-md px-1.5 py-0.5', hover === i && 'bg-ink/5')} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
<span className="size-2.5 shrink-0 rounded-[3px]" style={{ background: color(i) }} aria-hidden />
<span className="min-w-0 flex-1 truncate">{s.label}</span>
<span className="num text-ink-2">{fmt(s.value, unit)}</span>
<span className="num w-10 text-right text-ink-3">{pct(s.value)}</span>
</li>
))}
</ul>
</div>
</ChartFrame>
);
}

433
web/src/genui/library.tsx Normal file
View file

@ -0,0 +1,433 @@
/**
* React renderers for the generative UI catalog in shared/genui.ts. Everything is drawn with
* the app's own components and tokens, so generated blocks look native in every theme.
*/
import { createLibrary, defineComponent, useIsStreaming, useRenderNode, useStateField, useTriggerAction, type ComponentRenderProps } from '@openuidev/react-lang';
import { Check, ChevronDown, ChevronLeft, ChevronRight, CircleAlert, ExternalLink, Info, Lightbulb, RotateCcw, Sparkles, TriangleAlert, X } from 'lucide-react';
import { useState, type ReactNode } from 'react';
import { GENUI_COMPONENTS, GENUI_GROUPS, GENUI_ROOT } from '@shared/genui';
import { cx } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { BarChart, LineChart, PieChart, type ChartSeries } from './charts';
type Props = Record<string, any>;
type Renderer = (p: ComponentRenderProps<Props>) => ReactNode;
const TONE_TEXT: Record<string, string> = { neutral: 'text-ink', accent: 'text-accent', good: 'text-good', warn: 'text-warn', bad: 'text-bad' };
const TONE_SOFT: Record<string, string> = { neutral: 'bg-sunken text-ink-2', accent: 'bg-accent-soft text-accent', good: 'bg-good-soft text-good', warn: 'bg-warn-soft text-warn', bad: 'bg-bad-soft text-bad' };
const TONE_BAR: Record<string, string> = { neutral: 'bg-ink-3', accent: 'bg-accent', good: 'bg-good', warn: 'bg-warn', bad: 'bg-bad' };
const GAP: Record<string, string> = { s: 'gap-2', m: 'gap-3', l: 'gap-5' };
/** Child nodes may arrive as one node, a list, or null while streaming. */
const list = (v: unknown): unknown[] => (Array.isArray(v) ? v.filter((x) => x !== null && x !== undefined) : v === null || v === undefined ? [] : [v]);
const num = (v: unknown, fallback = 0) => (typeof v === 'number' && Number.isFinite(v) ? v : typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)) ? Number(v) : fallback);
const text = (v: unknown) => (v === null || v === undefined ? '' : typeof v === 'number' ? v.toLocaleString(undefined, { maximumFractionDigits: 2 }) : String(v));
/** Props of nested helper components (Series, Slice, Tab…) arrive as element nodes. */
const propsOf = (node: unknown): Props => (node && typeof node === 'object' && 'props' in (node as object) ? ((node as { props: Props }).props ?? {}) : ((node as Props) ?? {}));
const R: Record<string, Renderer> = {
Stack: ({ props, renderNode }) => (
<div className={cx('flex', props.direction === 'row' ? 'flex-row flex-wrap items-start' : 'flex-col', GAP[props.gap ?? 'm'])}>{renderNode(list(props.children))}</div>
),
Card: ({ props, renderNode }) => (
<section className={cx('rounded-[14px] border bg-surface p-4', props.tone && props.tone !== 'neutral' ? 'border-current/25' : 'border-line', props.tone && props.tone !== 'neutral' && TONE_TEXT[props.tone])}>
{(props.title || props.subtitle) && (
<header className="mb-3">
{props.title && <h4 className="text-[15px] font-semibold text-ink">{props.title}</h4>}
{props.subtitle && <p className="text-[12.5px] text-ink-3">{props.subtitle}</p>}
</header>
)}
<div className="flex flex-col gap-3 text-ink">{renderNode(list(props.children))}</div>
</section>
),
Grid: ({ props, renderNode }) => {
const cols = Math.max(1, Math.min(4, Math.round(num(props.columns, 2))));
return <div className={cx('grid gap-3', cols === 1 ? '' : cols === 2 ? 'sm:grid-cols-2' : cols === 3 ? 'sm:grid-cols-3' : 'grid-cols-2 sm:grid-cols-4')}>{renderNode(list(props.children))}</div>;
},
Tabs: function Tabs({ props, renderNode }) {
const tabs = list(props.tabs).map(propsOf);
const [active, setActive] = useState(0);
const current = tabs[Math.min(active, tabs.length - 1)];
return (
<div>
<div role="tablist" className="mb-3 flex gap-1 overflow-x-auto border-b border-line">
{tabs.map((t, i) => (
<button key={i} type="button" role="tab" aria-selected={i === active} onClick={() => setActive(i)} className={cx('-mb-px shrink-0 border-b-2 px-3 py-1.5 text-[13px] font-medium', i === active ? 'border-accent text-ink' : 'border-transparent text-ink-3 hover:text-ink')}>
{text(t.label)}
</button>
))}
</div>
<div className="flex flex-col gap-3">{current ? renderNode(list(current.children)) : null}</div>
</div>
);
},
Tab: ({ props, renderNode }) => <div className="flex flex-col gap-3">{renderNode(list(props.children))}</div>,
Accordion: ({ props, renderNode }) => (
<div className="divide-y divide-line rounded-[12px] border border-line bg-surface">
{list(props.items).map((item, i) => {
const p = propsOf(item);
return (
<details key={i} className="group">
<summary className="flex cursor-pointer list-none items-center gap-2 px-3.5 py-2.5 text-[14px] font-medium [&::-webkit-details-marker]:hidden">
<span className="flex-1">{text(p.title)}</span>
<ChevronDown className="size-4 text-ink-3 transition-transform group-open:rotate-180" />
</summary>
<div className="flex flex-col gap-3 px-3.5 pb-3.5">{renderNode(list(p.children))}</div>
</details>
);
})}
</div>
),
AccordionItem: ({ props, renderNode }) => <div className="flex flex-col gap-3">{renderNode(list(props.children))}</div>,
Divider: () => <hr className="border-line" />,
Heading: ({ props }) => {
const size = props.size ?? 'm';
return <h4 className={cx('font-semibold text-ink', size === 'l' ? 'display text-[22px]' : size === 's' ? 'text-[13px] tracking-wide text-ink-2 uppercase' : 'text-[16px]')}>{text(props.text)}</h4>;
},
Text: ({ props }) => <Markdown className={cx(props.tone === 'muted' ? 'text-ink-2' : props.tone === 'small' ? 'text-[12.5px] text-ink-3' : '', 'text-[14.5px]')}>{text(props.text)}</Markdown>,
Callout: ({ props }) => {
const tone = props.tone ?? 'info';
const style = { info: ['bg-accent-soft/70 border-accent/25', <Info key="i" className="text-accent" />], tip: ['bg-good-soft/70 border-good/25', <Lightbulb key="t" className="text-good" />], warning: ['bg-warn-soft/80 border-warn/30', <TriangleAlert key="w" className="text-warn" />], danger: ['bg-bad-soft/80 border-bad/30', <CircleAlert key="d" className="text-bad" />] }[tone as 'info'] ?? ['bg-sunken border-line', <Info key="n" />];
return (
<div className={cx('flex gap-2.5 rounded-[12px] border px-3.5 py-3 [&>svg]:mt-0.5 [&>svg]:size-4 [&>svg]:shrink-0', style[0] as string)}>
{style[1]}
<div className="min-w-0 flex-1">
{props.title && <div className="mb-0.5 text-[13.5px] font-semibold">{props.title}</div>}
<Markdown className="text-[14px]">{text(props.text)}</Markdown>
</div>
</div>
);
},
Badge: ({ props }) => <span className={cx('inline-flex h-6 w-fit items-center rounded-full px-2.5 text-[12px] font-medium', TONE_SOFT[props.tone ?? 'neutral'])}>{text(props.label)}</span>,
Stat: ({ props }) => (
<div className="rounded-[12px] border border-line bg-surface px-3.5 py-3">
<div className="text-[12px] font-medium text-ink-3">{text(props.label)}</div>
<div className={cx('num mt-0.5 text-[24px] leading-tight font-semibold', TONE_TEXT[props.tone ?? 'neutral'])}>{text(props.value)}</div>
{props.detail && <div className="mt-0.5 text-[12px] text-ink-3">{props.detail}</div>}
</div>
),
Progress: ({ props }) => {
const max = num(props.max, 100) || 100;
const value = Math.max(0, Math.min(max, num(props.value)));
return (
<div>
<div className="mb-1 flex items-baseline justify-between text-[13px]">
<span className="font-medium">{text(props.label)}</span>
<span className="num text-ink-3">{max === 100 ? `${Math.round(value)}%` : `${text(value)} / ${text(max)}`}</span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-ink/8">
<div className={cx('h-full rounded-full transition-[width] duration-700', TONE_BAR[props.tone ?? 'accent'])} style={{ width: `${(value / max) * 100}%` }} />
</div>
</div>
);
},
Table: ({ props }) => (
<div className="table-wrap md text-[13.5px]">
<table>
{props.caption && <caption className="pb-1.5 text-left text-[12px] text-ink-3">{props.caption}</caption>}
<thead>
<tr>
{list(props.columns).map((c, i) => (
<th key={i}>{text(c)}</th>
))}
</tr>
</thead>
<tbody>
{list(props.rows).map((row, i) => (
<tr key={i}>
{list(row).map((cell, j) => (
<td key={j} className={typeof cell === 'number' ? 'num' : undefined}>
{typeof cell === 'string' ? <Markdown className="[&_p]:m-0">{cell}</Markdown> : text(cell)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
),
List: ({ props }) => {
const Tag = props.ordered ? 'ol' : 'ul';
return (
<div className="md text-[14.5px]">
<Tag>
{list(props.items).map((it, i) => (
<li key={i}>{text(it)}</li>
))}
</Tag>
</div>
);
},
Steps: ({ props }) => (
<ol className="relative space-y-3">
{list(props.steps).map((s, i, all) => {
const p = propsOf(s);
return (
<li key={i} className="relative flex gap-3">
{i < all.length - 1 && <span className="absolute top-7 bottom-[-12px] left-[13px] w-px bg-line" aria-hidden />}
<span className="num relative grid size-7 shrink-0 place-items-center rounded-full bg-accent-soft text-[12.5px] font-semibold text-accent">{i + 1}</span>
<div className="min-w-0 pt-0.5">
<div className="text-[14.5px] font-medium">{text(p.title)}</div>
{p.detail && <Markdown className="text-[13.5px] text-ink-2">{text(p.detail)}</Markdown>}
</div>
</li>
);
})}
</ol>
),
Step: ({ props }) => <div className="text-[14px]">{text(props.title)}</div>,
BarChart: ({ props }) => <BarChart labels={list(props.labels).map(text)} series={seriesOf(props.series)} title={props.title} unit={props.unit} stacked={Boolean(props.stacked)} horizontal={Boolean(props.horizontal)} />,
LineChart: ({ props }) => <LineChart labels={list(props.labels).map(text)} series={seriesOf(props.series)} title={props.title} unit={props.unit} area={Boolean(props.area)} />,
PieChart: ({ props }) => (
<PieChart
slices={list(props.slices)
.map(propsOf)
.map((s) => ({ label: text(s.label), value: num(s.value) }))}
title={props.title}
unit={props.unit}
donut={props.donut !== false}
/>
),
Series: () => null,
Slice: () => null,
Slider: function Slider({ props }) {
const min = num(props.min);
const max = num(props.max, min + 100);
const field = useStateField(String(props.name ?? 'value'), props.value);
const value = num(field.value, num(props.value, min));
return (
<label className="block">
<span className="mb-1.5 flex items-baseline justify-between text-[13px]">
<span className="font-medium">{text(props.label)}</span>
<span className="num rounded-md bg-sunken px-1.5 py-0.5 text-[12.5px] font-semibold">
{text(value)}
{props.unit ? ` ${props.unit}` : ''}
</span>
</span>
<input type="range" min={min} max={max} step={num(props.step, 1) || 1} value={value} onChange={(e) => field.setValue(Number(e.target.value))} className="genui-range w-full" />
</label>
);
},
NumberInput: function NumberInput({ props }) {
const field = useStateField(String(props.name ?? 'value'), props.value);
return (
<label className="block">
<span className="mb-1 block text-[13px] font-medium">{text(props.label)}</span>
<span className="flex items-center gap-2">
<input
type="number"
inputMode="decimal"
step={num(props.step, 0) || 'any'}
value={field.value === null || field.value === undefined ? '' : String(field.value)}
onChange={(e) => field.setValue(e.target.value === '' ? null : Number(e.target.value))}
className="num h-9 w-32 rounded-[9px] border border-line-strong bg-surface px-2.5 text-sm outline-none focus:border-accent"
/>
{props.unit && <span className="text-[13px] text-ink-3">{props.unit}</span>}
</span>
</label>
);
},
Select: function Select({ props }) {
const options = list(props.options).map(propsOf);
const field = useStateField(String(props.name ?? 'value'), props.value);
return (
<label className="block">
<span className="mb-1 block text-[13px] font-medium">{text(props.label)}</span>
<select value={String(field.value ?? '')} onChange={(e) => field.setValue(e.target.value)} className="h-9 w-full max-w-xs rounded-[9px] border border-line-strong bg-surface px-2.5 text-sm outline-none focus:border-accent">
{options.map((o, i) => (
<option key={i} value={text(o.value)}>
{text(o.label ?? o.value)}
</option>
))}
</select>
</label>
);
},
Option: () => null,
Toggle: function Toggle({ props }) {
const field = useStateField(String(props.name ?? 'value'), props.value);
const on = Boolean(field.value);
return (
<button type="button" role="switch" aria-checked={on} onClick={() => field.setValue(!on)} className="flex items-center gap-2.5 text-left text-[13.5px] font-medium">
<span className={cx('relative h-5 w-9 shrink-0 rounded-full transition-colors', on ? 'bg-accent' : 'bg-ink/20')}>
<span className={cx('absolute top-0.5 size-4 rounded-full bg-white shadow-1 transition-transform', on ? 'translate-x-[18px]' : 'translate-x-0.5')} />
</span>
{text(props.label)}
</button>
);
},
Button: function GenButton({ props }) {
const trigger = useTriggerAction();
const streaming = useIsStreaming();
const variant = props.variant ?? 'secondary';
return (
<button
type="button"
disabled={streaming}
onClick={() => void trigger(text(props.label), undefined, props.action)}
className={cx(
'inline-flex h-9 w-fit items-center gap-1.5 rounded-[10px] px-3.5 text-[13.5px] font-medium transition-colors disabled:opacity-50',
variant === 'primary' ? 'bg-ink text-paper hover:bg-ink/85' : variant === 'ghost' ? 'text-accent hover:bg-accent-soft' : 'border border-line-strong bg-surface hover:border-ink-3',
)}
>
{text(props.label)}
</button>
);
},
Link: ({ props }) => {
const url = text(props.url);
if (!/^https?:\/\//i.test(url)) return <span>{text(props.label)}</span>;
return (
<a href={url} target="_blank" rel="noreferrer noopener" className="inline-flex w-fit items-center gap-1 text-[14px] font-medium text-accent hover:underline">
{text(props.label)} <ExternalLink className="size-3.5" />
</a>
);
},
FollowUps: function FollowUps({ props }) {
const trigger = useTriggerAction();
const streaming = useIsStreaming();
return (
<div className="flex flex-wrap gap-1.5">
{list(props.prompts)
.slice(0, 4)
.map((p, i) => (
<button
key={i}
type="button"
disabled={streaming}
onClick={() => void trigger(text(p))}
className="group flex items-center gap-1.5 rounded-full border border-line bg-surface py-1.5 pr-3 pl-2.5 text-left text-[13px] text-ink-2 transition-colors hover:border-accent/50 hover:text-ink disabled:opacity-50"
>
<Sparkles className="size-3.5 shrink-0 text-accent" />
{text(p)}
</button>
))}
</div>
);
},
Question: function Question({ props }) {
const options = list(props.options).map(text);
const correct = new Set(list(props.correct).map((n) => num(n, -1)));
const multi = Boolean(props.multi) || correct.size > 1;
const [picked, setPicked] = useState<number[]>([]);
const [checked, setChecked] = useState(false);
const right = checked && picked.length === correct.size && picked.every((i) => correct.has(i));
const toggle = (i: number) => {
if (checked) return;
setPicked((p) => (multi ? (p.includes(i) ? p.filter((x) => x !== i) : [...p, i]) : [i]));
};
return (
<div className="rounded-[14px] border border-line bg-surface p-4">
<div className="eyebrow mb-1.5 flex items-center gap-1.5 text-accent">
<Sparkles className="size-3.5" /> Quick check
</div>
<Markdown serif className="text-[16.5px] leading-snug">
{text(props.stem)}
</Markdown>
<p className="mt-1.5 mb-2.5 text-[12px] font-medium text-ink-3">{multi ? 'Select all that apply.' : 'Choose one answer.'}</p>
<div className="space-y-1.5">
{options.map((o, i) => {
const isPicked = picked.includes(i);
const isRight = correct.has(i);
const state = !checked ? (isPicked ? 'picked' : 'idle') : isRight ? 'right' : isPicked ? 'wrong' : 'idle';
return (
<button
key={i}
type="button"
onClick={() => toggle(i)}
className={cx(
'flex w-full items-start gap-2.5 rounded-[11px] border px-3 py-2 text-left text-[14px] transition-colors',
state === 'picked' && 'border-accent bg-accent-soft',
state === 'right' && 'border-good bg-good-soft',
state === 'wrong' && 'border-bad bg-bad-soft',
state === 'idle' && 'border-line-strong hover:border-ink-3',
checked && state === 'idle' && 'opacity-70',
)}
>
<span className={cx('num mt-px grid size-5 shrink-0 place-items-center border text-[11px] font-semibold', multi ? 'rounded-[5px]' : 'rounded-full', state === 'idle' ? 'border-line-strong text-ink-3' : 'border-current')}>
{state === 'right' ? <Check className="size-3" /> : state === 'wrong' ? <X className="size-3" /> : String.fromCharCode(65 + i)}
</span>
<span className="min-w-0 flex-1">{o}</span>
</button>
);
})}
</div>
{!checked ? (
<button type="button" disabled={picked.length === 0} onClick={() => setChecked(true)} className="mt-3 inline-flex h-9 items-center rounded-[10px] bg-ink px-4 text-[13.5px] font-medium text-paper hover:bg-ink/85 disabled:opacity-40">
Check
</button>
) : (
<div className="mt-3 animate-in space-y-2">
<div className={cx('flex items-center gap-1.5 text-[14px] font-semibold', right ? 'text-good' : 'text-bad')}>
{right ? <Check className="size-4" /> : <X className="size-4" />}
{right ? 'Correct' : 'Not quite'}
</div>
{props.rationale && <Markdown className="text-[14px] text-ink-2">{text(props.rationale)}</Markdown>}
<button type="button" onClick={() => (setChecked(false), setPicked([]))} className="inline-flex items-center gap-1 text-[12.5px] font-medium text-ink-3 hover:text-ink">
<RotateCcw className="size-3.5" /> Try again
</button>
</div>
)}
</div>
);
},
Flashcards: function Flashcards({ props }) {
const cards = list(props.cards).map(propsOf);
const [index, setIndex] = useState(0);
const [flipped, setFlipped] = useState(false);
if (cards.length === 0) return null;
const i = Math.min(index, cards.length - 1);
const card = cards[i];
const go = (d: number) => {
setFlipped(false);
setIndex((n) => (n + d + cards.length) % cards.length);
};
return (
<div className="rounded-[14px] border border-line bg-surface p-3.5">
<button type="button" onClick={() => setFlipped(!flipped)} className="genui-flip block w-full [perspective:1000px]" aria-label={flipped ? 'Show the front' : 'Show the answer'}>
<span className={cx('relative grid min-h-36 w-full transition-transform duration-500 [transform-style:preserve-3d]', flipped && '[transform:rotateY(180deg)]')}>
<span className="col-start-1 row-start-1 grid place-items-center rounded-[11px] bg-sunken/70 p-5 [backface-visibility:hidden]">
<Markdown serif className="text-center text-[17px]">
{text(card.front)}
</Markdown>
</span>
<span className="col-start-1 row-start-1 grid place-items-center rounded-[11px] bg-accent-soft p-5 [backface-visibility:hidden] [transform:rotateY(180deg)]">
<Markdown className="text-center text-[15px]">{text(card.back)}</Markdown>
</span>
</span>
</button>
<div className="mt-2.5 flex items-center gap-2">
<button type="button" onClick={() => go(-1)} aria-label="Previous card" className="grid size-8 place-items-center rounded-lg text-ink-2 hover:bg-ink/6">
<ChevronLeft className="size-4" />
</button>
<span className="num flex-1 text-center text-[12.5px] text-ink-3">
{i + 1} / {cards.length} · tap to flip
</span>
<button type="button" onClick={() => go(1)} aria-label="Next card" className="grid size-8 place-items-center rounded-lg text-ink-2 hover:bg-ink/6">
<ChevronRight className="size-4" />
</button>
</div>
</div>
);
},
FlashCard: () => null,
};
function seriesOf(value: unknown): ChartSeries[] {
return list(value)
.map(propsOf)
.map((s) => ({ name: text(s.name) || 'Series', values: list(s.values).map((v) => (v === null ? null : num(v, NaN))).map((v) => (v === null || Number.isNaN(v) ? null : v)) }));
}
export const genUiLibrary = createLibrary({
root: GENUI_ROOT,
components: GENUI_COMPONENTS.map((c) => defineComponent({ name: c.name, description: c.description, props: c.props, component: (R[c.name] ?? (() => null)) as never })),
componentGroups: GENUI_GROUPS,
});
export { useRenderNode };

View file

@ -16,10 +16,10 @@ interface State {
open: boolean;
seed: AssistantSeed | null;
/** What the user is currently looking at; supplied by pages. */
context: { classId: string | null; documentIds: string[]; label: string };
context: { classId: string | null; documentIds: string[]; label: string; folderId?: string | null };
}
let state: State = { open: false, seed: null, context: { classId: null, documentIds: [], label: '' } };
let state: State = { open: false, seed: null, context: { classId: null, documentIds: [], label: '', folderId: null } };
const listeners = new Set<() => void>();
const set = (patch: Partial<State>) => {
state = { ...state, ...patch };
@ -52,7 +52,7 @@ export const assistant = {
},
setContext(context: State['context']) {
const cur = state.context;
if (cur.classId === context.classId && cur.label === context.label && cur.documentIds.join() === context.documentIds.join()) return;
if (cur.classId === context.classId && cur.label === context.label && (cur.folderId ?? null) === (context.folderId ?? null) && cur.documentIds.join() === context.documentIds.join()) return;
set({ context });
},
};
@ -68,11 +68,11 @@ export function useAssistantState(): State {
);
}
/** Pages call this so the assistant knows which class or document "this" refers to. */
export function useAssistantContext(classId: string | null | undefined, label = '', documentIds: string[] = []): void {
/** Pages call this so the assistant knows which class, exam or document "this" refers to. */
export function useAssistantContext(classId: string | null | undefined, label = '', documentIds: string[] = [], folderId: string | null = null): void {
const key = documentIds.join(',');
useEffect(() => {
assistant.setContext({ classId: classId ?? null, documentIds: key ? key.split(',') : [], label });
return () => assistant.setContext({ classId: null, documentIds: [], label: '' });
}, [classId, label, key]);
assistant.setContext({ classId: classId ?? null, documentIds: key ? key.split(',') : [], label, folderId });
return () => assistant.setContext({ classId: null, documentIds: [], label: '', folderId: null });
}, [classId, label, key, folderId]);
}

View file

@ -1,5 +1,5 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback } from 'react';
import { useCallback, useEffect } from 'react';
import { api } from './api';
import type { AiModel, AiStatus, ClassDetail, ClassListItem, DeckDetail, Overview, QuizDetail } from './types';
@ -52,3 +52,28 @@ export function useRefresh() {
[qc],
);
}
/**
* Listens to /api/events and refreshes what changed elsewhere: a draft the assistant created,
* a quiz saved in another tab, a change the assistant confirmed. Reconnects by itself.
*/
export function useLiveChanges() {
const qc = useQueryClient();
useEffect(() => {
if (typeof EventSource === 'undefined') return;
const source = new EventSource('/api/events');
source.onmessage = (e) => {
let msg: { type?: string; topics?: string[] } = {};
try {
msg = JSON.parse(e.data);
} catch {
return;
}
if (msg.type !== 'change' || !msg.topics) return;
if (msg.topics.includes('drafts')) void qc.invalidateQueries({ queryKey: qk.drafts });
// Document processing is already polled by the pages that show it; its progress writes are skipped here.
if (msg.topics.includes('library')) void qc.invalidateQueries({ predicate: (q) => ['classes', 'class', 'overview', 'quiz', 'deck', 'note'].includes(String(q.queryKey[0])) });
};
return () => source.close();
}, [qc]);
}

View file

@ -5,6 +5,8 @@ export type { Card, ClassColor, ContentDraft, Option, Question, QuestionType };
export interface ClassInfo {
id: string;
name: string;
/** What the class calls its groups (folders): Exam by default. */
groupLabel: string;
code: string;
description: string;
color: ClassColor;
@ -456,14 +458,43 @@ export type UiItem =
| { type: 'draft'; draftId: string; kind: 'quiz' | 'deck' | 'note'; title: string; count: number; status: string }
| { type: 'action'; actionId: string; summary: string; changes: string[]; status: 'pending' | 'confirmed' | 'cancelled' | 'failed'; result?: string }
| { type: 'sources'; items: { ref: string; chunkId: number; documentId: string; label: string }[] }
| { type: 'link'; kind: 'quiz' | 'deck' | 'note' | 'document' | 'class' | 'attempt'; id: string; title: string };
| { type: 'link'; kind: 'quiz' | 'deck' | 'note' | 'document' | 'class' | 'attempt'; id: string; title: string }
| { type: 'questions'; id: string; intro?: string; questions: AskQuestion[] };
export interface AskQuestion {
id: string;
question: string;
input: 'choice' | 'text' | 'number';
options?: { label: string; description?: string }[];
multi?: boolean;
defaults?: string[];
placeholder?: string;
}
export type ToolKind = 'web_search' | 'web_fetch' | 'web_research' | 'mcp' | 'tool';
export interface WebSource {
title: string;
url: string;
}
export interface ToolActivity {
id: string;
name: string;
label: string;
status: 'running' | 'done' | 'error';
summary?: string;
kind?: ToolKind;
server?: string;
subject?: string;
sources?: WebSource[];
input?: string;
output?: string;
}
/** A web search or MCP server the chat can use, for the per-chat switches. */
export interface ChatToolSource {
id: string;
name: string;
kind: 'web' | 'mcp';
}
export type TagKind = 'quiz' | 'deck' | 'note' | 'document' | 'folder';
export interface TaggedItem {

View file

@ -1,6 +1,8 @@
import {
Archive,
ArrowDownAZ,
ArrowLeft,
ArrowRight,
BookOpen,
ChevronDown,
Clock,
@ -42,7 +44,7 @@ import { useClass, useRefresh } from '@/lib/queries';
import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@/lib/types';
import { cx, downloadFile, formatBytes, gradeTone, plural, timeAgo, useDocumentTitle, useLocalStorage } from '@/lib/util';
import { SortableList, type SortableRenderProps } from '@/ui/Sortable';
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
import { Badge, Button, Dialog, EmptyState, ErrorState, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, ProgressBar, Segmented, Skeleton, Textarea, useConfirm } from '@/ui';
import { letterGrade } from '@shared/content';
type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note';
@ -116,7 +118,18 @@ export default function ClassPage() {
const q = useClass(classId, polling ? 1500 : false);
const data = q.data;
useDocumentTitle(data?.class.name);
useAssistantContext(classId, data?.class.name);
/**
* The exam (folder) in view: a class is divided into exams, each with its own material.
* 'all' shows everything, 'none' what is in no exam. Remembered per class; new visitors start
* on the latest exam.
*/
const [examChoice, setExamChoice] = useLocalStorage<string>(`sd.exam.${classId}`, '');
const exams = data?.folders ?? [];
const examView = examChoice === 'all' || examChoice === 'none' || exams.some((f) => f.id === examChoice) ? examChoice : exams.length ? exams[exams.length - 1].id : 'all';
const currentExam = exams.find((f) => f.id === examView) ?? null;
const groupLabel = data?.class.groupLabel ?? 'Exam';
useAssistantContext(classId, currentExam ? `${data?.class.name} · ${currentExam.name}` : data?.class.name, [], currentExam?.id ?? null);
const [filter, setFilter] = useState<Filter>('all');
const [query, setQuery] = useState('');
@ -149,6 +162,7 @@ export default function ClassPage() {
setUploads((u) => [...u, { id, name: file.name, progress: 0 }]);
const form = new FormData();
form.append('classId', classId);
if (currentExam) form.append('folderId', currentExam.id);
form.append('file', file);
try {
await uploadWithProgress('/api/documents', form, (p) => setUploads((u) => u.map((x) => (x.id === id ? { ...x, progress: p } : x))));
@ -160,22 +174,35 @@ export default function ClassPage() {
}
};
/** Items of the exam in view. */
const scoped = useMemo(() => {
const items = data?.items ?? [];
const known = new Set((data?.folders ?? []).map((f) => f.id));
if (examView === 'all') return items;
if (examView === 'none') return items.filter((i) => !i.folderId || !known.has(i.folderId));
return items.filter((i) => i.folderId === examView);
}, [data, examView]);
const looseCount = useMemo(() => {
const known = new Set((data?.folders ?? []).map((f) => f.id));
return (data?.items ?? []).filter((i) => !i.folderId || !known.has(i.folderId)).length;
}, [data]);
const counts = useMemo(() => {
const c = { all: 0, quiz: 0, deck: 0, document: 0, note: 0 };
for (const i of data?.items ?? []) {
for (const i of scoped) {
c.all += 1;
c[i.kind] += 1;
}
return c;
}, [data]);
}, [scoped]);
const visible = useMemo(() => {
const needle = query.trim().toLowerCase();
const list = (data?.items ?? []).filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle)));
const list = scoped.filter((i) => (filter === 'all' || i.kind === filter) && (!needle || i.title.toLowerCase().includes(needle) || i.description.toLowerCase().includes(needle)));
return list.sort((a, b) =>
sort === 'title' ? a.title.localeCompare(b.title, undefined, { numeric: true }) : sort === 'recent' ? b.updatedAt - a.updatedAt : a.sortOrder - b.sortOrder || a.createdAt - b.createdAt,
);
}, [data, filter, query, sort]);
}, [scoped, filter, query, sort]);
if (q.isError) return <ErrorState title="Class not found" message={errorMessage(q.error)} onRetry={() => q.refetch()} />;
if (!data) {
@ -213,8 +240,10 @@ export default function ClassPage() {
}
};
const removeFolder = async (f: Folder) => {
if (!(await confirm({ title: 'Delete this folder?', message: `"${f.name}" will be removed. Everything inside it stays in the class.`, confirmLabel: 'Delete folder', danger: true }))) return;
const noun = groupLabel.toLowerCase();
if (!(await confirm({ title: `Delete this ${noun}?`, message: `"${f.name}" will be removed. Everything in it stays in the class, outside any ${noun}.`, confirmLabel: `Delete ${noun}`, danger: true }))) return;
await api.del(`/api/folders/${f.id}`).catch((e) => toast.error(errorMessage(e)));
if (examChoice === f.id) setExamChoice('');
await refresh();
};
const deleteClass = async () => {
@ -456,17 +485,18 @@ export default function ClassPage() {
</Button>
}
>
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz' })}>
{currentExam && <MenuLabel>Adding to {currentExam.name}</MenuLabel>}
<MenuItem icon={<BookOpen />} onSelect={() => setNewKind({ kind: 'quiz', folderId: currentExam?.id ?? null })}>
New quiz
</MenuItem>
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck' })}>
<MenuItem icon={<Layers />} onSelect={() => setNewKind({ kind: 'deck', folderId: currentExam?.id ?? null })}>
New flashcard deck
</MenuItem>
<MenuItem icon={<NotebookPen />} onSelect={() => setNewKind({ kind: 'note' })}>
<MenuItem icon={<NotebookPen />} onSelect={() => setNewKind({ kind: 'note', folderId: currentExam?.id ?? null })}>
New note
</MenuItem>
<MenuItem icon={<FolderPlus />} onSelect={() => setNewKind({ kind: 'folder' })}>
New folder
New {groupLabel.toLowerCase()}
</MenuItem>
<MenuSeparator />
<MenuItem icon={<Upload />} onSelect={() => fileRef.current?.click()}>
@ -590,6 +620,22 @@ export default function ClassPage() {
</div>
) : (
<>
<ExamTabs
exams={exams}
items={data.items}
looseCount={looseCount}
view={examView}
label={groupLabel}
onView={setExamChoice}
onNew={() => setNewKind({ kind: 'folder' })}
onRename={(f) => setRename({ kind: 'folder', id: f.id, title: f.name })}
onShare={(f) => setShare({ kind: 'folder', id: f.id, title: f.name })}
onDelete={removeFolder}
onReorder={async (ids) => {
await api.post(`/api/classes/${classId}/folders/reorder`, { ids }).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
/>
<div className="mb-4 flex flex-wrap items-center gap-2">
<div className="-mx-1 flex max-w-full gap-1 overflow-x-auto px-1 pb-1">
{(
@ -653,10 +699,31 @@ export default function ClassPage() {
{visible.length === 0 ? (
<div className="card">
<EmptyState title={searching ? 'Nothing matches' : 'Nothing here yet'} icon={<Search />}>
{query ? `No ${filter === 'all' ? 'items' : filter === 'deck' ? 'decks' : `${filter}s`} match "${query}".` : 'Try a different filter, or add something new.'}
</EmptyState>
{currentExam && !searching ? (
<EmptyState
title={`Nothing in ${currentExam.name} yet`}
icon={<FolderIcon />}
action={
<>
<Button variant="primary" icon={<Upload />} onClick={() => fileRef.current?.click()}>
Upload documents
</Button>
<Button icon={<Sparkles />} onClick={() => setGenerate({})}>
Generate
</Button>
</>
}
>
Add this {groupLabel.toLowerCase()}'s slides and notes, then generate quizzes and flashcards from them. Use Move on anything already in the class to bring it here.
</EmptyState>
) : (
<EmptyState title={searching ? 'Nothing matches' : 'Nothing here yet'} icon={<Search />}>
{query ? `No ${filter === 'all' ? 'items' : filter === 'deck' ? 'decks' : `${filter}s`} match "${query}".` : 'Try a different filter, or add something new.'}
</EmptyState>
)}
</div>
) : examView !== 'all' ? (
section(visible)
) : (
<div className="space-y-4">
{loose.length > 0 && section(loose)}
@ -741,19 +808,19 @@ export default function ClassPage() {
</div>
)}
<NewItemDialog kind={newKind?.kind ?? null} classId={classId} folderId={newKind?.folderId} onClose={() => setNewKind(null)} />
<NewItemDialog kind={newKind?.kind ?? null} classId={classId} folderId={newKind?.folderId} groupLabel={groupLabel} onClose={() => setNewKind(null)} />
<RenameDialog target={rename} onClose={() => setRename(null)} />
<MoveDialog target={move} onClose={() => setMove(null)} />
<ShareDialog target={share} onClose={() => setShare(null)} />
<ImportDialog open={importOpen} onClose={() => setImportOpen(false)} classId={classId} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={classId} preset={generate ?? undefined} />
<ImportDialog open={importOpen} onClose={() => setImportOpen(false)} classId={classId} folderId={currentExam?.id ?? null} />
<GenerateDialog open={generate !== null} onClose={() => setGenerate(null)} classId={classId} folderId={currentExam?.id ?? null} preset={generate ?? undefined} />
<ClassDialog open={editClass} onOpenChange={setEditClass} existing={cls} />
<PasteTextDialog open={pasteOpen} onClose={() => setPasteOpen(false)} classId={classId} />
<PasteTextDialog open={pasteOpen} onClose={() => setPasteOpen(false)} classId={classId} folderId={currentExam?.id ?? null} />
</div>
);
}
function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: () => void; classId: string }) {
function PasteTextDialog({ open, onClose, classId, folderId }: { open: boolean; onClose: () => void; classId: string; folderId?: string | null }) {
const refresh = useRefresh();
const [title, setTitle] = useState('');
const [text, setText] = useState('');
@ -767,7 +834,7 @@ function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: (
const save = async () => {
setBusy(true);
try {
await api.post('/api/documents/text', { classId, title, text });
await api.post('/api/documents/text', { classId, folderId: folderId ?? null, title, text });
await refresh();
toast.success('Added as a document');
onClose();
@ -806,3 +873,116 @@ function PasteTextDialog({ open, onClose, classId }: { open: boolean; onClose: (
</Dialog>
);
}
/* ------------------------------ exams ------------------------------ */
/**
* The second level of a class: one tab per exam (or unit, module… as the class calls them),
* plus "All" and, when anything is outside every exam, "Not in an exam".
*/
function ExamTabs({
exams,
items,
looseCount,
view,
label,
onView,
onNew,
onRename,
onShare,
onDelete,
onReorder,
}: {
exams: Folder[];
items: Item[];
looseCount: number;
view: string;
label: string;
onView: (v: string) => void;
onNew: () => void;
onRename: (f: Folder) => void;
onShare: (f: Folder) => void;
onDelete: (f: Folder) => void;
onReorder: (ids: string[]) => void;
}) {
const noun = label.toLowerCase();
const count = (id: string) => items.filter((i) => i.folderId === id).length;
const move = (index: number, by: number) => {
const ids = exams.map((f) => f.id);
const [id] = ids.splice(index, 1);
ids.splice(Math.max(0, Math.min(ids.length, index + by)), 0, id);
onReorder(ids);
};
if (exams.length === 0) {
return (
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-[14px] border border-dashed border-line-strong px-4 py-3 text-[13.5px] text-ink-2">
<FolderIcon className="size-4 shrink-0 text-tab" />
<span className="min-w-0 flex-1">Divide this class into {noun}s so each keeps its own documents, quizzes and flashcards, and generating uses only that {noun}'s material.</span>
<Button size="sm" icon={<Plus />} onClick={onNew}>
New {noun}
</Button>
</div>
);
}
const tab = (key: string, text: ReactNode, n: number, extra?: ReactNode) => (
<div key={key} className={cx('flex shrink-0 items-center rounded-[11px] border transition-colors', view === key ? 'border-tab bg-surface shadow-1' : 'border-transparent hover:bg-ink/5')}>
<button type="button" role="tab" aria-selected={view === key} onClick={() => onView(key)} className={cx('flex h-10 items-center gap-2 pr-2 pl-3.5 text-sm', view === key ? 'font-semibold text-ink' : 'font-medium text-ink-2')}>
{text}
<span className="num text-xs font-normal text-ink-3">{n}</span>
</button>
{extra}
</div>
);
return (
<div className="mb-4 border-b border-line pb-3">
<div role="tablist" aria-label={`${label}s`} className="-mx-1 flex items-center gap-1 overflow-x-auto px-1 pb-1">
{exams.map((f, index) =>
tab(
f.id,
<>
<FolderIcon className="size-4 text-tab" />
<span className="max-w-48 truncate">{f.name}</span>
{f.shared && <Share2 className="size-3.5 text-accent" aria-label="Shared" />}
</>,
count(f.id),
view === f.id ? (
<Menu
trigger={
<IconButton label={`${label} options for ${f.name}`} size="sm" tooltip={false} className="mr-1">
<MoreHorizontal />
</IconButton>
}
>
<MenuItem icon={<Pencil />} onSelect={() => onRename(f)}>
Rename
</MenuItem>
<MenuItem icon={<Share2 />} onSelect={() => onShare(f)}>
Share this {noun}
</MenuItem>
{index > 0 && (
<MenuItem icon={<ArrowLeft />} onSelect={() => move(index, -1)}>
Move earlier
</MenuItem>
)}
{index < exams.length - 1 && (
<MenuItem icon={<ArrowRight />} onSelect={() => move(index, 1)}>
Move later
</MenuItem>
)}
<MenuSeparator />
<MenuItem icon={<Trash2 />} danger onSelect={() => onDelete(f)}>
Delete {noun}
</MenuItem>
</Menu>
) : null,
),
)}
{looseCount > 0 && tab('none', <span className="text-ink-2">Not in a{/^[aeiou]/i.test(noun) ? 'n' : ''} {noun}</span>, looseCount)}
{tab('all', <span>All</span>, items.length)}
<button type="button" onClick={onNew} className="ml-1 flex h-10 shrink-0 items-center gap-1.5 rounded-[11px] px-3 text-sm font-medium text-ink-3 hover:bg-ink/5 hover:text-ink">
<Plus className="size-4" /> New {noun}
</button>
</div>
</div>
);
}

View file

@ -136,7 +136,7 @@ export default function SessionPage() {
navigate(back);
};
const renderExtra = ai.data?.ready
? (q: SnapshotQuestion, selected: string[]) => <Explain body={{ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected, rationale: q.rationale }} />
? (q: SnapshotQuestion, selected: string[]) => <Explain body={{ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected, rationale: q.rationale, quizId: q.quizId ?? undefined }} />
: undefined;
if (attempt.status === 'completed') {

View file

@ -1,10 +1,11 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Brain, Check, Copy, Database, Download, ExternalLink, FileUp, GraduationCap, HardDriveDownload, Layers, Link2, Lock, NotebookPen, RefreshCw, Share2, SlidersHorizontal, Sparkles, Stamp, Trash2, Upload } from 'lucide-react';
import { BookOpen, Brain, Globe, Check, Copy, Database, Download, ExternalLink, FileUp, GraduationCap, HardDriveDownload, Layers, Link2, Lock, NotebookPen, RefreshCw, Share2, SlidersHorizontal, Sparkles, Stamp, Trash2, Upload } from 'lucide-react';
import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from 'react';
import { NavLink, useNavigate, useParams } from 'react-router';
import { NavLink, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { shareUrl } from '@/features/dialogs';
import { TemplateSettings } from '@/features/TemplateSettings';
import { WebSearchSettings } from '@/features/WebSearchSettings';
import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { AppSettings, ShareListItem, Template } from '@/lib/types';
@ -16,6 +17,7 @@ const AiSettings = lazy(() => import('@/features/AiSettings'));
const TABS = [
{ id: 'study', label: 'Study', icon: <SlidersHorizontal /> },
{ id: 'ai', label: 'AI', icon: <Sparkles /> },
{ id: 'web', label: 'Web search', icon: <Globe /> },
{ id: 'sharing', label: 'Sharing', icon: <Share2 /> },
{ id: 'templates', label: 'Templates', icon: <Stamp /> },
{ id: 'data', label: 'Data and backup', icon: <Database /> },
@ -539,6 +541,16 @@ export default function SettingsPage() {
useEffect(() => {
if (tab && !TABS.some((t) => t.id === tab)) navigate('/settings', { replace: true });
}, [tab, navigate]);
// Back from an MCP or web search sign-in.
const [params, setParams] = useSearchParams();
useEffect(() => {
const outcome = params.get('mcp_oauth');
if (!outcome) return;
const message = params.get('message') || (outcome === 'ok' ? 'Signed in.' : 'The sign-in failed.');
if (outcome === 'ok') toast.success(message);
else toast.error(message);
setParams({}, { replace: true });
}, [params, setParams]);
return (
<div className="animate-in">
@ -564,6 +576,7 @@ export default function SettingsPage() {
<AiSettings />
</Suspense>
)}
{active === 'web' && <WebSearchSettings />}
{active === 'sharing' && <SharingSettings />}
{active === 'templates' && <TemplateSettings />}
{active === 'data' && <DataSettings />}

View file

@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, BookOpen, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun, Timer } from 'lucide-react';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { AlignLeft, ArrowLeft, BookOpen, Eye, ChevronRight, Download, FileText, Layers, Link2Off, Moon, NotebookPen, Play, RotateCcw, Sun, Timer } from 'lucide-react';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { isFullyCorrect, scoreQuestion, seededShuffle } from '@shared/content';
@ -9,18 +9,18 @@ import { SharedAssistant } from '@/features/SharedAssistant';
import { QuizResults, QuizRunner } from '@/features/quiz';
import { api, ApiError } from '@/lib/api';
import type { AnswerState, PublicCollection, PublicDeck, PublicDocument, PublicNote, PublicPayload, PublicQuiz, SnapshotQuestion } from '@/lib/types';
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useTheme } from '@/lib/util';
import { cx, formatBytes, plural, useDocumentTitle, useLocalStorage, useMediaQuery, useTheme } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Button, EmptyState, IconButton, Input, PageLoading, Switch } from '@/ui';
import { Button, EmptyState, IconButton, Input, PageLoading, Segmented, Switch } from '@/ui';
/* ------------------------------ frame ------------------------------ */
function Frame({ children, back }: { children: ReactNode; back?: { to: string; label: string } }) {
function Frame({ children, back, wide }: { children: ReactNode; back?: { to: string; label: string }; wide?: boolean }) {
const [, setTheme] = useTheme();
const dark = document.documentElement.dataset.theme === 'dark';
return (
<div className="min-h-dvh">
<header className="mx-auto flex h-14 max-w-3xl items-center gap-2 px-4 sm:px-5">
<header className={cx('mx-auto flex h-14 items-center gap-2 px-4 sm:px-5', wide ? 'max-w-5xl' : 'max-w-3xl')}>
{back ? (
<Link to={back.to} className="-ml-2 flex h-9 items-center gap-1.5 rounded-lg px-2 text-sm font-medium text-ink-2 hover:bg-ink/6 hover:text-ink">
<ArrowLeft className="size-4" /> {back.label}
@ -36,7 +36,7 @@ function Frame({ children, back }: { children: ReactNode; back?: { to: string; l
{dark ? <Sun /> : <Moon />}
</IconButton>
</header>
<main className="mx-auto max-w-3xl animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8">{children}</main>
<main className={cx('mx-auto animate-in px-4 pt-4 pb-20 sm:px-5 sm:pt-8', wide ? 'max-w-5xl' : 'max-w-3xl')}>{children}</main>
<footer className="pb-8 text-center text-xs text-ink-3">Shared with Study Desk. Your progress is saved in this browser only.</footer>
</div>
);
@ -118,7 +118,7 @@ function buildQuizState(quiz: PublicQuiz, mode: QuizState['mode'], shuffleQ: boo
};
}
function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
function SharedQuiz({ quiz, storageKey, back, explainUrl, onImmersive }: { quiz: PublicQuiz; storageKey: string; back?: { to: string; label: string }; explainUrl?: string; onImmersive?: (on: boolean) => void }) {
const renderExtra = explainUrl ? (q: SnapshotQuestion, selected: string[]) => <Explain url={explainUrl} body={{ kind: 'question', quizId: quiz.id, questionId: q.id, selected }} /> : undefined;
const [state, setState] = useLocalStorage<QuizState | null>(storageKey, null);
const [prefs, setPrefs] = useLocalStorage('sd.pub.prefs2', { mode: 'practice' as 'practice' | 'exam', shuffleQ: true, shuffleO: true, timed: false, minutes: 0 });
@ -142,6 +142,12 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz;
}, [quiz, state]);
const changed = Boolean(state?.version && state.version !== quizVersion(quiz));
// While a quiz is being taken the assistant button steps aside.
const taking = Boolean(state && questions.length > 0 && running && !state.done);
useEffect(() => {
onImmersive?.(taking);
return () => onImmersive?.(false);
}, [taking, onImmersive]);
const expired = Boolean(state && !state.done && state.deadlineAt && Date.now() > state.deadlineAt);
// A timed exam whose deadline passed while the page was closed is submitted as it stands.
@ -288,9 +294,13 @@ function SharedQuiz({ quiz, storageKey, back, explainUrl }: { quiz: PublicQuiz;
/* ------------------------------ deck ------------------------------ */
function SharedDeck({ deck, storageKey, back, explainUrl }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string }; explainUrl?: string }) {
function SharedDeck({ deck, storageKey, back, explainUrl, onImmersive }: { deck: PublicDeck; storageKey: string; back?: { to: string; label: string }; explainUrl?: string; onImmersive?: (on: boolean) => void }) {
const [saved, setSaved] = useLocalStorage<CramState | null>(storageKey, null);
const [running, setRunning] = useState(false);
useEffect(() => {
onImmersive?.(running);
return () => onImmersive?.(false);
}, [running, onImmersive]);
const state = useMemo(() => reconcileCramState(saved, deck.cards), [saved, deck.cards]);
if (running && state) {
@ -378,24 +388,92 @@ function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; lab
);
}
function SharedDocument({ doc, token, nested, back }: { doc: PublicDocument; token: string; nested?: boolean; back?: { to: string; label: string } }) {
const url = nested ? `/api/public/${token}/items/document/${doc.id}/file` : `/api/public/${token}/file`;
const inline = doc.docKind === 'pdf' || doc.docKind === 'image';
interface TextChunk {
id: number;
seq: number;
text: string;
heading: string;
pageStart: number | null;
pageEnd: number | null;
}
/** The document's extracted text, page by page: readable on any device, including phones. */
function SharedDocumentText({ base }: { base: string }) {
const q = useInfiniteQuery({
queryKey: ['public', 'text', base],
queryFn: ({ pageParam, signal }) => api.pub<{ chunks: TextChunk[]; nextOffset: number | null }>(`${base}/text?offset=${pageParam}&limit=30`, signal),
initialPageParam: 0,
getNextPageParam: (last) => last.nextOffset ?? undefined,
});
const chunks = q.data?.pages.flatMap((p) => p.chunks) ?? [];
if (q.isLoading) return <div className="card mt-5 h-64 animate-pulse" />;
if (chunks.length === 0) return <div className="card mt-5 p-6 text-sm text-ink-2">No readable text was found in this file. Download it to open it.</div>;
let lastPage: number | null = null;
return (
<Frame back={back}>
<article className="card mt-5 px-5 py-6 sm:px-9 sm:py-8">
{chunks.map((c) => {
const newPage = c.pageStart !== null && c.pageStart !== lastPage;
if (c.pageStart !== null) lastPage = c.pageEnd ?? c.pageStart;
return (
<section key={c.id} className="mb-5">
{newPage && <div className="eyebrow mb-2 border-t border-line pt-3 first:border-0 first:pt-0">Page {c.pageStart}</div>}
{c.heading && <h3 className="mb-1.5 text-[15px] font-semibold">{c.heading}</h3>}
<div className="reading text-[16px] leading-relaxed whitespace-pre-wrap">{c.text}</div>
</section>
);
})}
{q.hasNextPage && (
<Button variant="secondary" block loading={q.isFetchingNextPage} onClick={() => q.fetchNextPage()}>
Show more
</Button>
)}
</article>
);
}
function SharedDocument({ doc, token, nested, back }: { doc: PublicDocument; token: string; nested?: boolean; back?: { to: string; label: string } }) {
const base = nested ? `/api/public/${token}/items/document/${doc.id}` : `/api/public/${token}`;
const fileUrl = `${base}/file`;
const office = doc.docKind === 'docx' || doc.docKind === 'pptx';
const hasOriginal = doc.docKind === 'pdf' || doc.docKind === 'image' || office;
// Phones rarely show PDFs inside a page, so they start on the text.
const phone = useMediaQuery('(max-width: 639px)');
const [view, setView] = useState<'original' | 'text'>(hasOriginal && !(phone && doc.docKind === 'pdf') ? 'original' : 'text');
return (
<Frame back={back} wide>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<FileText className="size-3.5" /> Shared document
</div>
<h1 className="display text-[30px] sm:text-[36px]">{doc.title}</h1>
<p className="mt-2 text-sm text-ink-3">
{doc.filename} · {formatBytes(doc.size)}
{doc.pageCount ? ` · ${plural(doc.pageCount, 'page')}` : ''}
</p>
<Button href={url} download={inline ? undefined : doc.filename} target={inline ? '_blank' : undefined} variant="primary" size="lg" icon={<Download />} className="mt-5">
{inline ? 'Open file' : 'Download'}
</Button>
{doc.docKind === 'image' && <img src={url} alt={doc.title} className="card mt-6 max-w-full p-2" />}
{doc.docKind === 'pdf' && <iframe src={url} title={doc.title} className="card mt-6 hidden h-[78vh] w-full sm:block" />}
<div className="mt-3 flex flex-wrap items-center gap-3">
{hasOriginal && (
<Segmented
size="sm"
label="View"
value={view}
onChange={setView}
options={[
{ value: 'original', label: 'Original', icon: <Eye /> },
{ value: 'text', label: 'Text', icon: <AlignLeft /> },
]}
/>
)}
<span className="text-sm text-ink-3">
{doc.filename} · {formatBytes(doc.size)}
{doc.pageCount ? ` · ${plural(doc.pageCount, 'page')}` : ''}
</span>
<Button href={fileUrl} download={doc.filename} size="sm" variant="ghost" icon={<Download />} className="ml-auto">
Download
</Button>
</div>
{view === 'text' || !hasOriginal ? (
<SharedDocumentText base={base} />
) : doc.docKind === 'image' ? (
<img src={fileUrl} alt={doc.title} className="card mt-5 max-w-full p-2" />
) : (
// Office previews are self-contained HTML that the server sandboxes with its Content-Security-Policy.
<iframe src={office ? `${base}/preview` : fileUrl} title={doc.title} className="card mt-5 h-[80vh] w-full bg-surface" />
)}
</Frame>
);
}
@ -444,6 +522,7 @@ export default function SharedPage() {
const { token = '', kind, itemId } = useParams();
const navigate = useNavigate();
const nested = Boolean(kind && itemId);
const [immersive, setImmersive] = useState(false);
const q = useQuery({
queryKey: ['public', token, kind ?? '', itemId ?? ''],
queryFn: ({ signal }) => api.pub<PublicPayload>(nested ? `/api/public/${token}/items/${kind}/${itemId}` : `/api/public/${token}`, signal),
@ -473,13 +552,13 @@ export default function SharedPage() {
const back = nested ? { to: `/s/${token}`, label: 'All materials' } : undefined;
const key = `sd.pub.${token.slice(0, 12)}.${data.kind}.${'id' in data ? data.id : ''}`;
const explainUrl = data.ai?.explain ? `/api/public/${token}/explain` : undefined;
const assistant = data.ai?.assistant ? <SharedAssistant token={token} title={data.title} item={nested && data.kind !== 'collection' ? { kind: data.kind, id: data.id } : undefined} /> : null;
const assistant = data.ai?.assistant ? <SharedAssistant token={token} title={data.title} hidden={immersive} item={nested && data.kind !== 'collection' ? { kind: data.kind, id: data.id } : undefined} /> : null;
const page = (() => {
switch (data.kind) {
case 'quiz':
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} explainUrl={explainUrl} />;
return <SharedQuiz key={key} quiz={data} storageKey={key} back={back} explainUrl={explainUrl} onImmersive={setImmersive} />;
case 'deck':
return <SharedDeck key={key} deck={data} storageKey={key} back={back} explainUrl={explainUrl} />;
return <SharedDeck key={key} deck={data} storageKey={key} back={back} explainUrl={explainUrl} onImmersive={setImmersive} />;
case 'note':
return <SharedNote note={data} back={back} />;
case 'document':

View file

@ -46,6 +46,16 @@
--c-rose: #c2386e;
--c-plum: #7a45c2;
--c-slate: #5d6673;
/* Chart series (categorical, fixed order; validated for colour-vision deficiency). */
--score-yellow: #d9a300;
--series-1: #2a78d6;
--series-2: #eb6834;
--series-3: #1baf7a;
--series-4: #eda100;
--series-5: #e87ba4;
--series-6: #008300;
--series-7: #6250d6;
--series-8: #e34948;
color-scheme: light;
}
@ -82,6 +92,15 @@
--c-rose: #f07ea9;
--c-plum: #b893f2;
--c-slate: #a0a9b6;
--score-yellow: #e9c43f;
--series-1: #3987e5;
--series-2: #d95926;
--series-3: #199e70;
--series-4: #c98500;
--series-5: #d55181;
--series-6: #0ca30c;
--series-7: #9085e9;
--series-8: #e66767;
color-scheme: dark;
}
@ -629,3 +648,135 @@
background: #fff;
}
}
/* ------------------------------ generated reply blocks and tool steps ------------------------------ */
.genui-range {
appearance: none;
height: 20px;
background: transparent;
cursor: pointer;
}
.genui-range::-webkit-slider-runnable-track {
height: 4px;
border-radius: 999px;
background: color-mix(in srgb, var(--ink) 14%, transparent);
}
.genui-range::-moz-range-track {
height: 4px;
border-radius: 999px;
background: color-mix(in srgb, var(--ink) 14%, transparent);
}
.genui-range::-webkit-slider-thumb {
appearance: none;
margin-top: -7px;
width: 18px;
height: 18px;
border-radius: 999px;
background: var(--accent);
border: 3px solid var(--surface);
box-shadow: 0 0 0 1px var(--accent), var(--shadow-1);
}
.genui-range::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 999px;
background: var(--accent);
border: 3px solid var(--surface);
box-shadow: 0 0 0 1px var(--accent);
}
.genui-range:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 4px;
}
.genui-draw {
stroke-dasharray: 2000;
stroke-dashoffset: 2000;
animation: sd-draw 1.4s cubic-bezier(0.3, 0.7, 0.2, 1) forwards;
}
@keyframes sd-draw {
to {
stroke-dashoffset: 0;
}
}
/* A running tool step: the label shimmers while the work happens. */
.tool-shimmer {
background: linear-gradient(90deg, var(--ink-3) 0%, var(--ink) 45%, var(--ink-3) 90%);
background-size: 220% 100%;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
animation: sd-tool-shimmer 1.6s linear infinite;
}
@keyframes sd-tool-shimmer {
from {
background-position: 120% 0;
}
to {
background-position: -120% 0;
}
}
@keyframes sd-globe {
to {
transform: rotate(360deg);
}
}
.tool-spin-slow {
animation: sd-globe 2.4s linear infinite;
}
@keyframes sd-tool-done {
0% {
transform: scale(0.4);
opacity: 0;
}
70% {
transform: scale(1.15);
}
100% {
transform: scale(1);
opacity: 1;
}
}
.tool-pop {
animation: sd-tool-done 320ms cubic-bezier(0.2, 0.9, 0.3, 1.2);
}
/* 100% on a quiz: the score ring cycles through a rainbow and throws a few sparks. */
.score-spark {
opacity: 0;
animation: sd-spark 900ms cubic-bezier(0.2, 0.8, 0.3, 1) 1 forwards;
}
@keyframes sd-spark {
0% {
opacity: 1;
transform: translate(-50%, -50%) rotate(var(--a)) translateY(0) scale(1);
}
100% {
opacity: 0;
transform: translate(-50%, -50%) rotate(var(--a)) translateY(-92px) scale(0.4);
}
}
@keyframes sd-rainbow {
to {
filter: hue-rotate(360deg);
}
}
.ring-rainbow {
animation: sd-rainbow 3s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.genui-draw,
.tool-shimmer,
.tool-spin-slow,
.tool-pop,
.score-spark,
.ring-rainbow {
animation: none;
stroke-dashoffset: 0;
}
.tool-shimmer {
color: var(--ink-2);
}
}

View file

@ -1,4 +1,4 @@
import { memo, type ReactNode } from 'react';
import { createContext, lazy, memo, Suspense, useContext, type ReactNode } from 'react';
import ReactMarkdown, { type Components } from 'react-markdown';
import { Link } from 'react-router';
import remarkGfm from 'remark-gfm';
@ -11,7 +11,34 @@ export interface Citation {
chunkId: number;
}
const GenUiBlock = lazy(() => import('@/genui/GenUiBlock'));
/**
* Chat surfaces provide this so `openui-lang` fences in a reply render as live components.
* Elsewhere (notes, rationales) such fences stay code.
*/
export const GenUiContext = createContext<{ streaming: boolean; onSend?: (text: string) => void } | null>(null);
const GENUI_LANG = /\blanguage-(openui-lang|openui)\b/;
function Pre({ children, node }: { children?: ReactNode; node?: any }) {
const ctx = useContext(GenUiContext);
const code = node?.children?.[0];
const cls = code?.properties?.className;
const lang = Array.isArray(cls) ? cls.join(' ') : String(cls ?? '');
if (ctx && GENUI_LANG.test(lang)) {
const source = (code?.children ?? []).map((c: any) => (typeof c.value === 'string' ? c.value : '')).join('');
return (
<Suspense fallback={<div className="my-3 h-16 rounded-[14px] border border-line bg-surface" />}>
<GenUiBlock source={source} streaming={ctx.streaming} onSend={ctx.onSend} />
</Suspense>
);
}
return <pre>{children}</pre>;
}
const BASE: Components = {
pre: Pre as Components['pre'],
a: ({ href, children }) =>
// Links to pages inside the app (the assistant uses these to point at quizzes, decks and notes)
// navigate without a reload; everything else opens in a new tab.