Second revision: MCP servers, shared-link AI, flashcard modes, document previews
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s

Generation
- Every quiz is NCLEX style; "Practice exam" writes 50 questions.
- Calculation questions only when the material involves calculations (max 5 per exam).
- Broad topics: the class's topics are listed in the prompt, a quick grouping call maps
  narrow labels onto broad ones, and leftover variants are merged.
- Exact select-all count per batch; option order shuffled.
- Python check: at most 3 runs, fixed problems count as passed, cosmetic remarks ignored.

Assistant
- Text, tool steps and cards appear in the order they happen, with paragraph breaks
  between steps.
- Optional thinking box: fixed height, follows the newest text, can be scrolled back.
- "+" opens a material picker listing recent items; items can be dragged in from class
  pages; shorter placeholder.

MCP servers
- Streamable HTTP client; encrypted headers.
- Per-server instructions and switches for chat, Explain, generation and the quiz check.
- Settings UI.

Share links
- Optional "Explain this" and "Ask about this material" per link, off by default.
- Items are loaded on the server and checked against the share; no tools; rate-limited.
- Migration 4 stores the switches.

Study and documents
- Standard flashcard mode (optionally repeat missed cards until known) next to spaced
  repetition.
- Streak visuals restyled in the app palette.
- Side by side / Original document views, with sandboxed previews of Word and PowerPoint
  files.

Other
- Built-in embedding model baked into the image; sharp stubbed if it cannot load; real
  load error shown in Settings.
- Python runner blocks network and process modules in JavaScript too.
- "View questions and answers" removed from the quiz start screen.
- Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 15:48:54 -07:00
parent 5ea61c882c
commit 031f7bec31
45 changed files with 2918 additions and 397 deletions

View file

@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk } from '@/lib/queries';
import { McpSettings } from './McpSettings';
import { SemanticSettings } from './SemanticSettings';
import { REASONING_EFFORTS, type AdapterMeta, type AiModel, type AiStatus, type Provider, type ProviderKind, type TaskConfig, type TaskName, type TaskSettings } from '@/lib/types';
import { cx, formatCost, formatTokens, plural, timeAgo } from '@/lib/util';
@ -739,6 +740,8 @@ export default function AiSettings() {
{providers.data.length > 0 && <SemanticSettings providers={providers.data} />}
{providers.data.length > 0 && <McpSettings />}
{providers.data.length > 0 && <Usage />}
<ProviderDialog open={dialog.open} onClose={() => setDialog((d) => ({ ...d, open: false }))} adapters={meta.data.adapters} existing={dialog.existing} onSaved={afterSave} />

View file

@ -1,15 +1,52 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
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 { 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, useAssistantState } from '@/lib/assistantStore';
import { assistant, ITEM_DRAG_TYPE, useAssistantState } from '@/lib/assistantStore';
import { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
import type { AssistantEvent, ChatMessage, Mentionable, TaggedItem, TagKind, ToolActivity, UiItem } from '@/lib/types';
import type { AssistantEvent, ChatMessage, 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 { Badge, Button, Callout, IconButton, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner } from '@/ui';
import { Badge, Button, Callout, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Popover, Spinner } from '@/ui';
/** Applies one streamed event to a message. Text after a tool step or a new model step starts a new paragraph. */
function reduceEvent(m: ChatMessage, e: AssistantEvent): ChatMessage {
const parts = m.parts ? [...m.parts] : [];
switch (e.type) {
case 'start':
return { ...m, model: e.model };
case 'step': {
const last = parts[parts.length - 1];
if (last?.kind === 'text' && last.text) parts.push({ kind: 'text', text: '' });
return { ...m, parts };
}
case 'text': {
const last = parts[parts.length - 1];
const fresh = last?.kind !== 'text';
if (fresh) parts.push({ kind: 'text', text: e.delta });
else parts[parts.length - 1] = { kind: 'text', text: last.text + e.delta };
const startsBlock = fresh || (last?.kind === 'text' && last.text === '');
return { ...m, parts, text: m.text + (startsBlock && m.text ? '\n\n' : '') + e.delta };
}
case 'reasoning':
return { ...m, reasoning: (m.reasoning ?? '') + e.delta };
case 'tool': {
const known = m.tools.some((t) => t.id === e.tool.id);
if (!known) parts.push({ kind: 'tool', id: e.tool.id });
return { ...m, parts, tools: known ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] };
}
case 'ui':
parts.push({ kind: 'ui', index: m.ui.length });
return { ...m, parts, ui: [...m.ui, e.item] };
case 'error':
return { ...m, error: e.message };
default:
return m;
}
}
interface Conversation {
id: string;
@ -103,56 +140,123 @@ function ActionCard({ item, onResolved }: { item: Extract<UiItem, { type: 'actio
);
}
/** The model's reasoning, folded away by default: a short, scrollable window that follows the newest text. */
function ReasoningBox({ text, live }: { text: string; live: boolean }) {
const [open, setOpen] = useLocalStorage('sd.assistant.showReasoning', false);
const box = useRef<HTMLDivElement>(null);
const follow = useRef(true);
// Very long reasoning is trimmed from the front so the box stays light.
const shown = text.length > 24_000 ? `…${text.slice(-24_000)}` : text;
useEffect(() => {
const el = box.current;
if (el && follow.current) el.scrollTop = el.scrollHeight;
}, [shown, open]);
return (
<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">
<Brain className={cx('size-3.5', live && 'animate-pulse text-accent')} />
{open ? 'Hide thinking' : live ? 'Thinking… show' : 'Show thinking'}
<ChevronRight className={cx('size-3.5 transition-transform', open && 'rotate-90')} />
</button>
{open && (
<div
ref={box}
onScroll={(e) => {
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"
>
{shown}
</div>
)}
</div>
);
}
/** 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 }) {
const navigate = useNavigate();
const [toolsOpen, setToolsOpen] = useState(false);
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]);
const openCite = (c: Citation) => {
onNavigate();
navigate(`/documents/${c.documentId}?chunk=${c.chunkId}`);
};
const cards = message.ui.filter((u) => u.type !== 'sources');
const running = message.tools.filter((t) => t.status === 'running');
const finished = message.tools.filter((t) => t.status !== 'running');
const thinking = message.pending && !message.text && running.length === 0;
// Text, tool steps and cards in the order they happened. Older messages without parts fall back to text first.
const parts: MessagePart[] = message.parts?.length ? message.parts : [...(message.text ? [{ kind: 'text' as const, text: message.text }] : []), ...message.tools.map((t) => ({ kind: 'tool' as const, id: t.id })), ...message.ui.map((_, index) => ({ kind: 'ui' as const, index }))];
const blocks: ({ kind: 'text'; text: string } | { kind: 'tools'; tools: ToolActivity[] } | { kind: 'ui'; item: UiItem })[] = [];
for (const p of parts) {
if (p.kind === 'text') {
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;
const last = blocks[blocks.length - 1];
if (last?.kind === 'tools') last.tools.push(tool);
else blocks.push({ kind: 'tools', tools: [tool] });
} else {
const item = message.ui[p.index];
if (item && item.type !== 'sources') blocks.push({ kind: 'ui', item });
}
}
return (
<div className="space-y-2.5">
{finished.length > 0 && (
<div>
<button type="button" aria-expanded={toolsOpen} onClick={() => setToolsOpen(!toolsOpen)} 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', toolsOpen && 'rotate-90')} />
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
{finished.some((t) => t.status === 'error') && <CircleAlert className="size-3.5 text-bad" />}
</button>
{toolsOpen && <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>
{message.reasoning && <ReasoningBox text={message.reasoning} live={Boolean(message.pending) && !message.text} />}
{blocks.map((b, i) =>
b.kind === 'text' ? (
<Markdown key={i} citations={citations} onCite={openCite} className="text-[15px]">
{b.text}
</Markdown>
) : b.kind === 'tools' ? (
<ToolGroup 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 === '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">
<Play className="size-4 fill-current" />
</span>
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{b.item.title}</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
) : null,
)}
{running.map((t) => (
<ToolLine key={t.id} tool={t} />
))}
{thinking && (
<div className="flex items-center gap-2 text-[13px] text-ink-3" role="status">
<Spinner className="size-3.5" label="Thinking" /> {message.reasoning ? 'Thinking it through' : 'Thinking'}
</div>
)}
{message.text && <Markdown citations={citations} onCite={openCite} className="text-[15px]">{message.text}</Markdown>}
{cards.map((item, i) =>
item.type === 'draft' ? (
<DraftCard key={i} item={item} onNavigate={onNavigate} />
) : item.type === 'action' ? (
<ActionCard key={i} item={item} onResolved={(status, result) => onAction(item.actionId, status, result)} />
) : item.type === 'link' ? (
<Link key={i} to={`/${ITEM_URL[item.kind]}/${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">
<Play className="size-4 fill-current" />
</span>
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{item.title}</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
) : null,
)}
{cited.length > 0 && (
<div className="flex flex-wrap gap-1.5 pt-0.5">
{cited.map(({ n, cite }) => (
@ -242,7 +346,8 @@ function useMentionables(classId: string | null, query: string, enabled: boolean
const q = useQuery({
queryKey: ['ai', 'mentionables', classId ?? '', classId ? '' : debounced],
queryFn: () => api.get<{ items: Mentionable[] }>(`/api/ai/mentionables?${new URLSearchParams(classId ? { classId } : { q: debounced })}`).then((r) => r.items),
enabled: enabled && (Boolean(classId) || debounced.length >= 1),
// An empty search lists the most recently changed materials, so the picker is useful before typing.
enabled,
staleTime: 30_000,
});
const needle = query.toLowerCase();
@ -278,6 +383,9 @@ export default function AssistantPanel({
const [tags, setTags] = useState<TaggedItem[]>([]);
const [mention, setMention] = useState<{ start: number; query: string } | null>(null);
const [mentionIndex, setMentionIndex] = useState(0);
const [pickerOpen, setPickerOpen] = useState(false);
const [pickerQuery, setPickerQuery] = useState('');
const [dropping, setDropping] = useState(false);
const [modelId, setModelId] = useLocalStorage('sd.assistant.model', '');
/** The connection to the running turn. Aborting it only detaches: the turn continues on the server. */
const stream = useRef<AbortController | null>(null);
@ -301,16 +409,27 @@ export default function AssistantPanel({
[variant],
);
/** Applies one streamed event to the pending assistant message. */
const applyEvent = useCallback((pendingId: string, e: AssistantEvent) => {
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
if (e.type === 'start') patch((m) => ({ ...m, model: e.model }));
else if (e.type === 'text') patch((m) => ({ ...m, text: m.text + e.delta }));
else if (e.type === 'reasoning') patch((m) => ({ ...m, reasoning: (m.reasoning ?? '') + e.delta }));
else if (e.type === 'tool') patch((m) => ({ ...m, tools: m.tools.some((t) => t.id === e.tool.id) ? m.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...m.tools, e.tool] }));
else if (e.type === 'ui') patch((m) => ({ ...m, ui: [...m.ui, e.item] }));
else if (e.type === 'error') patch((m) => ({ ...m, error: e.message }));
/**
* Streamed events are applied in batches (every 50 ms) rather than one render per token, so
* long answers and reasoning do not make the page lag.
*/
const queued = useRef<{ id: string; e: AssistantEvent }[]>([]);
const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const flushEvents = useCallback(() => {
if (flushTimer.current) clearTimeout(flushTimer.current);
flushTimer.current = null;
const batch = queued.current;
queued.current = [];
if (batch.length === 0) return;
setMessages((list) => list.map((m) => batch.reduce((acc, { id, e }) => (id === m.id ? reduceEvent(acc, e) : acc), m)));
}, []);
const applyEvent = useCallback(
(pendingId: string, e: AssistantEvent) => {
queued.current.push({ id: pendingId, e });
if (!flushTimer.current) flushTimer.current = setTimeout(flushEvents, 50);
},
[flushEvents],
);
/** Follows a turn (new or already running) until it finishes or this panel detaches. */
const follow = useCallback(
@ -338,6 +457,7 @@ export default function AssistantPanel({
} catch (e) {
if ((e as Error)?.name !== 'AbortError') setMessages((list) => list.map((m) => (m.id === pendingId ? { ...m, error: errorMessage(e) } : m)));
} finally {
flushEvents();
if (stream.current === controller) {
stream.current = null;
setBusy(false);
@ -358,7 +478,7 @@ export default function AssistantPanel({
void startedId;
}
},
[applyEvent, onConversationChange, qc, refresh, setConversation],
[applyEvent, flushEvents, onConversationChange, qc, refresh, setConversation],
);
const load = useCallback(
@ -377,7 +497,7 @@ export default function AssistantPanel({
// Still answering: show what is saved up to the question, then replay the live turn.
const lastUser = res.messages.map((m) => m.role).lastIndexOf('user');
const pendingId = `p${Date.now()}`;
setMessages([...res.messages.slice(0, lastUser + 1), { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
setMessages([...res.messages.slice(0, lastUser + 1), { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], parts: [], createdAt: Date.now(), pending: true }]);
setLoadingHistory(false);
void follow(pendingId, (signal, onEvent) => streamEvents<AssistantEvent>(`/api/ai/chat/${id}/stream`, undefined, onEvent, signal));
} catch {
@ -441,7 +561,7 @@ export default function AssistantPanel({
setMessages((m) => [
...m,
{ id: `u${Date.now()}`, role: 'user', text: message, tags: sentTags.length ? sentTags : undefined, tools: [], ui: [], createdAt: Date.now() },
{ id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true },
{ id: pendingId, role: 'assistant', text: '', tools: [], ui: [], parts: [], createdAt: Date.now(), pending: true },
]);
await follow(pendingId, (signal, onEvent) =>
streamEvents<AssistantEvent>(
@ -532,23 +652,42 @@ export default function AssistantPanel({
}
setMention(null);
};
const openPicker = () => {
const el = inputRef.current;
const caret = el?.selectionStart ?? input.length;
const needsSpace = caret > 0 && !/\s/.test(input[caret - 1] ?? '');
const next = `${input.slice(0, caret)}${needsSpace ? ' ' : ''}@${input.slice(caret)}`;
setInput(next);
const at = caret + (needsSpace ? 1 : 0) + 1;
setMention({ start: at - 1, query: '' });
setMentionIndex(0);
setTimeout(() => {
el?.focus();
el?.setSelectionRange(at, at);
}, 0);
const pickerOptions = useMentionables(context.classId, pickerQuery, pickerOpen);
const toggleTag = (item: TaggedItem) =>
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t.filter((x) => !(x.kind === item.kind && x.id === item.id)) : [...t, { kind: item.kind, id: item.id, title: item.title }]));
const onDrop = (e: React.DragEvent) => {
setDropping(false);
const raw = e.dataTransfer.getData(ITEM_DRAG_TYPE);
if (!raw) return;
e.preventDefault();
try {
const item = JSON.parse(raw) as TaggedItem;
if (item?.id && item.kind) {
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t : [...t, { kind: item.kind, id: item.id, title: item.title }]));
inputRef.current?.focus();
}
} catch {
/* not ours */
}
};
return (
<div className="flex min-h-0 flex-1 flex-col">
<div
className={cx('relative flex min-h-0 flex-1 flex-col', dropping && 'ring-2 ring-accent ring-inset')}
onDragOver={(e) => {
if (!e.dataTransfer.types.includes(ITEM_DRAG_TYPE)) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'link';
if (!dropping) setDropping(true);
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDropping(false);
}}
onDrop={onDrop}
>
{dropping && (
<div className="pointer-events-none absolute inset-0 z-40 grid place-items-center bg-accent-soft/70 text-sm font-medium text-accent">Drop to add it to this chat</div>
)}
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-5')}>
<span className="grid size-8 shrink-0 place-items-center rounded-[10px] bg-ink text-marker">
<Sparkles className="size-4" />
@ -625,7 +764,7 @@ export default function AssistantPanel({
) : messages.length === 0 ? (
<div className="mx-auto flex h-full max-w-md flex-col justify-center pb-6">
<h2 className="display text-[26px]">What are we working on?</h2>
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review. Type @ to point me at a specific quiz, deck, note or document.</p>
<p className="mt-1.5 text-sm text-ink-2">I can read your documents, look at your results, and prepare quizzes, flashcards and study guides for you to review. Use + (or type @, or drag items in) to point me at a specific quiz, deck, note or document.</p>
<div className="mt-5 space-y-2">
{suggestions.map((s) => (
<button key={s} type="button" onClick={() => send(s)} className="group flex w-full items-center gap-3 rounded-[13px] border border-line bg-surface px-3.5 py-2.5 text-left text-sm shadow-1 hover:border-ink-3">
@ -677,9 +816,9 @@ export default function AssistantPanel({
)}
{mention && (
<div role="listbox" aria-label="Tag a material" className="absolute inset-x-0 bottom-full z-30 mb-2 max-h-72 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-2">
<div className="eyebrow px-2 pt-1 pb-1.5">{context.classId ? `Materials in ${className ?? 'this class'}` : 'Your library'}</div>
<div className="eyebrow px-2 pt-1 pb-1.5">{context.classId ? `Materials in ${className ?? 'this class'}` : mention.query ? 'Your library' : 'Recently changed'}</div>
{pickable.length === 0 ? (
<div className="px-2.5 py-2 text-[13px] text-ink-3">{context.classId || mention.query ? 'Nothing matches.' : 'Type to search your quizzes, decks, notes and documents.'}</div>
<div className="px-2.5 py-2 text-[13px] text-ink-3">{mention.query ? 'Nothing matches.' : 'Nothing in your library yet.'}</div>
) : (
pickable.map((o, i) => (
<button
@ -757,13 +896,57 @@ export default function AssistantPanel({
if (!busy) void send(input);
}
}}
placeholder={context.classId ? 'Ask anything. Type @ to tag a quiz, deck, note or document…' : 'Ask anything, or describe what to create…'}
placeholder={variant === 'drawer' ? 'Ask anything…' : 'Ask anything, or describe what to create…'}
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"
/>
<IconButton label="Tag a material" size="sm" className="mb-0.5" onClick={openPicker}>
<AtSign />
</IconButton>
<Popover
open={pickerOpen}
onOpenChange={(o) => {
setPickerOpen(o);
if (!o) setPickerQuery('');
}}
align="end"
className="w-80 p-2"
trigger={
<IconButton label="Add materials" size="sm" className="mb-0.5" tooltip={false}>
<Plus />
</IconButton>
}
>
<div className="relative mb-1.5">
<Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-ink-3" aria-hidden />
<Input autoFocus value={pickerQuery} onChange={(e) => setPickerQuery(e.target.value)} placeholder={context.classId ? `Search ${className ?? 'this class'}` : 'Search your library'} aria-label="Search materials" className="h-9 pl-8" />
</div>
<div role="listbox" aria-label="Materials" aria-multiselectable className="max-h-64 overflow-y-auto">
{pickerOptions.length === 0 ? (
<div className="px-2.5 py-3 text-[13px] text-ink-3">{pickerQuery ? 'Nothing matches.' : 'Nothing in your library yet.'}</div>
) : (
pickerOptions.map((o) => {
const on = tags.some((t) => t.kind === o.kind && t.id === o.id);
return (
<button key={`${o.kind}:${o.id}`} type="button" role="option" aria-selected={on} onClick={() => toggleTag(o)} className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-ink/6">
<span className={cx('grid size-7 shrink-0 place-items-center rounded-md [&>svg]:size-3.5', on ? 'bg-accent text-accent-ink' : 'bg-sunken text-ink-2')}>{on ? <Check /> : TAG_ICON[o.kind]}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm">{o.title}</span>
<span className="block truncate text-[11px] text-ink-3">
{TAG_NOUN[o.kind]}
{o.folderName ? ` · ${o.folderName}` : ''}
{!context.classId ? ` · ${o.className}` : ''}
</span>
</span>
</button>
);
})
)}
</div>
<div className="mt-1.5 flex items-center justify-between border-t border-line px-1 pt-1.5 text-[11px] text-ink-3">
<span>{tags.length ? `${plural(tags.length, 'item')} added` : 'Tip: type @ in the message, or drag items here'}</span>
<button type="button" className="font-medium text-accent hover:underline" onClick={() => setPickerOpen(false)}>
Done
</button>
</div>
</Popover>
<button
type="submit"
disabled={!busy && !input.trim()}

View file

@ -7,12 +7,15 @@ import { Button, Callout, Spinner } from '@/ui';
type ExplainBody =
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string }
| { kind: 'card'; front: string; back: string }
| { kind: 'text'; text: 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' };
/** "Explain with AI": streams a short explanation and accepts follow-up questions. */
export function Explain({ body, label = 'Explain with AI', className }: { body: ExplainBody; label?: string; className?: string }) {
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 [busy, setBusy] = useState(false);
@ -40,7 +43,7 @@ export function Explain({ body, label = 'Explain with AI', className }: { body:
abort.current = controller;
try {
await streamEvents<Event>(
'/api/ai/explain',
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)));

View file

@ -36,7 +36,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
const [text, setText] = useState('');
const [focus, setFocus] = useState('');
const [count, setCount] = useState(15);
const [style, setStyle] = useState<'nclex' | 'standard' | 'recall'>('nclex');
const [format, setFormat] = useState<'practice' | 'exam'>('practice');
const [difficulty, setDifficulty] = useState<'mixed' | 'easy' | 'medium' | 'hard'>('mixed');
const [sata, setSata] = useState(30);
const [cardStyle, setCardStyle] = useState<'concise' | 'detailed' | 'medication' | 'definition'>('concise');
@ -62,7 +62,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
setTemplateId('');
setModelId('');
setCount(k === 'deck' ? 30 : 15);
setStyle('nclex');
setFormat('practice');
setDifficulty('mixed');
setSata(30);
setCardStyle('concise');
@ -81,7 +81,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
const p = t.payload;
if (p.kind && !preset?.kind) setKind(p.kind);
if (typeof p.count === 'number') setCount(p.count);
if (p.style) setStyle(p.style);
if (p.kind === 'quiz') setFormat(p.format === 'exam' ? 'exam' : 'practice');
if (p.difficulty) setDifficulty(p.difficulty);
if (typeof p.sataShare === 'number') setSata(Math.round(p.sataShare * 100));
if (p.cardStyle) setCardStyle(p.cardStyle);
@ -104,7 +104,7 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
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 };
if (kind === 'quiz') Object.assign(body, { count, style, difficulty, sataShare: sata / 100, verify });
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 });
if (fixedSource && kind !== 'note') delete body.count;
@ -247,12 +247,20 @@ export function GenerateDialog({ open, onClose, classId, folderId, preset }: { o
<Input type="number" min={1} max={100} value={count} onChange={(e) => setCount(Math.max(1, Math.min(100, Number(e.target.value) || 1)))} />
</Field>
)}
<Field label="Style">
<Select value={style} onChange={(e) => setStyle(e.target.value as typeof style)}>
<option value="nclex">NCLEX-style (clinical judgment)</option>
<option value="standard">Standard exam questions</option>
<option value="recall">Quick recall</option>
</Select>
<Field label="Set" hint={format === 'exam' ? 'Like a unit exam: 50 questions, up to 5 calculations when the material has them.' : 'All questions are NCLEX style.'}>
<Segmented
label="Set"
value={format}
onChange={(f) => {
setFormat(f);
setCount(f === 'exam' ? 50 : 15);
}}
options={[
{ value: 'practice', label: 'Practice set' },
{ value: 'exam', label: 'Practice exam' },
]}
className="w-full"
/>
</Field>
<Field label="Difficulty">
<Select value={difficulty} onChange={(e) => setDifficulty(e.target.value as typeof difficulty)}>

View file

@ -0,0 +1,257 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { CircleAlert, CircleCheck, Plug, Plus, Trash2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { Badge, Button, Dialog, Field, Input, Section, Switch, Textarea, useConfirm } from '@/ui';
type McpArea = 'chat' | 'explain' | 'generate' | 'check';
type McpAreas = Record<McpArea, boolean>;
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.' },
{ key: 'check', label: 'Quiz check', description: 'The answer check after a quiz is generated.' },
];
const DEFAULT_AREAS: McpAreas = { chat: true, explain: true, generate: false, check: false };
interface McpServer {
id: string;
name: string;
url: string;
enabled: boolean;
instructions: string;
areas: McpAreas;
headerNames: string[];
lastTestAt: number | null;
lastTestOk: boolean | null;
lastTestMessage: string | null;
}
interface TestResult {
ok: boolean;
message: string;
tools: { name: string; description: string }[];
latencyMs: number;
}
const KEY = ['ai', 'mcp'];
function parseHeaders(text: string): Record<string, string> {
const out: Record<string, string> = {};
for (const line of text.split('\n')) {
const at = line.indexOf(':');
if (at > 0) out[line.slice(0, at).trim()] = line.slice(at + 1).trim();
}
return out;
}
function ServerDialog({ open, existing, onClose, onSaved }: { open: boolean; existing: McpServer | null; onClose: () => void; onSaved: (s: McpServer) => void }) {
const [name, setName] = useState('');
const [url, setUrl] = useState('');
const [headers, setHeaders] = useState('');
const [instructions, setInstructions] = useState('');
const [areas, setAreas] = useState<McpAreas>(DEFAULT_AREAS);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!open) return;
setName(existing?.name ?? '');
setUrl(existing?.url ?? '');
setHeaders('');
setInstructions(existing?.instructions ?? '');
setAreas(existing?.areas ?? DEFAULT_AREAS);
}, [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 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();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title={existing ? `Edit ${existing.name}` : 'Connect an MCP server'}
description="The assistant can call this server's tools. Only connect servers you trust: their tools run without asking."
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={!canSave} onClick={save}>
{existing ? 'Save' : 'Connect'}
</Button>
</>
}
>
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
if (canSave) void save();
}}
>
<Field label="Name" hint="Shown next to each tool the assistant uses.">
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Drug reference" maxLength={60} />
</Field>
<Field label="Server URL" hint="The Streamable HTTP endpoint, usually ending in /mcp. From inside Docker, use your server's address rather than localhost.">
<Input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://example.com/mcp" inputMode="url" spellCheck={false} className="num text-[13px]" />
</Field>
<Field label="When to use it" optional hint="Your guidance for the AI, for example: Use for current drug information. Do not use for questions my course material already answers.">
<Textarea rows={3} value={instructions} onChange={(e) => setInstructions(e.target.value)} maxLength={2000} placeholder="Use this to look up…" />
</Field>
<fieldset className="space-y-3 rounded-xl border border-line p-3.5">
<legend className="px-1 text-sm font-medium text-ink">Where it can be used</legend>
{AREAS.map((a) => (
<Switch key={a.key} checked={areas[a.key]} onChange={(v) => setAreas((s) => ({ ...s, [a.key]: v }))} label={a.label} description={a.description} />
))}
</fieldset>
<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>
<button type="submit" hidden />
</form>
</Dialog>
);
}
function ServerRow({ server, onEdit, reload }: { server: McpServer; onEdit: () => void; reload: () => void }) {
const confirm = useConfirm();
const [testing, setTesting] = useState(false);
const [tools, setTools] = useState<TestResult['tools'] | null>(null);
const test = async () => {
setTesting(true);
try {
const { result } = await api.post<{ result: TestResult }>(`/api/ai/mcp/${server.id}/test`);
if (result.ok) {
toast.success(result.message);
setTools(result.tools);
} else toast.error(result.message);
reload();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setTesting(false);
}
};
const toggle = async (enabled: boolean) => {
try {
await api.patch(`/api/ai/mcp/${server.id}`, { enabled });
reload();
} catch (e) {
toast.error(errorMessage(e));
}
};
const remove = async () => {
if (!(await confirm({ title: `Remove ${server.name}?`, message: 'The assistant will no longer see its tools.', confirmLabel: 'Remove', danger: true }))) return;
try {
await api.del(`/api/ai/mcp/${server.id}`);
reload();
} catch (e) {
toast.error(errorMessage(e));
}
};
return (
<div className="p-4">
<div className="flex flex-wrap items-start gap-3">
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-sunken text-ink-2">
<Plug className="size-4" />
</span>
<div className="min-w-0 flex-1">
<div className="font-semibold">{server.name}</div>
<div className="num truncate text-xs text-ink-3">{server.url}</div>
<div className="mt-1.5 flex flex-wrap gap-1">
{AREAS.filter((a) => server.areas[a.key]).map((a) => (
<Badge key={a.key}>{a.label}</Badge>
))}
{!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.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" />}
<span className="min-w-0 break-words">{server.lastTestMessage}</span>
</div>
)}
</div>
<Switch checked={server.enabled} onChange={toggle} label={<span className="sr-only">Use {server.name}</span>} />
</div>
<div className="mt-3 flex flex-wrap gap-2">
<Button size="sm" variant="secondary" loading={testing} onClick={test}>
Test and list tools
</Button>
<Button size="sm" variant="ghost" onClick={onEdit}>
Edit
</Button>
<Button size="sm" variant="ghost" icon={<Trash2 />} onClick={remove} className="ml-auto text-bad">
Remove
</Button>
</div>
{tools && (
<ul className="mt-3 space-y-1 rounded-[10px] border border-line bg-sunken/50 p-3 text-xs">
{tools.length === 0 && <li className="text-ink-3">This server has no tools.</li>}
{tools.map((t) => (
<li key={t.name}>
<span className="num font-medium text-ink">{t.name}</span>
{t.description && <span className="text-ink-3"> · {t.description}</span>}
</li>
))}
</ul>
)}
</div>
);
}
/** MCP servers: external tools the assistant can call. */
export function McpSettings() {
const qc = useQueryClient();
const q = useQuery({ queryKey: KEY, queryFn: () => api.get<{ servers: McpServer[] }>('/api/ai/mcp') });
const [dialog, setDialog] = useState<{ open: boolean; existing: McpServer | null }>({ open: false, existing: null });
const reload = () => qc.invalidateQueries({ queryKey: KEY });
const servers = q.data?.servers ?? [];
return (
<Section
title="MCP servers"
action={
<Button size="sm" variant="secondary" icon={<Plus />} onClick={() => setDialog({ open: true, existing: null })}>
Add server
</Button>
}
>
{servers.length > 0 ? (
<div className="card divide-y divide-line">
{servers.map((s) => (
<ServerRow key={s.id} server={s} onEdit={() => setDialog({ open: true, existing: s })} reload={reload} />
))}
</div>
) : (
<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>
<ServerDialog
open={dialog.open}
existing={dialog.existing}
onClose={() => setDialog((d) => ({ ...d, open: false }))}
onSaved={(s) => {
void reload();
if (!dialog.existing) toast.success(`Added ${s.name}. Test it to see its tools.`);
}}
/>
</Section>
);
}

View file

@ -145,6 +145,11 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
{data.local.status === 'loading' ? ' Loading the model now…' : ''}
</p>
)}
{isLocal && data.local.status === 'error' && data.local.error && (
<Callout tone="bad" icon={<CircleAlert />} className="mt-3" title="The built-in model could not load">
{data.local.error}
</Callout>
)}
{eligible.length === 0 && !isLocal && (
<Callout tone="accent" icon={<Sparkles />} className="mt-3" title="Cloud embeddings need a provider">
Use the built-in model, or connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic and DeepSeek do not offer embeddings.

View file

@ -0,0 +1,129 @@
import { CornerDownLeft, MessageCircleQuestion, Sparkles, Square, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { errorMessage, streamEvents } from '@/lib/api';
import { cx } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Button, Callout, IconButton, Spinner } from '@/ui';
type Event = { type: 'text'; delta: string } | { type: 'error'; message: string } | { type: 'done' };
interface Turn {
role: 'user' | 'assistant';
text: string;
}
/**
* 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.
*/
export function SharedAssistant({ token, title, item }: { token: string; title: string; item?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string } }) {
const [open, setOpen] = useState(false);
const [turns, setTurns] = useState<Turn[]>([]);
const [input, setInput] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const abort = useRef<AbortController | null>(null);
const list = useRef<HTMLDivElement>(null);
useEffect(() => () => abort.current?.abort(), []);
useEffect(() => {
const el = list.current;
if (el) el.scrollTop = el.scrollHeight;
}, [turns, open]);
const send = 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));
}
};
if (!open) {
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>
);
}
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" />
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold">Ask about this</div>
<div className="truncate text-xs text-ink-3">{title}</div>
</div>
<IconButton label="Close" onClick={() => setOpen(false)}>
<X />
</IconButton>
</header>
<div ref={list} className="flex-1 space-y-3 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,
)}
{error && (
<Callout tone="bad" className="py-2">
{error}
</Callout>
)}
</div>
<form
className="flex gap-2 border-t border-line p-3"
onSubmit={(e) => {
e.preventDefault();
if (busy) return abort.current?.abort();
const text = input.trim();
if (!text) return;
setInput('');
void send(text.slice(0, 4000));
}}
>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Ask a question…"
aria-label="Your question"
className={cx('h-10 min-w-0 flex-1 rounded-[10px] border border-line-strong bg-paper px-3 text-sm outline-none focus:border-accent')}
/>
<Button type="submit" variant={busy ? 'secondary' : 'primary'} icon={busy ? <Square className="fill-current" /> : <CornerDownLeft />} aria-label={busy ? 'Stop' : 'Send'}>
{busy ? 'Stop' : 'Send'}
</Button>
</form>
<p className="px-4 pb-2.5 text-[11px] text-ink-3">AI can be wrong. Nothing you type here is saved.</p>
</section>
);
}

View file

@ -154,7 +154,7 @@ function PresetDialog({ template, onClose }: { template: Template | null; onClos
setBusy(true);
try {
const clean = { ...payload };
if (kind !== 'quiz') ['style', 'difficulty', 'sataShare'].forEach((k) => delete clean[k]);
if (kind !== 'quiz') ['style', 'format', 'difficulty', 'sataShare'].forEach((k) => delete clean[k]);
if (kind !== 'deck') delete clean.cardStyle;
if (kind !== 'note') delete clean.noteStyle;
if (kind === 'note') delete clean.count;
@ -210,11 +210,10 @@ function PresetDialog({ template, onClose }: { template: Template | null; onClos
)}
{kind === 'quiz' && (
<div className="grid gap-3 sm:grid-cols-3">
<Field label="Style">
<Select value={payload.style ?? 'nclex'} onChange={(e) => set({ style: e.target.value })}>
<option value="nclex">NCLEX</option>
<option value="standard">Standard</option>
<option value="recall">Quick recall</option>
<Field label="Set">
<Select value={payload.format ?? 'practice'} onChange={(e) => set({ format: e.target.value, style: 'nclex', ...(e.target.value === 'exam' && !payload.count ? { count: 50 } : {}) })}>
<option value="practice">Practice set</option>
<option value="exam">Practice exam</option>
</Select>
</Field>
<Field label="Difficulty">

View file

@ -362,6 +362,22 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
</span>
</div>
<p className="text-[13px] text-ink-3">"New link" replaces the address, so the old one stops working. Visitors study on their own; nothing they do touches your progress.</p>
<fieldset className="space-y-3.5 rounded-xl border border-line p-4">
<legend className="px-1 text-sm font-medium text-ink">AI for visitors</legend>
<Switch
checked={Boolean(share.ai?.explain)}
onChange={(v) => act(() => api.patch<{ share: Share }>(`/api/shares/${share.id}`, { ai: { explain: v } }))}
label="Explain this"
description="Visitors can ask the AI to explain a question or flashcard."
/>
<Switch
checked={Boolean(share.ai?.assistant)}
onChange={(v) => act(() => api.patch<{ share: Share }>(`/api/shares/${share.id}`, { ai: { assistant: v } }))}
label="Ask about this material"
description="A chat that answers from what you shared only. It can't see the rest of your library or your connected tools."
/>
<p className="text-xs text-ink-3">Uses your AI models and is billed to your API keys. Requests are rate-limited per visitor.</p>
</fieldset>
</>
) : (
<Callout icon={<Link2Off />}>{share ? 'The link is off. Anyone who has it sees a "no longer available" page.' : 'Sharing is off. Nobody else can see this.'}</Callout>

View file

@ -1,5 +1,5 @@
import { ArrowLeft, Check, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { ArrowLeft, Check, Flame, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import { cx, plural, shuffle, useHotkeys } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { Button, IconButton, ProgressBar } from '@/ui';
@ -14,49 +14,31 @@ export const STREAK_HOT = 5;
export const isStreakMilestone = (n: number) => n === 5 || (n >= 10 && n % 10 === 0);
export const streakTier = (n: number): StreakTier => (n >= 20 ? 3 : n >= 10 ? 2 : 1);
const BURST_MS: Record<StreakTier, number> = { 1: 1600, 2: 1900, 3: 2400 };
const BURST_COPY: Record<StreakTier, string> = { 1: 'On fire', 2: 'Blazing', 3: 'Unstoppable' };
export function FlameIcon({ className }: { className?: string }) {
const id = `flame-${useId().replace(/[^a-zA-Z0-9]/g, '')}`;
return (
<svg className={className} viewBox="0 0 24 24" aria-hidden focusable="false">
<defs>
<linearGradient id={id} x1="0" y1="1" x2="0" y2="0">
<stop offset="0%" stopColor="#ea580c" />
<stop offset="55%" stopColor="#fb923c" />
<stop offset="100%" stopColor="#fbbf24" />
</linearGradient>
</defs>
<path
fill={`url(#${id})`}
fillRule="evenodd"
clipRule="evenodd"
d="M12.963 2.286a.75.75 0 0 0-1.071-.136 9.742 9.742 0 0 0-3.539 6.177A7.547 7.547 0 0 1 6.648 6.61a.75.75 0 0 0-1.152-.082A9 9 0 1 0 15.68 4.534a7.46 7.46 0 0 1-2.717-2.248ZM15.75 14.25a3.75 3.75 0 1 1-7.313-1.172c.628.465 1.35.81 2.133 1a5.99 5.99 0 0 1 1.925-3.547 3.75 3.75 0 0 1 3.255 3.719Z"
/>
</svg>
);
}
const BURST_COPY: Record<StreakTier, string> = { 1: 'On a roll', 2: 'Hot streak', 3: 'Unstoppable' };
export function StreakChip({ streak }: { streak: number }) {
if (streak < 2) return null;
const hot = streak >= STREAK_HOT;
return (
<span key={hot ? 'hot' : 'warm'} className={cx('streak-chip inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-xs font-bold whitespace-nowrap', hot ? 'streak-chip-hot' : 'bg-ink/7 text-ink-2')}>
{hot && <FlameIcon className="size-3.5 shrink-0" />}
<span key={hot ? 'hot' : 'warm'} className={cx('streak-chip num inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-xs font-semibold whitespace-nowrap', hot ? 'streak-chip-hot' : 'bg-ink/7 text-ink-2')}>
{hot && <Flame className="size-3.5 shrink-0" strokeWidth={2.4} />}
{streak} in a row
</span>
);
}
/** Milestone moment: the count, marked with a highlighter stroke, in the app's own type and colours. */
function StreakBurst({ streak, tier }: { streak: number; tier: StreakTier }) {
const flame = { 1: 'size-16', 2: 'size-24', 3: 'size-36 md:size-44' }[tier];
const heading = { 1: 'text-lg', 2: 'text-2xl', 3: 'text-4xl md:text-5xl' }[tier];
const size = { 1: 'text-6xl', 2: 'text-7xl', 3: 'text-8xl md:text-9xl' }[tier];
return (
<div className="streak-scrim pointer-events-none absolute inset-0 z-30 flex items-center justify-center rounded-[24px]" style={{ '--streak-ms': `${BURST_MS[tier]}ms` } as CSSProperties} role="status" aria-live="polite">
<div className="streak-pop flex flex-col items-center">
<FlameIcon className={cx('streak-flame', flame)} />
<span className={cx('streak-heading mt-1 font-black tracking-wide uppercase', heading)}>{BURST_COPY[tier]}</span>
<span className="mt-1 text-sm font-semibold text-ink">{streak} in a row</span>
<div className="streak-pop flex flex-col items-center text-center">
<span className="flex items-center gap-1.5 text-xs font-semibold tracking-[0.16em] text-accent uppercase">
<Flame className="streak-flame size-4" strokeWidth={2.4} />
{BURST_COPY[tier]}
</span>
<span className={cx('streak-mark num mt-2 px-4 leading-none font-semibold tracking-tight text-ink', size)}>{streak}</span>
<span className="mt-2 font-serif text-xl text-ink-2 italic">in a row</span>
</div>
</div>
);
@ -250,6 +232,10 @@ export interface CramState {
shuffled: boolean;
/** Which pass this is: 1 = whole deck, 2+ = cards still being learned. */
round: number;
/** Standard mode option: a missed card goes to the back of the pile until it is known. */
repeatMissed?: boolean;
/** Cards that were missed at least once in this session (repeat mode). */
retried?: string[];
}
export interface CramCard {
@ -259,9 +245,9 @@ export interface CramCard {
hint?: string;
}
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1): CramState {
export function freshCramState(cards: CramCard[], shuffled: boolean, round = 1, repeatMissed = false): CramState {
const ids = cards.map((c) => c.id);
return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round };
return { order: shuffled ? shuffle(ids) : ids, index: 0, known: [], unknown: [], shuffled, round, repeatMissed, retried: [] };
}
/** Drops cards that no longer exist and clamps the position, so a saved session survives deck edits. */
@ -277,6 +263,8 @@ export function reconcileCramState(state: CramState | null | undefined, cards: C
unknown: (state.unknown ?? []).filter((id) => valid.has(id)),
shuffled: Boolean(state.shuffled),
round: state.round ?? 1,
repeatMissed: Boolean(state.repeatMissed),
retried: (state.retried ?? []).filter((id) => valid.has(id)),
};
}
@ -328,9 +316,13 @@ export function CramSession({
setLeaving(known ? 'right' : 'left');
record(known);
onGrade?.(card.id, known);
// Repeat mode: a missed card goes to the back of the pile and comes round again.
const requeue = !known && state.repeatMissed;
const next: CramState = {
...state,
index: state.index + 1,
order: requeue ? [...state.order, card.id] : state.order,
retried: requeue ? [...new Set([...(state.retried ?? []), card.id])] : state.retried,
known: known ? [...state.known.filter((x) => x !== card.id), card.id] : state.known.filter((x) => x !== card.id),
unknown: known ? state.unknown.filter((x) => x !== card.id) : [...state.unknown.filter((x) => x !== card.id), card.id],
};
@ -339,7 +331,7 @@ export function CramSession({
const move = (delta: number) => !busy && onState({ ...state, index: Math.max(0, Math.min(total, state.index + delta)) });
const restart = (shuffled = state.shuffled) => {
reset();
onState(freshCramState(cards, shuffled));
onState(freshCramState(cards, shuffled, 1, state.repeatMissed));
};
const shuffleRemaining = () => {
if (busy) return;
@ -351,7 +343,7 @@ export function CramSession({
};
const studyUnknown = () => {
reset();
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1));
onState(freshCramState(cards.filter((c) => state.unknown.includes(c.id)), true, state.round + 1, state.repeatMissed));
};
useHotkeys({
@ -371,7 +363,7 @@ export function CramSession({
<div className="flex min-h-dvh flex-col bg-paper">
<StudyTopBar
title={title}
subtitle={subtitle ?? (state.round > 1 ? `Round ${state.round}: still learning` : 'Browse')}
subtitle={subtitle ?? (state.round > 1 ? `Round ${state.round}: still learning` : state.repeatMissed ? 'Standard · missed cards repeat' : 'Standard')}
onExit={onExit}
exitLabel={exitLabel}
progress={total ? Math.min(1, state.index / total) : 0}
@ -398,7 +390,9 @@ export function CramSession({
</div>
<h2 className="display text-[28px]">{state.unknown.length === 0 ? 'You know them all' : 'Round complete'}</h2>
<p className="mt-2 text-[15px] text-ink-2">
{state.known.length} known{state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of {plural(total, 'card')}.
{state.repeatMissed
? `All ${plural(state.known.length, 'card')} known${state.retried?.length ? `; ${state.retried.length} took more than one try` : ' on the first try'}.`
: `${state.known.length} known${state.unknown.length > 0 ? `, ${state.unknown.length} still learning` : ''} out of ${plural(total, 'card')}.`}
</p>
<div className="mt-6 flex flex-wrap justify-center gap-2">
{state.unknown.length > 0 && (