First revision: DeepSeek, numeric questions, background assistant, UI fixes
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s

Providers and pricing
- Add a DeepSeek provider: thinking mode with low/high/max effort, reasoning_content
  replayed between tool steps, cache-hit usage, /models discovery and catalog prices.
- Fix "does not support tool calling": a rejected forced tool_choice (DeepSeek thinking
  mode) now asks for the call in the prompt; only a genuine no-tools 400 is "unsupported".
- Seven reasoning-effort levels (Off to Max) mapped per adapter.
- Cached-input price per model, cache-write and DeepSeek off-peak aware cost estimates.
- Built-in bge-small embedding model (transformers.js) as the semantic search default.

Quizzes
- Numeric (type-the-answer) questions: units ignored, optional ± tolerance; editor,
  runner, importer, templates and generation prompts.
- Quiz start screen instead of showing answers; navigator ring no longer clipped and
  key legend removed; clock only for timed exams; 7-point letter grades.

Assistant and generation
- Assistant turns run on the server independently of the browser, with re-attach and
  an explicit stop; drafts tray shows generations in progress.
- Per-chat model switcher, @-tagging of class materials, full-width assistant page and
  a smaller assistant button.
- Editable generation instructions and built-in presets, separate from the chatbot
  import instructions.

Other
- Dialog footer padding, keyboard hints removed, copy buttons work over plain HTTP,
  class and folder shares include documents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-15 12:48:17 -07:00
parent ccdad9728b
commit f0aabe4d5d
63 changed files with 3892 additions and 488 deletions

View file

@ -8,9 +8,10 @@ import { api, errorMessage } from '@/lib/api';
import { assistant, useAssistantState } from '@/lib/assistantStore';
import { qk, useClasses, useOverview, useRefresh } from '@/lib/queries';
import type { ClassInfo, SearchHit } from '@/lib/types';
import { cx, modKey, useDebounced, useHotkeys, useIsDesktop, useTheme, type ThemeChoice } from '@/lib/util';
import { cx, useDebounced, useHotkeys, useIsDesktop, useTheme, type ThemeChoice } from '@/lib/util';
import { Brand } from '@/pages/Auth';
import { Button, ClassDot, Dialog, Field, IconButton, Input, Kbd, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea } from '@/ui';
import { Button, ClassDot, Dialog, Field, IconButton, Input, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea, Tooltip } from '@/ui';
import { SidebarDrafts, useDraftNotifications } from '@/features/DraftsTray';
const AssistantPanel = lazy(() => import('@/features/AssistantPanel'));
@ -260,18 +261,6 @@ function CommandPalette({ open, onOpenChange, onNewClass }: { open: boolean; onO
))
)}
</div>
<div className="hidden items-center gap-4 border-t border-line px-5 py-2.5 text-xs text-ink-3 sm:flex">
<span className="flex items-center gap-1.5">
<Kbd>↑</Kbd>
<Kbd>↓</Kbd> to move
</span>
<span className="flex items-center gap-1.5">
<Kbd>Enter</Kbd> to open
</span>
<span className="flex items-center gap-1.5">
<Kbd>Esc</Kbd> to close
</span>
</div>
</div>
</Dialog>
);
@ -350,7 +339,6 @@ function Sidebar({ onSearch, onNewClass }: { onSearch: () => void; onNewClass: (
<button type="button" onClick={onSearch} className="flex h-9 w-full items-center gap-2 rounded-[10px] border border-line-strong bg-surface px-2.5 text-sm text-ink-3 shadow-1 hover:border-ink-3">
<Search className="size-4" aria-hidden />
<span className="flex-1 text-left">Search</span>
<Kbd>{modKey} K</Kbd>
</button>
</div>
<nav aria-label="Main" className="space-y-0.5 px-3">
@ -368,6 +356,8 @@ function Sidebar({ onSearch, onNewClass }: { onSearch: () => void; onNewClass: (
</NavItem>
</nav>
<SidebarDrafts />
<div className="mt-5 flex items-center justify-between px-5 pb-1.5">
<span className="eyebrow">Classes</span>
<IconButton label="New class" size="sm" onClick={onNewClass} className="-mr-2 size-7">
@ -539,6 +529,7 @@ export function Shell() {
const navigate = useNavigate();
const location = useLocation();
const { open: assistantOpen, seed } = useAssistantState();
useDraftNotifications();
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);
@ -581,7 +572,8 @@ export function Shell() {
<Sidebar onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />
<div className="flex min-w-0 flex-1 flex-col">
{!immersive && <MobileNav onSearch={() => setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />}
<main id="main" tabIndex={-1} className={cx('w-full flex-1 outline-none', !immersive && 'mx-auto max-w-[1080px] px-4 pt-6 pb-28 sm:px-8 lg:pt-10 lg:pb-16')}>
{/* The assistant page lays itself out edge to edge; other pages sit in the reading column. */}
<main id="main" tabIndex={-1} className={cx('w-full flex-1 outline-none', !immersive && !onAssistantPage && 'mx-auto max-w-[1080px] px-4 pt-6 pb-28 sm:px-8 lg:pt-10 lg:pb-16')}>
<Outlet />
</main>
</div>
@ -600,15 +592,16 @@ export function Shell() {
</aside>
)}
{!showDrawer && !onAssistantPage && !immersive && isDesktop && (
<button
type="button"
onClick={() => assistant.open()}
className="fixed right-6 bottom-6 z-20 flex h-11 items-center gap-2 rounded-full bg-ink pr-4 pl-3.5 text-sm font-medium text-paper shadow-2 transition-transform hover:-translate-y-0.5"
>
<Sparkles className="size-4 text-marker" />
Assistant
<span className="ml-1 rounded border border-paper/25 px-1 py-px font-mono text-[10px] text-paper/70">{modKey} J</span>
</button>
<Tooltip label="Assistant" side="left">
<button
type="button"
aria-label="Open the assistant"
onClick={() => assistant.open()}
className="fixed right-5 bottom-5 z-20 grid size-10 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-[18px]" />
</button>
</Tooltip>
)}
<CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} onNewClass={() => setClassDialog(true)} />
<ClassDialog open={classDialog} onOpenChange={setClassDialog} />

View file

@ -5,7 +5,7 @@ import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk } from '@/lib/queries';
import { SemanticSettings } from './SemanticSettings';
import type { AdapterMeta, AiModel, AiStatus, Provider, ProviderKind, TaskConfig, TaskName, TaskSettings } from '@/lib/types';
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';
import { Badge, Button, Callout, Dialog, EmptyState, Field, IconButton, Input, Menu, MenuItem, MenuSeparator, Section, Select, Skeleton, Switch, Textarea, Tooltip, useConfirm } from '@/ui';
@ -19,6 +19,7 @@ const KIND_BLURB: Record<ProviderKind, string> = {
openai: 'GPT models with an OpenAI API key.',
anthropic: 'Claude models with an Anthropic API key.',
gemini: 'Gemini models with a Google AI Studio key.',
deepseek: 'DeepSeek Flash and Pro with a DeepSeek platform key.',
openai_compatible: 'OpenRouter, Groq, Together, LM Studio, vLLM and other compatible servers.',
ollama: 'Models running on your own machine or server.',
};
@ -182,6 +183,34 @@ function ProviderDialog({ open, onClose, adapters, existing, onSaved }: { open:
/* ------------------------------ model dialog ------------------------------ */
/** The discount a provider gives on cached input when a model has no cached price of its own (mirrors the server). */
const CACHE_HINT: Record<ProviderKind, string> = {
openai: "OpenAI's discount (90% off for GPT-5 and later)",
anthropic: "Claude's cache-read rate (10% of input)",
gemini: "Gemini's cache rate (10% of input)",
deepseek: "DeepSeek's cache-hit rate",
openai_compatible: 'the normal input price',
ollama: 'the normal input price',
};
function cachedGuess(model: AiModel): string {
const id = model.model.slice(model.model.lastIndexOf('/') + 1);
const ratio =
model.providerKind === 'openai'
? /^gpt-4\.1/.test(id)
? 0.25
: /^(gpt-4o|o\d)/.test(id)
? 0.5
: 0.1
: model.providerKind === 'anthropic' || model.providerKind === 'gemini'
? 0.1
: model.providerKind === 'deepseek'
? 0.02
: 1;
const v = (model.priceIn ?? 0) * ratio;
return `$${v < 0.01 ? v.toFixed(4) : v.toFixed(3)}`;
}
function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClose: () => void; onSaved: () => void }) {
const [label, setLabel] = useState('');
const [caps, setCaps] = useState(model?.capabilities ?? { tools: true, vision: false, pdf: false, reasoning: false, temperature: true });
@ -189,6 +218,7 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
const [maxOut, setMaxOut] = useState('');
const [priceIn, setPriceIn] = useState('');
const [priceOut, setPriceOut] = useState('');
const [priceCached, setPriceCached] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!model) return;
@ -198,13 +228,14 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
setMaxOut(model.maxOutput?.toString() ?? '');
setPriceIn(model.priceIn?.toString() ?? '');
setPriceOut(model.priceOut?.toString() ?? '');
setPriceCached(model.priceCachedIn?.toString() ?? '');
}, [model]);
const num = (s: string) => (s.trim() === '' ? null : Number(s));
const save = async () => {
if (!model) return;
setBusy(true);
try {
await api.patch(`/api/ai/models/${model.id}`, { label, capabilities: caps, contextWindow: num(ctx), maxOutput: num(maxOut), priceIn: num(priceIn), priceOut: num(priceOut) });
await api.patch(`/api/ai/models/${model.id}`, { label, capabilities: caps, contextWindow: num(ctx), maxOutput: num(maxOut), priceIn: num(priceIn), priceOut: num(priceOut), priceCachedIn: num(priceCached) });
onSaved();
onClose();
} catch (e) {
@ -254,6 +285,9 @@ function ModelDialog({ model, onClose, onSaved }: { model: AiModel | null; onClo
<Field label="Output price" hint="USD per million tokens">
<Input type="number" min={0} step="0.01" value={priceOut} onChange={(e) => setPriceOut(e.target.value)} placeholder="Unknown" />
</Field>
<Field label="Cached input price" hint={`USD per million cached (cache-hit) input tokens. Blank uses ${model ? CACHE_HINT[model.providerKind] : 'the provider discount'}.`} className="col-span-2">
<Input type="number" min={0} step="0.001" value={priceCached} onChange={(e) => setPriceCached(e.target.value)} placeholder={model?.priceIn != null ? `About ${cachedGuess(model)}` : 'Unknown'} />
</Field>
</div>
</div>
</Dialog>
@ -495,10 +529,11 @@ function TaskRow({ name, label, description, config, models, resolved, onChange
<Field label="Reasoning effort" hint={model && !model.capabilities.reasoning ? 'Not supported by this model' : undefined}>
<Select value={config.reasoningEffort ?? ''} onChange={(e) => onChange({ ...config, reasoningEffort: (e.target.value || null) as TaskConfig['reasoningEffort'] })}>
<option value="">Model default</option>
<option value="none">Off / minimal</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
{REASONING_EFFORTS.map((e) => (
<option key={e.value} value={e.value}>
{e.label}
</option>
))}
</Select>
</Field>
<Field label="Temperature" hint={model && !model.capabilities.temperature ? 'Ignored by this model' : '0 to 2'}>
@ -536,13 +571,14 @@ function Usage() {
<div className="card px-4 py-5 text-sm text-ink-2">No AI requests in this period.</div>
) : (
<div className="card overflow-hidden">
<div className="grid grid-cols-3 divide-x divide-line border-b border-line">
<div className="grid grid-cols-2 gap-px border-b border-line bg-line sm:grid-cols-4">
{[
['Estimated cost', formatCost(u.total.cost)],
['Requests', u.total.calls.toLocaleString()],
['Tokens in / out', `${formatTokens(u.total.input)} / ${formatTokens(u.total.output)}`],
['Cached input', u.total.input ? `${formatTokens(u.total.cached)} (${Math.round((u.total.cached / u.total.input) * 100)}%)` : '0'],
].map(([k, v]) => (
<div key={k} className="px-4 py-3">
<div key={k} className="bg-surface px-4 py-3">
<div className="eyebrow">{k}</div>
<div className="num mt-1 text-lg font-semibold">{v}</div>
</div>
@ -555,6 +591,7 @@ function Usage() {
<th className="px-4 py-2 font-medium">Model</th>
<th className="px-3 py-2 text-right font-medium">Requests</th>
<th className="px-3 py-2 text-right font-medium">In</th>
<th className="px-3 py-2 text-right font-medium">Cached</th>
<th className="px-3 py-2 text-right font-medium">Out</th>
<th className="px-4 py-2 text-right font-medium">Cost</th>
</tr>
@ -571,6 +608,7 @@ function Usage() {
</td>
<td className="num px-3 py-2 text-right">{m.calls}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.input)}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.cached)}</td>
<td className="num px-3 py-2 text-right">{formatTokens(m.output)}</td>
<td className="num px-4 py-2 text-right">{m.unpriced > 0 && !m.cost ? 'no price set' : formatCost(m.cost)}</td>
</tr>

View file

@ -1,13 +1,13 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowUp, BookOpen, Check, ChevronRight, CircleAlert, FileText, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
import { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, 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 { useAiStatus, useClasses, useRefresh } from '@/lib/queries';
import type { AssistantEvent, ChatMessage, ToolActivity, UiItem } from '@/lib/types';
import { cx, plural, timeAgo } from '@/lib/util';
import { useAiModels, useAiStatus, useClasses, useRefresh } from '@/lib/queries';
import type { AssistantEvent, ChatMessage, Mentionable, 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';
@ -16,6 +16,7 @@ interface Conversation {
title: string;
classId: string | null;
updatedAt: number;
running?: boolean;
}
const ITEM_URL = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents', class: 'classes', attempt: 'session' } as const;
@ -172,6 +173,82 @@ function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMess
);
}
/* ------------------------------ composer: model picker and @ tags ------------------------------ */
const TAG_ICON: Record<TagKind, ReactNode> = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText />, folder: <Folder /> };
const TAG_NOUN: Record<TagKind, string> = { quiz: 'Quiz', deck: 'Flashcards', note: 'Note', document: 'Document', folder: 'Folder' };
function TagChip({ item, onRemove, inverted }: { item: TaggedItem; onRemove?: () => void; inverted?: boolean }) {
return (
<span className={cx('inline-flex h-6 max-w-full items-center gap-1 rounded-full pr-2 pl-1.5 text-xs font-medium [&>svg]:size-3 [&>svg]:shrink-0', inverted ? 'bg-paper/15 text-paper' : 'bg-accent-soft text-accent')}>
{TAG_ICON[item.kind]}
<span className="truncate">{item.title}</span>
{onRemove && (
<button type="button" aria-label={`Remove ${item.title}`} onClick={onRemove} className="-mr-1 grid size-4 place-items-center rounded-full hover:bg-accent/15">
<X className="size-3" />
</button>
)}
</span>
);
}
/** Model chooser for this chat. "Default" follows the Assistant model set in Settings. */
function ModelPicker({ value, onChange, defaultLabel }: { value: string; onChange: (id: string) => void; defaultLabel?: string }) {
const models = useAiModels();
const usable = (models.data ?? []).filter((m) => m.available);
const chosen = usable.find((m) => m.id === value);
const providers = [...new Set(usable.map((m) => m.providerName))];
return (
<Menu
align="start"
trigger={
<button type="button" className="flex max-w-full min-w-0 items-center gap-1 rounded-md text-xs text-ink-3 hover:text-ink" aria-label="Choose the model for this chat">
<span className="truncate">{chosen ? chosen.label : defaultLabel ? `${defaultLabel}` : 'Default model'}</span>
<ChevronDown className="size-3 shrink-0" />
</button>
}
>
<MenuLabel>Model for this chat</MenuLabel>
<MenuItem onSelect={() => onChange('')} hint={!chosen ? <Check className="size-3.5" /> : undefined}>
Default{defaultLabel ? ` · ${defaultLabel}` : ''}
</MenuItem>
{providers.map((p) => (
<div key={p}>
<MenuSeparator />
<MenuLabel>{p}</MenuLabel>
{usable
.filter((m) => m.providerName === p)
.map((m) => (
<MenuItem key={m.id} onSelect={() => onChange(m.id)} hint={m.id === value ? <Check className="size-3.5" /> : !m.capabilities.tools ? 'no tools' : undefined}>
{m.label}
</MenuItem>
))}
</div>
))}
</Menu>
);
}
/** Finds an "@query" being typed just before the caret. */
function mentionAt(text: string, caret: number): { start: number; query: string } | null {
const before = text.slice(0, caret);
const m = /(^|\s)@([^\s@]{0,40})$/.exec(before);
return m ? { start: caret - m[2].length - 1, query: m[2] } : null;
}
function useMentionables(classId: string | null, query: string, enabled: boolean) {
const debounced = useDebounced(query, 150);
// Inside a class: load its materials once and filter here. Elsewhere: search by title.
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),
staleTime: 30_000,
});
const needle = query.toLowerCase();
return (q.data ?? []).filter((i) => !needle || i.title.toLowerCase().includes(needle) || (i.folderName ?? '').toLowerCase().includes(needle)).slice(0, 40);
}
/* ------------------------------ panel ------------------------------ */
export default function AssistantPanel({
@ -186,56 +263,166 @@ export default function AssistantPanel({
onConversationChange?: (id: string | null) => void;
}) {
const ai = useAiStatus();
const models = useAiModels();
const classes = useClasses();
const refresh = useRefresh();
const qc = useQueryClient();
const { seed, context } = useAssistantState();
const [conversationId, setConversationId] = useState<string | null>(routeConversationId ?? null);
const initialConversation = variant === 'page' ? (routeConversationId ?? null) : assistant.drawerConversation;
const [conversationId, setConversationId] = useState<string | null>(initialConversation);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const [busy, setBusy] = useState(false);
const [loadingHistory, setLoadingHistory] = useState(false);
const [focusDocs, setFocusDocs] = useState<string[]>([]);
const abort = useRef<AbortController | null>(null);
const [tags, setTags] = useState<TaggedItem[]>([]);
const [mention, setMention] = useState<{ start: number; query: string } | null>(null);
const [mentionIndex, setMentionIndex] = useState(0);
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);
const stopRequested = useRef(false);
const conversationRef = useRef<string | null>(initialConversation);
const scroller = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const stick = useRef(true);
const handledSeed = useRef(0);
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: Conversation[] }>('/api/ai/conversations').then((r) => r.conversations), staleTime: 30_000 });
const availableModel = (models.data ?? []).find((m) => m.id === modelId && m.available);
const effectiveModelId = availableModel ? modelId : '';
const load = useCallback(async (id: string) => {
setLoadingHistory(true);
try {
const res = await api.get<{ messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
setMessages(res.messages);
const setConversation = useCallback(
(id: string | null) => {
conversationRef.current = id;
setConversationId(id);
stick.current = true;
} catch {
setConversationId(null);
setMessages([]);
} finally {
setLoadingHistory(false);
}
if (variant === 'drawer') assistant.rememberDrawerConversation(id);
},
[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 }));
}, []);
/** Follows a turn (new or already running) until it finishes or this panel detaches. */
const follow = useCallback(
async (pendingId: string, run: (signal: AbortSignal, onEvent: (e: AssistantEvent) => void) => Promise<void>) => {
stream.current?.abort();
const controller = new AbortController();
stream.current = controller;
stopRequested.current = false;
setBusy(true);
let finished = false;
let startedId: string | null = null;
try {
await run(controller.signal, (e) => {
if (e.type === 'start') {
startedId = e.conversationId;
if (stopRequested.current) void api.post(`/api/ai/chat/${e.conversationId}/stop`).catch(() => undefined);
if (e.conversationId !== conversationRef.current) {
setConversation(e.conversationId);
onConversationChange?.(e.conversationId);
}
}
if (e.type === 'done') finished = true;
applyEvent(pendingId, e);
});
} catch (e) {
if ((e as Error)?.name !== 'AbortError') setMessages((list) => list.map((m) => (m.id === pendingId ? { ...m, error: errorMessage(e) } : m)));
} finally {
if (stream.current === controller) {
stream.current = null;
setBusy(false);
}
// Detached (left the conversation): leave the turn running and the message as it is.
if (finished || !controller.signal.aborted) {
setMessages((list) =>
list.map((m) =>
m.id === pendingId
? { ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : stopRequested.current ? '*(Stopped.)*' : m.text) }
: m,
),
);
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
// Tools may have created drafts, classes or sessions.
void refresh();
}
void startedId;
}
},
[applyEvent, onConversationChange, qc, refresh, setConversation],
);
const load = useCallback(
async (id: string) => {
stream.current?.abort();
setLoadingHistory(true);
try {
const res = await api.get<{ conversation: { id: string; running?: boolean }; messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
setConversation(id);
stick.current = true;
if (!res.conversation.running) {
setMessages(res.messages);
setBusy(false);
return;
}
// 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 }]);
setLoadingHistory(false);
void follow(pendingId, (signal, onEvent) => streamEvents<AssistantEvent>(`/api/ai/chat/${id}/stream`, undefined, onEvent, signal));
} catch {
setConversation(null);
setMessages([]);
} finally {
setLoadingHistory(false);
}
},
[follow, setConversation],
);
// Open the remembered or routed conversation on mount.
useEffect(() => {
if (initialConversation) void load(initialConversation);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (routeConversationId && routeConversationId !== conversationId) void load(routeConversationId);
if (!routeConversationId && variant === 'page' && conversationId && !busy) {
setConversationId(null);
if (variant !== 'page') return;
if (routeConversationId && routeConversationId !== conversationRef.current) void load(routeConversationId);
if (!routeConversationId && conversationRef.current && !busy) {
setConversation(null);
setMessages([]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [routeConversationId]);
const newChat = useCallback(() => {
abort.current?.abort();
setConversationId(null);
// Detach only: an answer still being written keeps going and is saved in its conversation.
stream.current?.abort();
setBusy(false);
setConversation(null);
setMessages([]);
setFocusDocs([]);
setTags([]);
onConversationChange?.(null);
setTimeout(() => inputRef.current?.focus(), 30);
}, [onConversationChange]);
}, [onConversationChange, setConversation]);
const stop = useCallback(() => {
stopRequested.current = true;
const id = conversationRef.current;
if (id) void api.post(`/api/ai/chat/${id}/stop`).catch(() => undefined);
}, []);
const activeDocs = focusDocs.length > 0 ? focusDocs : context.documentIds;
const className = classes.data?.find((c) => c.id === context.classId)?.name;
@ -244,47 +431,37 @@ export default function AssistantPanel({
async (text: string, opts: { conversationId?: string | null; documentIds?: string[]; classId?: string | null } = {}) => {
const message = text.trim();
if (!message || busy) return;
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationId;
setBusy(true);
const convo = opts.conversationId !== undefined ? opts.conversationId : conversationRef.current;
const sentTags = tags;
setInput('');
setTags([]);
setMention(null);
stick.current = true;
const pendingId = `p${Date.now()}`;
setMessages((m) => [...m, { id: `u${Date.now()}`, role: 'user', text: message, tools: [], ui: [], createdAt: Date.now() }, { id: pendingId, role: 'assistant', text: '', tools: [], ui: [], createdAt: Date.now(), pending: true }]);
const patch = (fn: (m: ChatMessage) => ChatMessage) => setMessages((list) => list.map((m) => (m.id === pendingId ? fn(m) : m)));
const controller = new AbortController();
abort.current = controller;
let newId: string | null = null;
try {
await streamEvents<AssistantEvent>(
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 },
]);
await follow(pendingId, (signal, onEvent) =>
streamEvents<AssistantEvent>(
'/api/ai/chat',
{ conversationId: convo, message, context: { classId: opts.classId !== undefined ? opts.classId : context.classId, documentIds: opts.documentIds ?? activeDocs } },
(e) => {
if (e.type === 'start') {
newId = e.conversationId;
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 }));
{
conversationId: convo,
message,
modelId: effectiveModelId || undefined,
context: {
classId: opts.classId !== undefined ? opts.classId : context.classId,
documentIds: opts.documentIds ?? activeDocs,
items: sentTags.map((t) => ({ kind: t.kind, id: t.id })),
},
},
controller.signal,
);
} catch (e) {
if ((e as Error)?.name !== 'AbortError') patch((m) => ({ ...m, error: errorMessage(e) }));
} finally {
patch((m) => ({ ...m, pending: false, tools: m.tools.map((t) => (t.status === 'running' ? { ...t, status: 'error', summary: 'Stopped' } : t)), text: m.text || (m.error || m.ui.length || m.tools.length ? m.text : controller.signal.aborted ? '*(Stopped.)*' : m.text) }));
setBusy(false);
if (newId && newId !== convo) {
setConversationId(newId);
onConversationChange?.(newId);
}
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
// Tools may have created drafts, classes or sessions.
void refresh();
}
onEvent,
signal,
),
);
},
[busy, conversationId, context.classId, activeDocs, onConversationChange, qc, refresh],
[busy, tags, follow, effectiveModelId, context.classId, activeDocs],
);
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
@ -293,8 +470,9 @@ export default function AssistantPanel({
handledSeed.current = seed.id;
assistant.consumeSeed();
if (seed.newChat) {
abort.current?.abort();
setConversationId(null);
stream.current?.abort();
setBusy(false);
setConversation(null);
setMessages([]);
onConversationChange?.(null);
}
@ -304,14 +482,15 @@ export default function AssistantPanel({
if (seed.prompt) setInput(seed.prompt);
setTimeout(() => inputRef.current?.focus(), 60);
}
}, [seed, ai.data, send, onConversationChange]);
}, [seed, ai.data, send, onConversationChange, setConversation]);
// Keep the newest content in view unless the user has scrolled up to read.
useEffect(() => {
const el = scroller.current;
if (el && stick.current) el.scrollTop = el.scrollHeight;
}, [messages]);
useEffect(() => () => abort.current?.abort(), []);
// Leaving only disconnects; the server finishes the answer and saves it.
useEffect(() => () => stream.current?.abort(), []);
const updateAction = (actionId: string, status: string, result: string) => {
setMessages((list) => list.map((m) => ({ ...m, ui: m.ui.map((u) => (u.type === 'action' && u.actionId === actionId ? { ...u, status: status as typeof u.status, result } : u)) })));
@ -329,16 +508,54 @@ export default function AssistantPanel({
}, [activeDocs.length, className]);
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : 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));
const updateMention = (text: string, caret: number) => {
const next = mentionAt(text, caret);
setMention(next);
if (!next || next.query !== mention?.query) setMentionIndex(0);
};
const choose = (item: Mentionable) => {
setTags((t) => (t.some((x) => x.kind === item.kind && x.id === item.id) ? t : [...t, { kind: item.kind, id: item.id, title: item.title }]));
if (mention) {
const caret = inputRef.current?.selectionStart ?? input.length;
const next = `${input.slice(0, mention.start)}${input.slice(caret)}`.replace(/\s{2,}/g, ' ');
setInput(next);
setTimeout(() => {
const el = inputRef.current;
if (el) {
el.focus();
el.setSelectionRange(mention.start, mention.start);
}
}, 0);
}
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);
};
return (
<div className="flex min-h-0 flex-1 flex-col">
<header className={cx('flex h-14 shrink-0 items-center gap-2 border-b border-line px-3', variant === 'page' && 'lg:px-0')}>
<span className="grid size-8 place-items-center rounded-[10px] bg-ink text-marker">
<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" />
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold">Assistant</div>
<div className="truncate text-xs text-ink-3">{ai.data?.resolved.chat ? ai.data.resolved.chat.label : ai.data && !ai.data.ready ? 'Not set up' : ''}</div>
{ai.data?.ready ? <ModelPicker value={effectiveModelId} onChange={setModelId} defaultLabel={ai.data.resolved.chat?.label} /> : <div className="truncate text-xs text-ink-3">{ai.data ? 'Not set up' : ''}</div>}
</div>
<IconButton label="New chat" size="sm" onClick={newChat}>
<Plus />
@ -354,7 +571,7 @@ export default function AssistantPanel({
<MenuLabel>Recent conversations</MenuLabel>
{(history.data ?? []).length === 0 && <div className="px-2.5 py-2 text-[13px] text-ink-3">Nothing yet</div>}
{(history.data ?? []).slice(0, 12).map((c) => (
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={timeAgo(c.updatedAt)}>
<MenuItem key={c.id} onSelect={() => load(c.id)} hint={c.running ? 'working…' : timeAgo(c.updatedAt)}>
{c.title}
</MenuItem>
))}
@ -365,7 +582,9 @@ export default function AssistantPanel({
icon={<Trash2 />}
danger
onSelect={async () => {
await api.del(`/api/ai/conversations/${conversationId}`).catch(() => undefined);
const id = conversationId;
stop();
await api.del(`/api/ai/conversations/${id}`).catch(() => undefined);
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
newChat();
}}
@ -385,7 +604,7 @@ export default function AssistantPanel({
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
}}
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-1')}
className={cx('min-h-0 flex-1 overflow-y-auto px-4 py-5', variant === 'page' && 'lg:px-6')}
aria-live="polite"
>
{ai.isLoading || loadingHistory ? (
@ -395,18 +614,18 @@ export default function AssistantPanel({
) : !ai.data?.ready ? (
<div className="mx-auto max-w-sm pt-8">
<Callout tone="accent" icon={<Sparkles />} title="Connect an AI model to use the assistant">
Add a provider such as OpenAI, Anthropic, Google Gemini or a local model, then switch on a model.
Add a provider such as OpenAI, Anthropic, Google Gemini, DeepSeek or a local model, then switch on a model.
<div className="mt-3">
<Button to="/settings/ai" onClick={() => variant === 'drawer' && assistant.close()} size="sm" variant="primary">
Open AI settings
</Button>
Open AI settings
</Button>
</div>
</Callout>
</div>
) : 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.</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. Type @ 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">
@ -421,7 +640,16 @@ export default function AssistantPanel({
{messages.map((m) =>
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">{m.text}</div>
<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">
{m.tags?.length ? (
<div className="mb-1.5 flex flex-wrap gap-1">
{m.tags.map((t) => (
<TagChip key={`${t.kind}:${t.id}`} item={t} inverted />
))}
</div>
) : null}
{m.text}
</div>
</div>
) : (
<AssistantMessage key={m.id} message={m} onNavigate={() => variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} />
@ -432,8 +660,8 @@ export default function AssistantPanel({
</div>
{ai.data?.ready && (
<div className={cx('safe-bottom shrink-0 border-t border-line px-3 pt-2.5 pb-3', variant === 'page' && 'lg:px-0')}>
<div className="mx-auto max-w-2xl">
<div className={cx('safe-pb-3 shrink-0 border-t border-line px-3 pt-2.5', variant === 'page' && 'lg:px-6')}>
<div className="relative mx-auto max-w-2xl">
{contextLabel && (
<div className="mb-2 flex items-center gap-1.5">
<Badge tone="accent" className="max-w-full">
@ -447,41 +675,104 @@ export default function AssistantPanel({
)}
</div>
)}
{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>
{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>
) : (
pickable.map((o, i) => (
<button
key={`${o.kind}:${o.id}`}
type="button"
role="option"
aria-selected={i === mentionIndex}
onMouseDown={(e) => e.preventDefault()}
onMouseMove={() => setMentionIndex(i)}
onClick={() => choose(o)}
className={cx('flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left', i === mentionIndex && 'bg-ink/7')}
>
<span className="grid size-7 shrink-0 place-items-center rounded-md bg-sunken text-ink-2 [&>svg]:size-3.5">{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>
)}
<form
className="flex items-end gap-2 rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20"
className="rounded-[16px] border border-line-strong bg-surface p-1.5 shadow-1 focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20"
onSubmit={(e) => {
e.preventDefault();
if (busy) abort.current?.abort();
if (busy) stop();
else void send(input);
}}
>
<textarea
ref={inputRef}
value={input}
rows={1}
onChange={(e) => {
setInput(e.target.value);
e.target.style.height = 'auto';
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
if (!busy) void send(input);
}
}}
placeholder="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"
/>
<button
type="submit"
disabled={!busy && !input.trim()}
aria-label={busy ? 'Stop' : 'Send'}
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')}
>
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />}
</button>
{tags.length > 0 && (
<div className="flex flex-wrap gap-1 px-1.5 pt-1 pb-1.5">
{tags.map((t) => (
<TagChip key={`${t.kind}:${t.id}`} item={t} onRemove={() => setTags((list) => list.filter((x) => !(x.kind === t.kind && x.id === t.id)))} />
))}
</div>
)}
<div className="flex items-end gap-1.5">
<textarea
ref={inputRef}
value={input}
rows={1}
onChange={(e) => {
setInput(e.target.value);
updateMention(e.target.value, e.target.selectionStart ?? e.target.value.length);
e.target.style.height = 'auto';
e.target.style.height = `${Math.min(e.target.scrollHeight, 180)}px`;
}}
onSelect={(e) => mention && updateMention(e.currentTarget.value, e.currentTarget.selectionStart ?? 0)}
onBlur={() => setTimeout(() => setMention(null), 120)}
onKeyDown={(e) => {
if (mention && pickable.length > 0) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
setMentionIndex((i) => (i + (e.key === 'ArrowDown' ? 1 : -1) + pickable.length) % pickable.length);
return;
}
if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault();
choose(pickable[Math.min(mentionIndex, pickable.length - 1)]);
return;
}
}
if (mention && e.key === 'Escape') {
e.preventDefault();
setMention(null);
return;
}
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
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…'}
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>
<button
type="submit"
disabled={!busy && !input.trim()}
aria-label={busy ? 'Stop' : 'Send'}
className={cx('grid size-9 shrink-0 place-items-center rounded-[11px] transition-colors disabled:opacity-35', busy ? 'bg-sunken text-ink' : 'bg-ink text-paper hover:bg-ink/85')}
>
{busy ? <Square className="size-3.5 fill-current" /> : <ArrowUp className="size-[18px]" />}
</button>
</div>
</form>
<p className="mt-1.5 px-1 text-[11px] text-ink-3">Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.</p>
</div>

View file

@ -0,0 +1,114 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, CircleAlert, Layers, NotebookPen, Sparkles } from 'lucide-react';
import { useEffect, useRef } from 'react';
import { NavLink, useNavigate } from 'react-router';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { DraftSummary } from '@/lib/types';
import { cx, plural, timeAgo } from '@/lib/util';
import { ProgressBar } from '@/ui';
const ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
const NOUN = { quiz: 'quiz', deck: 'flashcards', note: 'study guide' };
/**
* Drafts that still need attention: generations in progress (polled while running), drafts
* ready for review, and recent failures. Generation runs on the server, so leaving the page
* never loses it; this is how you get back to it.
*/
export function useOpenDrafts() {
const q = useQuery({
queryKey: qk.drafts,
queryFn: ({ signal }) => api.get<{ drafts: DraftSummary[] }>('/api/drafts', signal).then((r) => r.drafts),
refetchInterval: (query) => (query.state.data?.some((d) => d.status === 'generating') ? 2000 : 60_000),
});
const dayAgo = Date.now() - 86_400_000;
const drafts = (q.data ?? []).filter((d) => d.status === 'generating' || d.status === 'ready' || (d.status === 'failed' && d.updatedAt > dayAgo));
return { drafts, generating: drafts.filter((d) => d.status === 'generating') };
}
/** Announces generations that finish while you are elsewhere in the app. */
export function useDraftNotifications() {
const { drafts } = useOpenDrafts();
const refresh = useRefresh();
const navigate = useNavigate();
const seen = useRef<Map<string, string>>(new Map());
useEffect(() => {
const prev = seen.current;
for (const d of drafts) {
const before = prev.get(d.id);
if (before === 'generating' && d.status !== 'generating') {
const onPage = window.location.pathname === `/drafts/${d.id}`;
if (!onPage) {
if (d.status === 'ready') toast.success(`${d.title || 'Your draft'} is ready to review`, { action: { label: 'Review', onClick: () => navigate(`/drafts/${d.id}`) } });
else toast.error(`${d.title || 'A draft'} did not finish`);
}
void refresh(qk.drafts);
}
}
seen.current = new Map(drafts.map((d) => [d.id, d.status]));
}, [drafts, refresh, navigate]);
}
function DraftRow({ d, compact }: { d: DraftSummary; compact?: boolean }) {
const status =
d.status === 'generating'
? d.progressLabel || 'Starting'
: d.status === 'failed'
? 'Did not finish'
: d.kind === 'note'
? 'Ready to review'
: `Ready · ${plural(d.itemCount, d.kind === 'quiz' ? 'question' : 'card')}`;
return (
<NavLink
to={`/drafts/${d.id}`}
className={({ isActive }) => cx('block rounded-[9px] px-2.5 py-2 transition-colors', isActive ? 'bg-ink/8' : 'hover:bg-ink/5', !compact && 'border border-line bg-surface shadow-1')}
>
<span className="flex items-center gap-2">
<span className={cx('grid shrink-0 place-items-center [&>svg]:size-3.5', d.status === 'failed' ? 'text-bad' : d.status === 'generating' ? 'text-accent' : 'text-ink-3')}>
{d.status === 'failed' ? <CircleAlert /> : d.status === 'generating' ? <Sparkles className="animate-pulse" /> : ICON[d.kind]}
</span>
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{d.title || `New ${NOUN[d.kind]}`}</span>
{!compact && <span className="shrink-0 text-[11px] text-ink-3">{timeAgo(d.updatedAt)}</span>}
</span>
<span className={cx('mt-0.5 block truncate pl-[22px] text-[11px]', d.status === 'failed' ? 'text-bad' : 'text-ink-3')}>{status}</span>
{d.status === 'generating' && <ProgressBar value={Math.max(0.04, d.progress)} className="mt-1.5 ml-[22px] h-1" label={`Generating ${d.title}`} />}
</NavLink>
);
}
/** Sidebar section: only shown while something is generating or waiting for review. */
export function SidebarDrafts() {
const { drafts } = useOpenDrafts();
if (drafts.length === 0) return null;
return (
<div className="mt-5 px-3">
<div className="mb-1.5 flex items-center justify-between px-2">
<span className="eyebrow">Drafts</span>
{drafts.length > 5 && <span className="text-[11px] text-ink-3">{drafts.length}</span>}
</div>
<div className="max-h-56 space-y-0.5 overflow-y-auto">
{drafts.slice(0, 8).map((d) => (
<DraftRow key={d.id} d={d} compact />
))}
</div>
</div>
);
}
/** The same list for the Today page, where phones see it. */
export function DraftsSection() {
const { drafts } = useOpenDrafts();
if (drafts.length === 0) return null;
return (
<section className="mb-8">
<h2 className="eyebrow mb-3">Drafts</h2>
<div className="grid gap-2 sm:grid-cols-2">
{drafts.slice(0, 6).map((d) => (
<DraftRow key={d.id} d={d} />
))}
</div>
</section>
);
}

View file

@ -86,6 +86,8 @@ function LlmInstructionsDialog({ open, onClose }: { open: boolean; onClose: () =
setCopied(true);
toast.success('Instructions copied');
setTimeout(() => setCopied(false), 2000);
} else {
toast.error('Your browser blocked copying. Select the text and copy it yourself.');
}
}}
>
@ -269,7 +271,7 @@ export function ImportDialog({ open, onClose, classId, folderId }: { open: boole
<Button size="sm" icon={<FileUp />} onClick={() => fileRef.current?.click()}>
Choose file
</Button>
<span>{filename ? filename : 'or drop a .json, .txt or .csv file here. Study Desk V1 exports work too.'}</span>
<span>{filename ? filename : 'or drop a .json, .txt or .csv file here.'}</span>
</div>
</div>

View file

@ -15,8 +15,11 @@ interface EmbeddingStatus {
running: boolean;
lastError: string;
defaults: Record<ProviderKind, string | null>;
local: { model: string; label: string; dimensions: number; downloaded: boolean; status: 'idle' | 'loading' | 'ready' | 'error'; error: string; enabledByDefault: boolean };
}
const LOCAL = 'local';
const KEY = ['ai', 'embeddings'];
/**
@ -33,7 +36,8 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
refetchInterval: (query) => (query.state.data?.running ? 1500 : false),
});
const data = q.data;
const eligible = providers.filter((p) => p.kind !== 'anthropic' && p.enabled);
// Anthropic and DeepSeek have no embeddings API.
const eligible = providers.filter((p) => p.kind !== 'anthropic' && p.kind !== 'deepseek' && p.enabled);
const [providerId, setProviderId] = useState('');
const [model, setModel] = useState('');
const [dimensions, setDimensions] = useState('');
@ -47,9 +51,10 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
}, [data]);
if (!data) return null;
const isLocal = providerId === LOCAL;
const chosen = providers.find((p) => p.id === providerId);
const suggested = chosen ? data.defaults[chosen.kind] : null;
const dirty = providerId !== (data.settings.providerId ?? '') || model.trim() !== data.settings.model || dimensions !== (data.settings.dimensions ? String(data.settings.dimensions) : '');
const suggested = isLocal ? data.local.label : chosen ? data.defaults[chosen.kind] : null;
const dirty = providerId !== (data.settings.providerId ?? '') || (!isLocal && (model.trim() !== data.settings.model || dimensions !== (data.settings.dimensions ? String(data.settings.dimensions) : '')));
const reload = () => qc.invalidateQueries({ queryKey: KEY });
const save = async () => {
@ -59,7 +64,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
}
setBusy('save');
try {
await api.put('/api/ai/embeddings', { providerId: providerId || null, model: providerId ? model.trim() : '', dimensions: dimensions ? Number(dimensions) : null });
await api.put('/api/ai/embeddings', { providerId: providerId || null, model: providerId && !isLocal ? model.trim() : '', dimensions: dimensions && !isLocal ? Number(dimensions) : null });
toast.success(providerId ? 'Semantic search is on. Indexing your documents…' : 'Semantic search is off');
await reload();
} catch (e) {
@ -103,11 +108,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
Finds passages by meaning as well as by words, so "why do patients on Lasix need bananas?" finds the section on furosemide and potassium. Used by search, the assistant and
focused generation. Keyword search keeps working without it.
</p>
{eligible.length === 0 ? (
<Callout tone="accent" icon={<Sparkles />} className="mt-4" title="Needs an embeddings provider">
Connect OpenAI, Gemini, Ollama or an OpenAI-compatible server above. Anthropic does not offer embeddings.
</Callout>
) : (
{(
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
<Field label="Provider">
<Select
@ -115,10 +116,12 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
onChange={(e) => {
const next = providers.find((p) => p.id === e.target.value);
setProviderId(e.target.value);
if (next && (!model || !dirty)) setModel(data.defaults[next.kind] ?? '');
if (e.target.value === LOCAL) setModel(data.local.model);
else if (next && (!model || !dirty || model === data.local.model)) setModel(data.defaults[next.kind] ?? '');
}}
>
<option value="">Off (keywords only)</option>
<option value={LOCAL}>Built-in model (free, runs on this server)</option>
{eligible.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
@ -127,16 +130,29 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
</Select>
</Field>
<Field label="Embedding model" hint={suggested ? `Suggested: ${suggested}` : chosen ? 'The model id your server uses for embeddings' : undefined}>
<Input value={model} onChange={(e) => setModel(e.target.value)} placeholder={suggested || 'text-embedding-3-small'} disabled={!providerId} />
<Input value={isLocal ? data.local.label : model} onChange={(e) => setModel(e.target.value)} placeholder={suggested || 'text-embedding-3-small'} disabled={!providerId || isLocal} />
</Field>
<Field label="Size" hint="Optional">
<Input type="number" min={64} max={4096} step={64} value={dimensions} onChange={(e) => setDimensions(e.target.value)} placeholder="Native" disabled={!providerId} className="sm:w-28" />
<Input type="number" min={64} max={4096} step={64} value={isLocal ? String(data.local.dimensions) : dimensions} onChange={(e) => setDimensions(e.target.value)} placeholder="Native" disabled={!providerId || isLocal} className="sm:w-28" />
</Field>
</div>
)}
{eligible.length > 0 && (
{isLocal && (
<p className="mt-2 text-[13px] text-ink-3">
{data.local.downloaded
? 'The model is on this server. Embeddings are computed on its processor at no cost.'
: 'The model (about 35 MB) is downloaded from Hugging Face the first time it is used, then kept with your data. Embeddings are computed on this server at no cost.'}
{data.local.status === 'loading' ? ' Loading the model now…' : ''}
</p>
)}
{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.
</Callout>
)}
{(
<div className="mt-3 flex flex-wrap gap-2">
<Button variant="primary" size="sm" disabled={!dirty || (Boolean(providerId) && !model.trim())} loading={busy === 'save'} onClick={save}>
<Button variant="primary" size="sm" disabled={!dirty || (Boolean(providerId) && !isLocal && !model.trim())} loading={busy === 'save'} onClick={save}>
Save
</Button>
{data.configured && !dirty && (
@ -174,7 +190,7 @@ export function SemanticSettings({ providers }: { providers: Provider[] }) {
</div>
)}
</div>
<p className="mt-2 text-xs text-ink-3">Embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage. Local Ollama models are free.</p>
<p className="mt-2 text-xs text-ink-3">The built-in model and local Ollama models are free. Cloud embedding costs are small (OpenAI's small model is about $0.02 per million tokens) and appear in Usage.</p>
</Section>
);
}

View file

@ -0,0 +1,338 @@
import { useQuery } from '@tanstack/react-query';
import { BookOpen, Bot, ChevronRight, Layers, MessageSquareText, NotebookPen, Pencil, RotateCcw, Trash2 } from 'lucide-react';
import { useEffect, useState, type ReactNode } from 'react';
import { toast } from 'sonner';
import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { Template } from '@/lib/types';
import { cx, plural } from '@/lib/util';
import { Badge, Button, Dialog, Field, IconButton, Input, Section, Segmented, Select, Skeleton, Textarea, useConfirm } from '@/ui';
/* ------------------------------ shared text editor ------------------------------ */
/** A collapsible row holding one block of instructions, with save and reset. */
function InstructionRow({ label, text, builtin, customized, onSave }: { label: string; text: string; builtin: string; customized: boolean; onSave: (text: string | null) => Promise<void> }) {
const [open, setOpen] = useState(false);
const [value, setValue] = useState(text);
const [busy, setBusy] = useState(false);
useEffect(() => setValue(text), [text]);
const dirty = value.trim() !== text.trim();
const save = async (next: string | null) => {
setBusy(true);
try {
await onSave(next);
toast.success(next === null ? 'Back to the built-in wording' : 'Saved');
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<li>
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="flex w-full items-center gap-2.5 px-4 py-3 text-left hover:bg-ink/4">
<ChevronRight className={cx('size-4 shrink-0 text-ink-3 transition-transform', open && 'rotate-90')} />
<span className="min-w-0 flex-1 truncate text-sm font-medium">{label}</span>
{customized ? <Badge tone="accent">Edited</Badge> : <Badge>Built in</Badge>}
</button>
{open && (
<div className="px-4 pb-4">
<Textarea value={value} onChange={(e) => setValue(e.target.value)} rows={12} spellCheck={false} aria-label={label} className="num text-[12.5px] leading-relaxed" />
<div className="mt-2 flex flex-wrap items-center gap-2">
<Button size="sm" variant="primary" disabled={!dirty || value.trim().length < 10} loading={busy} onClick={() => save(value)}>
Save
</Button>
{dirty && (
<Button size="sm" variant="ghost" onClick={() => setValue(text)}>
Undo changes
</Button>
)}
{(customized || value.trim() !== builtin.trim()) && (
<Button size="sm" variant="ghost" icon={<RotateCcw />} className="ml-auto" disabled={busy} onClick={() => save(null)}>
Reset to built-in
</Button>
)}
</div>
</div>
)}
</li>
);
}
/* ------------------------------ import (outside chatbot) instructions ------------------------------ */
interface LlmInstructions {
quiz: string;
deck: string;
customized: { quiz: boolean; deck: boolean };
builtin?: { quiz: string; deck: string };
}
function ImportInstructions() {
const q = useQuery({ queryKey: ['llm-instructions'], queryFn: () => api.get<LlmInstructions>('/api/llm-instructions') });
if (!q.data) return <Skeleton className="h-28" />;
const save = (kind: 'quiz' | 'deck') => async (text: string | null) => {
await api.put('/api/llm-instructions', { kind, text });
await q.refetch();
};
return (
<Section title="Import instructions (manual generation)">
<ul className="card divide-y divide-line overflow-hidden">
<InstructionRow label="Quiz questions" text={q.data.quiz} builtin={q.data.builtin?.quiz ?? q.data.quiz} customized={q.data.customized.quiz} onSave={save('quiz')} />
<InstructionRow label="Flashcards" text={q.data.deck} builtin={q.data.builtin?.deck ?? q.data.deck} customized={q.data.customized.deck} onSave={save('deck')} />
</ul>
<p className="mt-2 text-xs text-ink-3">
What "AI instructions" in the Import window copies for ChatGPT, Claude or another chatbot you use yourself. They describe the import JSON format, so keep that part intact.
</p>
</Section>
);
}
/* ------------------------------ built-in generator instructions ------------------------------ */
interface GenerationInstruction {
key: string;
group: string;
label: string;
text: string;
builtin: string;
customized: boolean;
}
function GeneratorInstructions() {
const q = useQuery({ queryKey: ['ai', 'instructions'], queryFn: () => api.get<{ instructions: GenerationInstruction[] }>('/api/ai/instructions').then((r) => r.instructions) });
if (!q.data) return <Skeleton className="h-40" />;
const groups = [...new Set(q.data.map((i) => i.group))];
const save = (key: string) => async (text: string | null) => {
await api.put('/api/ai/instructions', { key, text });
await q.refetch();
};
return (
<Section title="AI generation instructions (automatic generation)">
<div className="space-y-3">
{groups.map((g) => (
<div key={g}>
<div className="mb-1.5 text-xs font-medium text-ink-3">{g}</div>
<ul className="card divide-y divide-line overflow-hidden">
{q.data!
.filter((i) => i.group === g)
.map((i) => (
<InstructionRow key={i.key} label={i.label} text={i.text} builtin={i.builtin} customized={i.customized} onSave={save(i.key)} />
))}
</ul>
</div>
))}
</div>
<p className="mt-2 text-xs text-ink-3">
Sent to your connected AI model when you use Generate or ask the assistant to make quizzes, flashcards or study guides. The output format is handled separately, so these only need to
describe what good material looks like.
</p>
</Section>
);
}
/* ------------------------------ generation presets ------------------------------ */
type PresetKind = 'quiz' | 'deck' | 'note';
function PresetDialog({ template, onClose }: { template: Template | null; onClose: () => void }) {
const refresh = useRefresh();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [payload, setPayload] = useState<Record<string, any>>({});
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!template) return;
setName(template.name);
setDescription(template.description);
setPayload({ ...template.payload });
}, [template]);
const set = (patch: Record<string, unknown>) => setPayload((p) => ({ ...p, ...patch }));
const kind: PresetKind = payload.kind ?? 'quiz';
const save = async () => {
if (!template) return;
setBusy(true);
try {
const clean = { ...payload };
if (kind !== 'quiz') ['style', '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;
if (!String(clean.instructions ?? '').trim()) delete clean.instructions;
await api.patch(`/api/templates/${template.id}`, { name, description, payload: clean });
await refresh();
toast.success('Preset saved');
onClose();
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(false);
}
};
return (
<Dialog
open={template !== null}
onOpenChange={(o) => !o && onClose()}
title="Edit preset"
description={template?.builtin ? 'A built-in preset. Your changes are kept, and you can reset it later.' : undefined}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" loading={busy} disabled={!name.trim()} onClick={save}>
Save
</Button>
</>
}
>
<div className="space-y-4">
<Field label="Name">
<Input value={name} onChange={(e) => setName(e.target.value)} maxLength={120} />
</Field>
<Field label="Description" optional>
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={1000} />
</Field>
<Segmented<PresetKind>
label="Creates"
value={kind}
onChange={(k) => set({ kind: k })}
options={[
{ value: 'quiz', label: 'Quiz', icon: <BookOpen /> },
{ value: 'deck', label: 'Flashcards', icon: <Layers /> },
{ value: 'note', label: 'Study guide', icon: <NotebookPen /> },
]}
/>
{kind !== 'note' && (
<Field label={kind === 'quiz' ? 'Questions' : 'Cards'}>
<Input type="number" min={1} max={200} value={payload.count ?? (kind === 'quiz' ? 15 : 30)} onChange={(e) => set({ count: Math.max(1, Math.min(200, Number(e.target.value) || 1)) })} className="w-28" />
</Field>
)}
{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>
</Select>
</Field>
<Field label="Difficulty">
<Select value={payload.difficulty ?? 'mixed'} onChange={(e) => set({ difficulty: e.target.value })}>
<option value="mixed">Mixed</option>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</Select>
</Field>
<Field label={`Select all: ${Math.round((payload.sataShare ?? 0.3) * 100)}%`}>
<input type="range" min={0} max={100} step={5} value={Math.round((payload.sataShare ?? 0.3) * 100)} onChange={(e) => set({ sataShare: Number(e.target.value) / 100 })} className="mt-3 w-full accent-[var(--accent)]" />
</Field>
</div>
)}
{kind === 'deck' && (
<Field label="Card style">
<Select value={payload.cardStyle ?? 'concise'} onChange={(e) => set({ cardStyle: e.target.value })}>
<option value="concise">Concise</option>
<option value="detailed">Detailed</option>
<option value="medication">Medication</option>
<option value="definition">Term and definition</option>
</Select>
</Field>
)}
{kind === 'note' && (
<Field label="Guide style">
<Select value={payload.noteStyle ?? 'study_guide'} onChange={(e) => set({ noteStyle: e.target.value })}>
<option value="study_guide">Study guide</option>
<option value="summary">Summary</option>
<option value="outline">Outline</option>
<option value="cheat_sheet">Cheat sheet</option>
</Select>
</Field>
)}
<Field label="Extra instructions" optional hint="Added to the AI generation instructions whenever this preset is used.">
<Textarea rows={4} value={payload.instructions ?? ''} onChange={(e) => set({ instructions: e.target.value })} />
</Field>
</div>
</Dialog>
);
}
/* ------------------------------ page ------------------------------ */
export function TemplateSettings() {
const refresh = useRefresh();
const confirm = useConfirm();
const [editing, setEditing] = useState<Template | null>(null);
const q = useQuery({ queryKey: qk.templates, queryFn: () => api.get<{ templates: Template[] }>('/api/templates').then((r) => r.templates) });
if (!q.data) return <Skeleton className="h-48" />;
const groups: { kind: Template['kind']; title: string; blurb: string; icon: ReactNode }[] = [
{ kind: 'generation', title: 'AI generation presets', blurb: 'Appear under "Preset" when you generate with AI. Built-in presets can be edited and reset.', icon: <Bot /> },
{ kind: 'quiz', title: 'Quiz templates', blurb: 'Appear under "Start from" when you create a quiz. Save any quiz as a template from its menu.', icon: <BookOpen /> },
{ kind: 'deck', title: 'Flashcard templates', blurb: 'Appear under "Start from" when you create a deck.', icon: <Layers /> },
];
const act = async (fn: () => Promise<unknown>, message: string) => {
try {
await fn();
await refresh();
toast.success(message);
} catch (e) {
toast.error(errorMessage(e));
}
};
return (
<>
<GeneratorInstructions />
<ImportInstructions />
{groups.map((g) => {
const list = q.data!.filter((t) => t.kind === g.kind);
return (
<Section key={g.kind} title={g.title}>
<ul className="card divide-y divide-line">
{list.map((t) => (
<li key={t.id} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{t.name}</span>
{t.edited ? <Badge tone="accent">Edited</Badge> : t.builtin ? <Badge>Built in</Badge> : <Badge tone="accent">Yours</Badge>}
</div>
{t.description && <div className="mt-0.5 line-clamp-2 text-[13px] text-ink-2">{t.description}</div>}
{t.kind !== 'generation' && <div className="mt-0.5 text-xs text-ink-3">{t.kind === 'quiz' ? plural((t.payload.questions ?? []).length, 'question') : plural((t.payload.cards ?? []).length, 'card')}</div>}
</div>
{t.kind === 'generation' && (
<IconButton label="Edit preset" size="sm" onClick={() => setEditing(t)}>
<Pencil />
</IconButton>
)}
{t.edited && (
<IconButton label="Reset to built-in" size="sm" onClick={() => act(() => api.post(`/api/templates/${t.id}/reset`), 'Preset reset')}>
<RotateCcw />
</IconButton>
)}
{!t.builtin && (
<IconButton
label="Delete template"
size="sm"
onClick={async () => {
if (!(await confirm({ title: 'Delete this template?', message: `"${t.name}" will be removed.`, confirmLabel: 'Delete', danger: true }))) return;
await act(() => api.del(`/api/templates/${t.id}`), 'Template deleted');
}}
>
<Trash2 />
</IconButton>
)}
</li>
))}
{list.length === 0 && <li className="px-4 py-4 text-[13px] text-ink-3">None yet.</li>}
</ul>
<p className="mt-2 flex items-center gap-1.5 text-xs text-ink-3">{g.blurb}</p>
</Section>
);
})}
<p className="flex items-center gap-1.5 text-xs text-ink-3">
<MessageSquareText className="size-3.5" /> Changes apply to new generations. Drafts that are already written are not affected.
</p>
<PresetDialog template={editing} onClose={() => setEditing(null)} />
</>
);
}

View file

@ -150,7 +150,7 @@ export function ForecastBars({ values, className }: { values: number[]; classNam
/** Horizontal accuracy bar with the percentage. */
export function AccuracyBar({ value, className }: { value: number; className?: string }) {
const p = Math.round(value * 100);
const tone = p >= 80 ? 'bg-good' : p >= 60 ? 'bg-warn' : 'bg-bad';
const tone = p >= 85 ? 'bg-good' : p >= 77 ? 'bg-warn' : 'bg-bad';
return (
<div className={cx('flex items-center gap-2', className)}>
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-ink/8">

View file

@ -280,8 +280,8 @@ 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. Uploaded documents are not included.',
class: 'Anyone with the link can study every quiz, deck and note in this class. Uploaded documents are not included.',
folder: 'Anyone with the link can study the quizzes, decks and notes in this folder and view 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.',
};
export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id: string; title: string } | null; onClose: () => void }) {
@ -321,6 +321,8 @@ export function ShareDialog({ target, onClose }: { target: { kind: ShareKind; id
setCopied(true);
toast.success('Link copied');
setTimeout(() => setCopied(false), 2000);
} else {
toast.error('Your browser blocked copying. Select the link and copy it yourself.');
}
};
const on = Boolean(share?.enabled);

View file

@ -1,7 +1,7 @@
import { Check, ImagePlus, MessageSquareText, Plus, Trash2 } from 'lucide-react';
import { useRef, useState, type ReactNode } from 'react';
import { toast } from 'sonner';
import { DIFFICULTIES, LIMITS, optionLetter, type DraftCard, type DraftQuestion, type Issue, type QuestionType } from '@shared/content';
import { DIFFICULTIES, LIMITS, optionLetter, parseNumericAnswer, type DraftCard, type DraftQuestion, type Issue, type QuestionType } from '@shared/content';
import { api, errorMessage } from '@/lib/api';
import { cx } from '@/lib/util';
import { IconButton, Input, Segmented, Select, Textarea } from '@/ui';
@ -157,6 +157,19 @@ export function QuestionEditor({
};
const setType = (type: QuestionType) => {
if (type === value.type) return;
if (type === 'numeric') {
// Keep any marked answer that already is a number; otherwise start with one blank answer.
const keep = value.options.filter((o) => o.correct && parseNumericAnswer(o.text) !== null).map((o) => ({ ...o, correct: true }));
set({ type, options: keep.length ? keep : [{ text: '', correct: true, why: value.options.find((o) => o.correct)?.why ?? '' }] });
return;
}
if (value.type === 'numeric') {
const options = value.options.filter((o) => o.text.trim()).map((o, i) => ({ ...o, correct: type === 'multi' || i === 0 }));
while (options.length < 4) options.push({ text: '', correct: false, why: '' });
set({ type, options });
return;
}
if (type === 'single') {
// Keep only the first marked answer so the question stays valid.
let seen = false;
@ -178,9 +191,11 @@ export function QuestionEditor({
label="Question type"
value={value.type}
onChange={setType}
className="max-w-full overflow-x-auto"
options={[
{ value: 'single', label: 'Multiple choice' },
{ value: 'multi', label: 'Select all that apply' },
{ value: 'multi', label: 'Select all' },
{ value: 'numeric', label: 'Numeric answer' },
]}
/>
</div>
@ -190,6 +205,41 @@ export function QuestionEditor({
<MarkdownArea label="Question text" value={value.stem} onChange={(stem) => set({ stem })} placeholder="A client with heart failure reports…" rows={2} serif autoFocus={autoFocus} invalid={has('stem')} />
</div>
{value.type === 'numeric' ? (
<div>
<FieldLabel>Correct answer</FieldLabel>
<ul className="space-y-2">
{value.options.map((o, i) => (
<li key={i} className="flex items-start gap-2">
<Input
value={o.text}
onChange={(e) => setOption(i, { text: e.target.value, correct: true })}
aria-label={i === 0 ? 'Correct answer' : `Also accepted ${i}`}
aria-invalid={Boolean(o.text.trim()) && parseNumericAnswer(o.text) === null}
placeholder={i === 0 ? '12.5 mL' : 'Another accepted answer'}
inputMode="decimal"
className="num max-w-xs"
/>
{value.options.length > 1 && (
<IconButton label="Remove this answer" size="sm" className="mt-1" onClick={() => set({ options: value.options.filter((_, k) => k !== i) })}>
<Trash2 />
</IconButton>
)}
</li>
))}
</ul>
<p className="mt-1.5 text-[13px] text-ink-3">The student types a number. Units are ignored, so "12.5" and "12.5 mL" both count. Add a tolerance with ±, for example "12.5 ± 0.1 mL".</p>
{value.options.length < LIMITS.options && (
<button type="button" onClick={() => set({ options: [...value.options, { text: '', correct: true, why: '' }] })} className="mt-1 inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium text-accent hover:bg-accent-soft">
<Plus className="size-4" /> Accept another answer
</button>
)}
<div className="mt-3">
<FieldLabel>Working</FieldLabel>
<Textarea autoGrow rows={1} value={value.options[0]?.why ?? ''} onChange={(e) => setOption(0, { why: e.target.value })} aria-label="Working" placeholder="How the answer is calculated (optional)" className="bg-sunken text-[13px]" />
</div>
</div>
) : (
<div>
<FieldLabel>{value.type === 'single' ? 'Answer choices · mark the correct one' : 'Answer choices · mark every correct one'}</FieldLabel>
<ul className="space-y-2">
@ -230,6 +280,7 @@ export function QuestionEditor({
</button>
)}
</div>
)}
<div>
<FieldLabel>Rationale</FieldLabel>

View file

@ -2,7 +2,7 @@ import { ArrowLeft, Check, Lightbulb, RotateCcw, Shuffle, SkipForward, X } from
import { useCallback, useEffect, useId, 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, Kbd, ProgressBar } from '@/ui';
import { Button, IconButton, ProgressBar } from '@/ui';
import { Ring } from './charts';
/* ------------------------------ streaks ------------------------------ */
@ -163,7 +163,7 @@ export function FlipCard({
<div className={cx(face, 'flip-front')} inert={flipped ? true : undefined}>
<div className="flex items-center justify-between px-6 pt-5">
<span className="eyebrow">{label ?? 'Question'}</span>
<span className="text-xs text-ink-3">Click or press Space to flip</span>
<span className="text-xs text-ink-3">Tap the card to flip it</span>
</div>
<div className="grid flex-1 place-items-center px-7 py-6 sm:px-12 lg:px-16">
<Markdown serif className={cx('max-h-[52vh] w-full overflow-y-auto', size(front))}>
@ -238,18 +238,6 @@ export function StudyFooter({ children }: { children: ReactNode }) {
);
}
export function KeyHints({ items }: { items: [ReactNode, string][] }) {
return (
<div className="mt-2 hidden flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] text-ink-3 md:flex">
{items.map(([keys, label]) => (
<span key={label} className="flex items-center gap-1">
{keys} {label}
</span>
))}
</div>
);
}
const SWIPE_MS = 230;
/* ------------------------------ browse / cram ------------------------------ */
@ -433,7 +421,7 @@ export function CramSession({
{!done && card && (
<StudyFooter>
<div className="flex items-center gap-2">
<IconButton label="Previous card (Backspace)" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
<IconButton label="Previous card" onClick={() => move(-1)} disabled={state.index === 0 || busy}>
<ArrowLeft />
</IconButton>
{seenAnswer ? (
@ -450,17 +438,10 @@ export function CramSession({
Show answer
</Button>
)}
<IconButton label="Skip card (S)" onClick={() => move(1)} disabled={busy}>
<IconButton label="Skip card" onClick={() => move(1)} disabled={busy}>
<SkipForward />
</IconButton>
</div>
<KeyHints
items={[
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
[<Kbd>←</Kbd>, 'still learning'],
[<Kbd>→</Kbd>, 'know it'],
]}
/>
</StudyFooter>
)}
</div>

View file

@ -1,10 +1,10 @@
import { ArrowLeft, ArrowRight, Check, CircleCheck, CircleX, Clock, Flag, LayoutGrid, RotateCcw, X } from 'lucide-react';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { isFullyCorrect, optionLetter, scoreQuestion, type SataScoring } from '@shared/content';
import { isFullyCorrect, letterGrade, optionLetter, parseNumericAnswer, scoreQuestion, type SataScoring } from '@shared/content';
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, Kbd, ProgressBar, Segmented, useConfirm } from '@/ui';
import { Badge, Button, Dialog, IconButton, Input, ProgressBar, Segmented, useConfirm } from '@/ui';
import { Ring } from './charts';
/* ------------------------------ option list ------------------------------ */
@ -71,6 +71,87 @@ function OptionList({
);
}
/* ------------------------------ numeric answer ------------------------------ */
/** The accepted answer(s) of a numeric question, for display. */
function acceptedAnswers(question: SnapshotQuestion): string {
return question.options
.filter((o) => o.correct !== false)
.map((o) => o.text)
.join(' or ');
}
/** A calculation: the student types the number. Units are optional; only the number is checked. */
function NumericAnswer({
question,
value,
revealed,
onChange,
onSubmit,
autoFocus,
}: {
question: SnapshotQuestion;
value: string;
revealed: boolean;
onChange?: (text: string) => void;
onSubmit?: () => void;
autoFocus?: boolean;
}) {
const right = revealed && isFullyCorrect(scoreQuestion(question, value ? [value] : []));
const unreadable = value.trim() !== '' && parseNumericAnswer(value) === null;
const why = question.options.find((o) => o.why)?.why;
return (
<div className="space-y-2.5">
<label className="block">
<span className="sr-only">Your answer</span>
<Input
value={value}
autoFocus={autoFocus}
inputMode="decimal"
autoComplete="off"
spellCheck={false}
readOnly={revealed || !onChange}
onChange={(e) => onChange?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
e.preventDefault();
onSubmit?.();
}
}}
placeholder="Type your answer, e.g. 12.5"
aria-invalid={unreadable || undefined}
className={cx(
'num h-14 max-w-sm rounded-[14px] px-4 text-[20px]',
revealed && (right ? 'border-good bg-good-soft ring-1 ring-good' : 'border-bad bg-bad-soft ring-1 ring-bad'),
)}
/>
</label>
{!revealed && <p className="text-[13px] text-ink-3">{unreadable ? 'Enter a number. Units are optional.' : 'Only the number is checked, so units are optional.'}</p>}
{revealed && (
<div className="rounded-[14px] border border-good/60 border-dashed px-3.5 py-2.5">
<div className="flex flex-wrap items-baseline gap-x-2 text-[15px]">
<span className="text-[13px] font-medium text-good">Correct answer</span>
<span className="num font-semibold">{acceptedAnswers(question)}</span>
</div>
{why && <div className="mt-1 text-[13.5px] leading-snug text-ink-2">{why}</div>}
</div>
)}
</div>
);
}
/** What the student answered, as text (for the AI explanation). */
function answerTexts(question: SnapshotQuestion, selected: string[]): string[] {
if (question.type === 'numeric') return selected.slice(0, 1);
return question.options.filter((o) => selected.includes(o.id)).map((o) => o.text);
}
/** Tone for a percentage on the 7-point scale: A and B good, C passing, D and F failing. */
export function gradeToneFor(percent: number): 'good' | 'warn' | 'bad' {
const letter = letterGrade(percent);
return letter === 'A' || letter === 'B' ? 'good' : letter === 'C' ? 'warn' : 'bad';
}
/** "2 of 3" style credit for a select-all question, so partial credit is never a mystery. */
function creditDetail(question: SnapshotQuestion, selected: string[], sata: SataScoring): string | null {
if (question.type !== 'multi') return null;
@ -194,12 +275,21 @@ export function QuizRunner(p: RunnerProps) {
topRef.current?.scrollIntoView({ block: 'start' });
}, [index]);
const numeric = question.type === 'numeric';
const toggle = (id: string) => {
if (checked) return;
if (checked || numeric) return;
const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id];
p.onAnswer(question.id, next, false);
};
const check = () => selected.length > 0 && p.onAnswer(question.id, selected, true);
const typed = numeric ? (selected[0] ?? '') : '';
const setTyped = (text: string) => !checked && p.onAnswer(question.id, text.trim() ? [text] : [], false);
const canCheck = numeric ? parseNumericAnswer(typed) !== null : selected.length > 0;
const check = () => {
if (!canCheck) return;
// Let the typed answer show its correct/incorrect colour instead of the focus ring.
if (numeric) (document.activeElement as HTMLElement | null)?.blur();
p.onAnswer(question.id, numeric ? [typed.trim()] : selected, true);
};
const go = (i: number) => p.onIndex(Math.max(0, Math.min(total - 1, i)));
const toggleFlag = () => p.onFlags(flagged ? p.flags.filter((f) => f !== question.id) : [...p.flags, question.id]);
@ -223,8 +313,8 @@ export function QuizRunner(p: RunnerProps) {
};
useHotkeys({
...Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)])),
...Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)])),
...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)]))),
...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)]))),
Enter: primary,
ArrowRight: () => go(index + 1),
ArrowLeft: () => go(index - 1),
@ -253,7 +343,7 @@ export function QuizRunner(p: RunnerProps) {
</div>
{live && (
<div
className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-semibold', live.percent >= 80 ? 'bg-good-soft text-good' : live.percent >= 60 ? 'bg-warn-soft text-warn' : 'bg-bad-soft text-bad')}
className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-semibold', { good: 'bg-good-soft text-good', warn: 'bg-warn-soft text-warn', bad: 'bg-bad-soft text-bad' }[gradeToneFor(live.percent)])}
aria-label={`Score so far: ${fmtPoints(live.points)} of ${live.n} correct, ${live.percent} percent`}
>
<span className="hidden sm:inline">
@ -262,10 +352,13 @@ export function QuizRunner(p: RunnerProps) {
{live.percent}%
</div>
)}
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining !== null && remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label={remaining !== null ? 'Time remaining' : 'Time elapsed'}>
<Clock className="size-3.5" />
{formatDuration(remaining ?? clock)}
</div>
{/* The clock is a timed-exam feature; untimed sessions track time quietly for the results. */}
{remaining !== null && (
<div className={cx('num flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[13px] font-medium', remaining < 60 ? 'bg-bad-soft text-bad' : 'text-ink-2')} aria-label="Time remaining">
<Clock className="size-3.5" />
{formatDuration(remaining)}
</div>
)}
<button type="button" onClick={() => setNavOpen(true)} className="num flex h-9 items-center gap-1.5 rounded-[9px] border border-line-strong bg-surface px-2.5 text-[13px] font-medium shadow-1 hover:border-ink-3" aria-label="Question navigator">
<LayoutGrid className="size-3.5 text-ink-3" />
{index + 1}/{total}
@ -289,8 +382,12 @@ export function QuizRunner(p: RunnerProps) {
<Markdown serif className="text-[20px] leading-[1.45] sm:text-[22px]">
{question.stem}
</Markdown>
<p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : 'Choose one answer.'}</p>
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
<p className="mt-3 mb-4 text-[13px] font-medium text-ink-3">{question.type === 'multi' ? 'Select all that apply.' : numeric ? 'Enter your answer.' : 'Choose one answer.'}</p>
{numeric ? (
<NumericAnswer key={question.id} question={question} value={typed} revealed={checked} onChange={setTyped} onSubmit={primary} />
) : (
<OptionList question={question} selected={selected} revealed={checked} onToggle={toggle} />
)}
{checked && (
<div className="mt-5 animate-in space-y-4">
@ -301,10 +398,7 @@ export function QuizRunner(p: RunnerProps) {
<Markdown className="text-[15px]">{question.rationale}</Markdown>
</div>
)}
{p.renderExtra?.(
question,
question.options.filter((o) => selected.includes(o.id)).map((o) => o.text),
)}
{p.renderExtra?.(question, answerTexts(question, selected))}
</div>
)}
</div>
@ -324,11 +418,8 @@ export function QuizRunner(p: RunnerProps) {
<Button size="lg" variant="ghost" onClick={() => (isLast ? requestFinish() : go(index + 1))}>
{isLast ? 'Finish' : 'Skip'}
</Button>
<Button size="lg" variant="primary" disabled={selected.length === 0} onClick={check} className="min-w-32">
<Button size="lg" variant="primary" disabled={!canCheck} onClick={check} className="min-w-32">
Check
<span className="hidden sm:inline">
<Kbd>↵</Kbd>
</span>
</Button>
</>
) : isLast ? (
@ -361,7 +452,8 @@ export function QuizRunner(p: RunnerProps) {
</Button>
}
>
<div className="grid grid-cols-6 gap-2 sm:grid-cols-8">
{/* Padding keeps the current-question ring (and its offset) inside the scroll area. */}
<div className="grid grid-cols-6 gap-2 p-1.5 sm:grid-cols-8">
{p.questions.map((q, i) => {
const s = statusOf(q);
return (
@ -383,21 +475,6 @@ export function QuizRunner(p: RunnerProps) {
);
})}
</div>
<div className="mt-5 hidden flex-wrap gap-x-4 gap-y-2 text-xs text-ink-3 sm:flex">
<span className="flex items-center gap-1.5">
<Kbd>1</Kbd>–<Kbd>9</Kbd> or <Kbd>A</Kbd>–<Kbd>E</Kbd> choose
</span>
<span className="flex items-center gap-1.5">
<Kbd>Enter</Kbd> check / next
</span>
<span className="flex items-center gap-1.5">
<Kbd>←</Kbd>
<Kbd>→</Kbd> move
</span>
<span className="flex items-center gap-1.5">
<Kbd>M</Kbd> flag
</span>
</div>
</Dialog>
</div>
);
@ -440,7 +517,8 @@ 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 = percent >= 80 ? 'good' : percent >= 60 ? 'warn' : 'bad';
const tone = gradeToneFor(percent);
const grade = letterGrade(percent);
const topics = useMemo(() => {
const map = new Map<string, { n: number; s: number }>();
@ -455,7 +533,7 @@ 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 = percent >= 90 ? 'Excellent work' : percent >= 80 ? 'Strong result' : percent >= 60 ? 'Getting there' : 'Worth another pass';
const headline = { A: 'Excellent work', B: 'Strong result', C: 'Passing', D: 'Just below passing', F: 'Worth another pass' }[grade];
return (
<div className="min-h-dvh bg-paper">
@ -471,13 +549,13 @@ export function QuizResults(p: ResultsProps) {
<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="leading-none">
<span className="display num text-[38px] font-medium">{percent}</span>
<span className="text-lg text-ink-3">%</span>
<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>
<div className="min-w-0 flex-1">
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'}</div>
<div className="eyebrow mb-1">{p.mode === 'exam' ? 'Exam result' : 'Practice result'} · grade {grade}</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
@ -506,7 +584,7 @@ export function QuizResults(p: ResultsProps) {
<span className="min-w-0 flex-1 truncate text-sm font-medium">{t.topic}</span>
<span className="text-xs text-ink-3">{plural(t.n, 'question')}</span>
<div className="h-1.5 w-24 overflow-hidden rounded-full bg-ink/8 sm:w-36">
<div className={cx('h-full rounded-full', pc >= 80 ? 'bg-good' : pc >= 60 ? 'bg-warn' : 'bg-bad')} style={{ width: `${Math.max(4, pc)}%` }} />
<div className={cx('h-full rounded-full', { good: 'bg-good', warn: 'bg-warn', bad: 'bg-bad' }[gradeToneFor(pc)])} style={{ width: `${Math.max(4, pc)}%` }} />
</div>
<span className="num w-10 text-right text-[13px] font-medium">{pc}%</span>
</div>
@ -550,7 +628,7 @@ export function QuizResults(p: ResultsProps) {
<Markdown serif className="mb-3.5 text-[17px]">
{r.q.stem}
</Markdown>
<OptionList question={r.q} selected={r.selected} revealed />
{r.q.type === 'numeric' ? <NumericAnswer question={r.q} value={r.selected[0] ?? ''} revealed /> : <OptionList question={r.q} selected={r.selected} revealed />}
{r.scored && !r.correct && r.answered && creditDetail(r.q, r.selected, p.sataScoring) && <p className="mt-2.5 text-[13px] text-ink-2">{creditDetail(r.q, r.selected, p.sataScoring)}</p>}
{r.q.rationale && (
<div className="mt-3.5 rounded-xl bg-sunken px-4 py-3">
@ -560,10 +638,7 @@ export function QuizResults(p: ResultsProps) {
)}
{p.renderExtra && (
<div className="mt-3">
{p.renderExtra(
r.q,
r.q.options.filter((o) => r.selected.includes(o.id)).map((o) => o.text),
)}
{p.renderExtra(r.q, answerTexts(r.q, r.selected))}
</div>
)}
</li>

View file

@ -105,13 +105,13 @@ export function uploadWithProgress<T>(url: string, form: FormData, onProgress: (
});
}
/** POSTs JSON and reads a server-sent event stream of JSON objects. */
/** POSTs JSON (or GETs, when `body` is undefined) and reads a server-sent event stream of JSON objects. */
export async function streamEvents<T extends { type: string }>(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise<void> {
const res = await fetch(url, {
method: 'POST',
method: body === undefined ? 'GET' : 'POST',
credentials: 'same-origin',
headers: { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
body: JSON.stringify(body),
headers: body === undefined ? { ...BASE_HEADERS, Accept: 'text/event-stream' } : { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
body: body === undefined ? undefined : JSON.stringify(body),
signal,
});
if (!res.ok || !res.body) {

View file

@ -23,6 +23,8 @@ const set = (patch: Partial<State>) => {
listeners.forEach((fn) => fn());
};
let seedId = 0;
/** The drawer's conversation, kept while the drawer is closed so reopening continues it. */
let drawerConversation: string | null = null;
export const assistant = {
/** Opens the assistant, optionally with a prepared prompt. */
@ -39,6 +41,12 @@ export const assistant = {
consumeSeed() {
if (state.seed) set({ seed: null });
},
get drawerConversation() {
return drawerConversation;
},
rememberDrawerConversation(id: string | null) {
drawerConversation = id;
},
setContext(context: State['context']) {
const cur = state.context;
if (cur.classId === context.classId && cur.label === context.label && cur.documentIds.join() === context.documentIds.join()) return;

View file

@ -339,7 +339,7 @@ export interface ShareListItem extends Share {
/* ------------------------------ AI ------------------------------ */
export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'openai_compatible' | 'ollama';
export type ProviderKind = 'openai' | 'anthropic' | 'gemini' | 'deepseek' | 'openai_compatible' | 'ollama';
export interface AdapterMeta {
kind: ProviderKind;
label: string;
@ -386,12 +386,26 @@ export interface AiModel {
maxOutput: number | null;
priceIn: number | null;
priceOut: number | null;
/** USD per million cached input tokens; null = the provider's usual cache discount. */
priceCachedIn: number | null;
}
export type TaskName = 'chat' | 'generate' | 'vision' | 'quick';
/** Reasoning effort levels, lowest to highest. Each provider maps them onto what it accepts. */
export const REASONING_EFFORTS = [
{ value: 'none', label: 'Off' },
{ value: 'minimal', label: 'Minimal' },
{ value: 'low', label: 'Low' },
{ value: 'medium', label: 'Medium' },
{ value: 'high', label: 'High' },
{ value: 'xhigh', label: 'Extra high' },
{ value: 'max', label: 'Max' },
] as const;
export type ReasoningEffort = (typeof REASONING_EFFORTS)[number]['value'];
export interface TaskConfig {
modelId: string | null;
temperature: number | null;
reasoningEffort: 'none' | 'low' | 'medium' | 'high' | null;
reasoningEffort: ReasoningEffort | null;
maxOutputTokens: number | null;
}
export type TaskSettings = Record<TaskName | 'default', TaskConfig>;
@ -444,10 +458,22 @@ export interface ToolActivity {
status: 'running' | 'done' | 'error';
summary?: string;
}
export type TagKind = 'quiz' | 'deck' | 'note' | 'document' | 'folder';
export interface TaggedItem {
kind: TagKind;
id: string;
title: string;
}
export interface Mentionable extends TaggedItem {
className: string;
classColor: string;
folderName?: string;
}
export interface ChatMessage {
id: number | string;
role: 'user' | 'assistant';
text: string;
tags?: TaggedItem[];
tools: ToolActivity[];
ui: UiItem[];
model?: string;
@ -472,6 +498,8 @@ export interface Template {
description: string;
payload: Record<string, any>;
builtin: boolean;
/** A built-in template the user has changed. */
edited?: boolean;
updatedAt: number;
}
@ -514,6 +542,6 @@ export interface PublicCollection {
description?: string;
color: ClassColor;
folders: { id: string; name: string }[];
items: { kind: 'quiz' | 'deck' | 'note'; id: string; title: string; description: string; folderId: string | null; count: number }[];
items: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string; title: string; description: string; folderId: string | null; count: number }[];
}
export type PublicPayload = PublicQuiz | PublicDeck | PublicNote | PublicDocument | PublicCollection;

View file

@ -72,10 +72,12 @@ export function formatCost(n: number | null | undefined): string {
return `$${n.toFixed(2)}`;
}
/** Tone on the 7-point scale: A/B (85+) good, C (77-84) passing, D/F failing. */
export function gradeTone(percent: number | null): 'good' | 'warn' | 'bad' | 'none' {
if (percent === null) return 'none';
if (percent >= 80) return 'good';
if (percent >= 60) return 'warn';
const p = Math.round(percent);
if (p >= 85) return 'good';
if (p >= 77) return 'warn';
return 'bad';
}
@ -100,25 +102,43 @@ export function downloadText(filename: string, text: string, mime = 'application
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/**
* Copies text to the clipboard. The async Clipboard API only exists on secure origins
* (HTTPS or localhost), so a self-hosted server opened over plain HTTP falls back to a hidden
* textarea and `execCommand('copy')`. That textarea is placed inside the open dialog, if any:
* dialogs trap focus, and a textarea outside the trap cannot be focused or selected, which
* made every copy button inside a dialog silently fail.
*/
export async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
if (navigator.clipboard?.writeText && window.isSecureContext) {
try {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
return ok;
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
/* permission denied or document not focused: try the fallback */
}
}
const previous = document.activeElement as HTMLElement | null;
const host = (previous?.closest('[role="dialog"], [role="alertdialog"]') as HTMLElement | null) ?? document.querySelector<HTMLElement>('[role="dialog"][data-state="open"]') ?? document.body;
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.setAttribute('aria-hidden', 'true');
Object.assign(ta.style, { position: 'fixed', top: '0', left: '0', width: '1px', height: '1px', padding: '0', border: '0', opacity: '0', pointerEvents: 'none' });
host.appendChild(ta);
let ok = false;
try {
ta.focus({ preventScroll: true });
ta.select();
ta.setSelectionRange(0, text.length);
ok = document.execCommand('copy');
} catch {
ok = false;
} finally {
ta.remove();
previous?.focus?.({ preventScroll: true });
}
return ok;
}
export function shuffle<T>(items: readonly T[]): T[] {

View file

@ -1,5 +1,5 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { MessageSquare, Trash2 } from 'lucide-react';
import { MessageSquare, Plus, Trash2 } from 'lucide-react';
import { useNavigate, useParams } from 'react-router';
import AssistantPanel from '@/features/AssistantPanel';
import { api } from '@/lib/api';
@ -12,7 +12,12 @@ export default function AssistantPage() {
const navigate = useNavigate();
const qc = useQueryClient();
const confirm = useConfirm();
const history = useQuery({ queryKey: ['ai', 'conversations'], queryFn: () => api.get<{ conversations: { id: string; title: string; updatedAt: number }[] }>('/api/ai/conversations').then((r) => r.conversations) });
const history = useQuery({
queryKey: ['ai', 'conversations'],
queryFn: () => api.get<{ conversations: { id: string; title: string; updatedAt: number; running?: boolean }[] }>('/api/ai/conversations').then((r) => r.conversations),
// Keep "Working…" labels current while an answer is being written in the background.
refetchInterval: (q) => (q.state.data?.some((c) => c.running) ? 3000 : false),
});
const remove = async (id: string) => {
if (!(await confirm({ title: 'Delete this conversation?', confirmLabel: 'Delete', danger: true, message: 'The messages are removed. Drafts and anything you saved are kept.' }))) return;
@ -22,9 +27,14 @@ export default function AssistantPage() {
};
return (
<div className="-mx-4 -mt-6 -mb-28 flex h-[calc(100dvh-52px-56px)] sm:-mx-8 lg:mx-0 lg:-mt-10 lg:-mb-16 lg:h-dvh lg:gap-6">
<aside className="hidden w-60 shrink-0 flex-col border-r border-line py-6 pr-3 lg:flex">
<div className="eyebrow mb-2 px-2">Conversations</div>
<div className="flex h-[calc(100dvh-52px-56px)] lg:h-dvh">
<aside className="hidden w-64 shrink-0 flex-col border-r border-line bg-paper px-3 py-5 lg:flex">
<div className="mb-2 flex items-center justify-between px-2">
<span className="eyebrow">Conversations</span>
<IconButton label="New chat" size="sm" className="-mr-1.5 size-7" onClick={() => navigate('/assistant')}>
<Plus />
</IconButton>
</div>
<div className="min-h-0 flex-1 space-y-0.5 overflow-y-auto">
{(history.data ?? []).length === 0 && <p className="px-2 text-[13px] text-ink-3">Your conversations will be listed here.</p>}
{(history.data ?? []).map((c) => (
@ -34,7 +44,7 @@ export default function AssistantPage() {
<MessageSquare className="size-3.5 shrink-0 text-ink-3" />
<span className="truncate text-sm">{c.title}</span>
</span>
<span className="pl-[22px] text-[11px] text-ink-3">{timeAgo(c.updatedAt)}</span>
<span className="pl-[22px] text-[11px] text-ink-3">{c.running ? 'Working…' : timeAgo(c.updatedAt)}</span>
</button>
<IconButton label="Delete conversation" size="sm" className="mr-1 opacity-0 group-hover:opacity-100 focus-visible:opacity-100" onClick={() => remove(c.id)}>
<Trash2 />
@ -43,7 +53,7 @@ export default function AssistantPage() {
))}
</div>
</aside>
<div className="flex min-w-0 flex-1 flex-col">
<div className="flex min-w-0 flex-1 flex-col bg-surface/40">
<AssistantPanel variant="page" conversationId={conversationId} onConversationChange={(id) => navigate(id ? `/assistant/${id}` : '/assistant', { replace: true })} />
</div>
</div>

View file

@ -43,6 +43,7 @@ import type { DeckItem, DocumentItem, Folder, Item, NoteItem, QuizItem } from '@
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 { letterGrade } from '@shared/content';
type Filter = 'all' | 'quiz' | 'deck' | 'document' | 'note';
@ -70,7 +71,7 @@ function itemMeta(item: Item): ReactNode {
<>
<span>{plural(q.questionCount, 'question')}</span>
{q.lastPercent !== null && (
<span className={cx('num font-medium', { good: 'text-good', warn: 'text-warn', bad: 'text-bad', none: '' }[gradeTone(q.lastPercent)])}>Last {q.lastPercent}%</span>
<span className={cx('num font-medium', { good: 'text-good', warn: 'text-warn', bad: 'text-bad', none: '' }[gradeTone(q.lastPercent)])}>Last {letterGrade(q.lastPercent ?? 0)} · {q.lastPercent}%</span>
)}
{q.lastStudiedAt && <span>{timeAgo(q.lastStudiedAt)}</span>}
</>

View file

@ -343,7 +343,6 @@ export default function DeckPage() {
</div>
<CardEditor value={fresh} onChange={setFresh} onSubmit={addCard} />
<div className="mt-4 flex items-center justify-end gap-3">
<span className="hidden text-xs text-ink-3 sm:block">Ctrl+Enter adds the card and starts the next one</span>
<Button variant="primary" icon={<Plus />} loading={adding} disabled={!fresh.front.trim() || !fresh.back.trim()} onClick={addCard}>
Add card
</Button>

View file

@ -149,7 +149,7 @@ export default function DraftPage() {
</p>
<ProgressBar value={Math.max(0.04, draft.progress)} className="mx-auto mt-6 h-2 max-w-sm" label="Generation progress" />
{draft.kind !== 'note' && partial > 0 && <p className="mt-3 text-sm text-ink-3">{plural(partial, draft.kind === 'quiz' ? 'question' : 'card')} so far</p>}
<p className="mt-6 text-[13px] text-ink-3">You can leave this page. The draft keeps generating and will be waiting here.</p>
<p className="mt-6 text-[13px] text-ink-3">You can leave this page. Generation continues on the server; follow it under Drafts in the sidebar (or on Today) and come back when it is ready.</p>
<Button
variant="ghost"
className="mt-4"

View file

@ -9,6 +9,8 @@ import { useAiStatus, useClasses, useOverview } from '@/lib/queries';
import type { AttemptSummary } from '@/lib/types';
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
import { Badge, Button, ClassDot, ErrorState, ProgressBar, Section, Skeleton } from '@/ui';
import { DraftsSection } from '@/features/DraftsTray';
import { letterGrade } from '@shared/content';
function greeting(): string {
const h = new Date().getHours();
@ -186,6 +188,8 @@ export default function Home() {
</div>
</div>
<DraftsSection />
{o.activeAttempts.length > 0 && (
<Section title="Pick up where you left off">
<div className="card divide-y divide-line overflow-hidden">
@ -247,7 +251,7 @@ export default function Home() {
const tone = gradeTone(p);
return (
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className={cx('num grid h-9 w-12 shrink-0 place-items-center rounded-[10px] text-sm font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
<span className={cx('num grid h-9 min-w-12 shrink-0 place-items-center rounded-[10px] px-1.5 text-[13px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${letterGrade(p)} ${p}%`}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{a.title}</span>
<span className="text-xs text-ink-3">

View file

@ -10,6 +10,7 @@ import { useAiStatus, useClasses } from '@/lib/queries';
import type { Insights } from '@/lib/types';
import { cx, gradeTone, pct, plural, timeAgo, useDocumentTitle } from '@/lib/util';
import { Button, ClassDot, EmptyState, ErrorState, PageHeader, Section, Segmented, Select, Skeleton } from '@/ui';
import { letterGrade } from '@shared/content';
function Stat({ label, value, sub, tone }: { label: string; value: string; sub?: string; tone?: 'good' | 'warn' | 'bad' | 'none' }) {
return (
@ -184,7 +185,7 @@ export default function InsightsPage() {
const tone = gradeTone(p);
return (
<Link key={a.id} to={`/session/${a.id}`} className="flex items-center gap-3 px-4 py-2.5 hover:bg-ink/4">
<span className={cx('num grid h-8 w-12 shrink-0 place-items-center rounded-[9px] text-[13px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
<span className={cx('num grid h-8 min-w-12 shrink-0 place-items-center rounded-[9px] px-1.5 text-[12.5px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${letterGrade(p)} ${p}%`}</span>
<span className="min-w-0 flex-1 truncate text-sm font-medium">{a.title}</span>
<span className="shrink-0 text-xs text-ink-3">
{a.mode === 'exam' ? 'Exam · ' : ''}

View file

@ -2,7 +2,7 @@ import { ArrowDown, ArrowUp, BookOpen, Check, ChevronRight, ClipboardList, Copy,
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { blankQuestion, optionLetter, QUESTION_TYPE_LABEL, questionToDraft, validateDraftQuestion, type DraftCard, type DraftQuestion, type Question } from '@shared/content';
import { blankQuestion, letterGrade, optionLetter, QUESTION_TYPE_LABEL, questionToDraft, validateDraftQuestion, type DraftCard, type DraftQuestion, type Question } from '@shared/content';
import { parseImport } from '@shared/importer';
import { MoveDialog, RenameDialog, ShareDialog } from '@/features/dialogs';
import { QuestionEditor } from '@/features/editors';
@ -22,19 +22,20 @@ interface StartPrefs {
shuffleOptions: boolean;
}
export function StartSessionDialog({ open, onClose, quizId, total, title }: { open: boolean; onClose: () => void; quizId: string; total: number; title: string }) {
/** Session options (mode, length, shuffling, exam time limit), shared by the start screen and the start dialog. */
function useStartOptions(quizId: string, total: number, active: boolean) {
const { start, starting } = useStartSession();
const [prefs, setPrefs] = useLocalStorage<StartPrefs>('sd.startPrefs', { mode: 'practice', shuffleQuestions: true, shuffleOptions: true });
const [count, setCount] = useState(total);
const [timed, setTimed] = useState(false);
const [minutes, setMinutes] = useState(30);
useEffect(() => {
if (open) {
if (active) {
setCount(total);
setMinutes(Math.max(5, Math.round(total * 1.2)));
setTimed(false);
}
}, [open, total]);
}, [active, total]);
const go = () =>
start({
mode: prefs.mode,
@ -42,25 +43,15 @@ export function StartSessionDialog({ open, onClose, quizId, total, title }: { op
shuffleQuestions: prefs.shuffleQuestions,
shuffleOptions: prefs.shuffleOptions,
count: count < total ? count : undefined,
// A time limit is an exam option only; practice sessions are never timed.
timeLimitMin: prefs.mode === 'exam' && timed ? minutes : null,
});
return { prefs, setPrefs, count, setCount, timed, setTimed, minutes, setMinutes, go, starting, total };
}
function StartOptionsFields({ o }: { o: ReturnType<typeof useStartOptions> }) {
const { prefs, setPrefs, count, setCount, timed, setTimed, minutes, setMinutes, total } = o;
return (
<Dialog
open={open}
onOpenChange={(o) => !o && onClose()}
title="Start a session"
description={title}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" icon={<Play className="fill-current" />} loading={starting} onClick={go}>
Start
</Button>
</>
}
>
<div className="space-y-5">
<div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label="Mode">
{(
@ -102,10 +93,75 @@ export function StartSessionDialog({ open, onClose, quizId, total, title }: { op
)}
</div>
</div>
);
}
export function StartSessionDialog({ open, onClose, quizId, total, title }: { open: boolean; onClose: () => void; quizId: string; total: number; title: string }) {
const o = useStartOptions(quizId, total, open);
return (
<Dialog
open={open}
onOpenChange={(v) => !v && onClose()}
title="Start a session"
description={title}
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button variant="primary" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go}>
Start
</Button>
</>
}
>
<StartOptionsFields o={o} />
</Dialog>
);
}
/** The quiz start screen: how to take it, without showing any questions or answers. */
function StartPanel({ quizId, total, resume, onShowQuestions }: { quizId: string; total: number; resume: { id: string; answeredCount: number; questionCount: number } | null; onShowQuestions: () => void }) {
const o = useStartOptions(quizId, total, true);
if (total === 0) {
return (
<div className="card border-dashed">
<EmptyState icon={<BookOpen />} title="No questions yet" action={<Button variant="primary" icon={<Plus />} onClick={onShowQuestions}>Add questions</Button>}>
Add questions to this quiz before taking it.
</EmptyState>
</div>
);
}
return (
<section className="card p-5 sm:p-6">
{resume && (
<Callout
tone="warn"
icon={<Play />}
className="mb-5"
title="You have a session in progress"
action={
<Button to={`/session/${resume.id}`} variant="marker" size="sm">
Resume ({resume.answeredCount}/{resume.questionCount})
</Button>
}
>
Pick up where you left off, or start a new session below.
</Callout>
)}
<StartOptionsFields o={o} />
<div className="mt-6 flex flex-wrap items-center gap-2 border-t border-line pt-5">
<Button variant="primary" size="lg" icon={<Play className="fill-current" />} loading={o.starting} onClick={o.go} className="min-w-40">
{resume ? 'Start new session' : 'Start'}
</Button>
<Button variant="ghost" size="lg" icon={<ClipboardList />} onClick={onShowQuestions} className="ml-auto">
View questions and answers
</Button>
</div>
</section>
);
}
/** Paste several questions (or cards) as text or JSON and add them to an existing item. */
export function BulkAddDialog({ open, onClose, kind, onAdd }: { open: boolean; onClose: () => void; kind: 'quiz' | 'deck'; onAdd: (items: unknown[]) => Promise<void> }) {
const [text, setText] = useState('');
@ -230,7 +286,8 @@ export default function QuizPage() {
useAssistantContext(data?.quiz.classId, data?.quiz.title);
const { start, starting } = useStartSession();
const [tab, setTab] = useState<'questions' | 'history'>('questions');
// The start screen comes first, so opening a quiz never reveals its answers.
const [tab, setTab] = useState<'start' | 'questions' | 'history'>(() => (params.get('q') || params.get('edit') ? 'questions' : 'start'));
const [editing, setEditing] = useState<string | 'new' | null>(null);
const [draft, setDraft] = useState<DraftQuestion>(blankQuestion());
const [saving, setSaving] = useState(false);
@ -252,8 +309,10 @@ export default function QuizPage() {
if (params.get('edit')) {
setDraft(blankQuestion());
setEditing('new');
setTab('questions');
}
const target = params.get('q');
if (target) setTab('questions');
if (target) setTimeout(() => document.getElementById(`q-${target}`)?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 120);
if (params.get('start') || params.get('edit')) {
next.delete('start');
@ -299,6 +358,7 @@ export default function QuizPage() {
setEditing(question.id);
};
const beginNew = () => {
setTab('questions');
setDraft({ ...blankQuestion(), topic: questions[questions.length - 1]?.topic ?? '' });
setEditing('new');
setTimeout(() => newRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' }), 60);
@ -358,7 +418,7 @@ export default function QuizPage() {
const editorFooter = (isNew: boolean) => (
<div className="mt-5 flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4">
<span className="mr-auto hidden text-xs text-ink-3 sm:block">Ctrl+Enter to save</span>
<span className="mr-auto" />
<Button variant="ghost" onClick={() => setEditing(null)}>
Cancel
</Button>
@ -393,10 +453,16 @@ export default function QuizPage() {
{full.length > 0 && (
<>
<span>
Last <strong className="num text-ink">{last}%</strong>
Last{' '}
<strong className="num text-ink">
{last !== null ? `${letterGrade(last)} · ${last}%` : '—'}
</strong>
</span>
<span>
Best <strong className="num text-ink">{best}%</strong>
Best{' '}
<strong className="num text-ink">
{best !== null ? `${letterGrade(best)} · ${best}%` : '—'}
</strong>
</span>
<span>{plural(history.length, 'attempt')}</span>
</>
@ -414,9 +480,11 @@ export default function QuizPage() {
Resume ({data.activeAttempt.answeredCount}/{data.activeAttempt.questionCount})
</Button>
) : null}
<Button variant={data.activeAttempt ? 'secondary' : 'primary'} size="lg" icon={<Play className="fill-current" />} disabled={questions.length === 0} onClick={() => setStartOpen(true)}>
{data.activeAttempt ? 'Start new' : 'Start'}
</Button>
{tab !== 'start' && (
<Button variant={data.activeAttempt ? 'secondary' : 'primary'} size="lg" icon={<Play className="fill-current" />} disabled={questions.length === 0} onClick={() => setStartOpen(true)}>
{data.activeAttempt ? 'Start new' : 'Start'}
</Button>
)}
<Menu
trigger={
<IconButton label="Quiz options" tooltip={false}>
@ -488,6 +556,7 @@ export default function QuizPage() {
onChange={setTab}
label="View"
options={[
{ value: 'start', label: 'Start', icon: <Play /> },
{ value: 'questions', label: `Questions`, icon: <ClipboardList /> },
{ value: 'history', label: `History${history.length ? ` (${history.length})` : ''}`, icon: <History /> },
]}
@ -509,7 +578,14 @@ export default function QuizPage() {
)}
</div>
{tab === 'questions' ? (
{tab === 'start' ? (
<StartPanel
quizId={quiz.id}
total={questions.length}
resume={data.activeAttempt ? { id: data.activeAttempt.id, answeredCount: data.activeAttempt.answeredCount, questionCount: data.activeAttempt.questionCount } : null}
onShowQuestions={() => (questions.length === 0 ? beginNew() : setTab('questions'))}
/>
) : tab === 'questions' ? (
<>
{questions.length === 0 && editing !== 'new' ? (
<div className="card border-dashed">
@ -634,7 +710,7 @@ export default function QuizPage() {
<>
{full.length >= 2 && (
<Callout className="mb-3" tone={last !== null && best !== null && last >= best ? 'good' : 'neutral'}>
{last !== null && best !== null && last >= best ? `Your latest attempt (${last}%) is your best so far.` : `Latest ${last}%, best ${best}% across ${plural(full.length, 'full attempt')}.`}
{last !== null && best !== null && last >= best ? `Your latest attempt (${letterGrade(last)}, ${last}%) is your best so far.` : `Latest ${last !== null ? `${letterGrade(last)} (${last}%)` : '—'}, best ${best !== null ? `${letterGrade(best)} (${best}%)` : '—'} across ${plural(full.length, 'full attempt')}.`}
</Callout>
)}
<ul className="card divide-y divide-line">
@ -644,7 +720,16 @@ export default function QuizPage() {
return (
<li key={h.id}>
<Link to={`/session/${h.id}`} className="flex items-center gap-3 px-4 py-3 hover:bg-ink/4">
<span className={cx('num grid h-10 w-14 shrink-0 place-items-center rounded-[10px] text-[15px] font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>{p === null ? '—' : `${p}%`}</span>
<span className={cx('num grid h-11 w-14 shrink-0 place-items-center rounded-[10px] leading-none font-semibold', tone === 'good' ? 'bg-good-soft text-good' : tone === 'warn' ? 'bg-warn-soft text-warn' : tone === 'bad' ? 'bg-bad-soft text-bad' : 'bg-sunken text-ink-3')}>
{p === null ? (
'—'
) : (
<span className="flex flex-col items-center gap-0.5">
<span className="text-[16px]">{letterGrade(p)}</span>
<span className="text-[11px] font-medium opacity-80">{p}%</span>
</span>
)}
</span>
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">
{h.completedAt ? formatDateTime(h.completedAt) : ''}

View file

@ -5,12 +5,12 @@ import { useNavigate, useSearchParams } from 'react-router';
import { toast } from 'sonner';
import { CardEditor } from '@/features/editors';
import { Explain } from '@/features/Explain';
import { FlipCard, KeyHints, StreakChip, StudyFooter, StudyTopBar, useStreak } from '@/features/flashcards';
import { FlipCard, StreakChip, StudyFooter, StudyTopBar, useStreak } from '@/features/flashcards';
import { api, errorMessage } from '@/lib/api';
import { useAiStatus, useRefresh } from '@/lib/queries';
import type { DueCounts, QueueCard } from '@/lib/types';
import { cx, formatMinutes, plural, useDocumentTitle, useHotkeys } from '@/lib/util';
import { Badge, Button, ClassDot, Dialog, ErrorState, IconButton, Kbd, Menu, MenuItem, PageLoading } from '@/ui';
import { Badge, Button, ClassDot, Dialog, ErrorState, IconButton, Menu, MenuItem, PageLoading } from '@/ui';
interface QueueResponse {
cards: QueueCard[];
@ -207,7 +207,7 @@ export default function ReviewPage() {
<Badge tone="good">{counts.review} due</Badge>
</div>
<span className="num text-[13px] font-medium text-ink-2 sm:hidden">{remaining} left</span>
<IconButton label="Undo last rating (U)" onClick={undo} disabled={!last || busy}>
<IconButton label="Undo last rating" onClick={undo} disabled={!last || busy}>
<Undo2 />
</IconButton>
{current && (
@ -220,7 +220,6 @@ export default function ReviewPage() {
>
<MenuItem
icon={<Pencil />}
hint="E"
onSelect={() => {
setDraft({ front: current.card.front, back: current.card.back, hint: current.card.hint, tags: current.card.tags });
setEditing(current);
@ -305,16 +304,6 @@ export default function ReviewPage() {
Show answer
</Button>
)}
<KeyHints
items={[
[<><Kbd>Space</Kbd><Kbd>↑</Kbd><Kbd>↓</Kbd></>, 'flip'],
[<Kbd>←</Kbd>, 'again'],
[<Kbd>→</Kbd>, 'good'],
[<><Kbd>1</Kbd>–<Kbd>4</Kbd></>, 'rate'],
[<Kbd>U</Kbd>, 'undo'],
[<Kbd>E</Kbd>, 'edit'],
]}
/>
</StudyFooter>
)}

View file

@ -4,6 +4,7 @@ import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from 'rea
import { NavLink, useNavigate, useParams } from 'react-router';
import { toast } from 'sonner';
import { shareUrl } from '@/features/dialogs';
import { TemplateSettings } from '@/features/TemplateSettings';
import { api, errorMessage } from '@/lib/api';
import { qk, useRefresh } from '@/lib/queries';
import type { AppSettings, ShareListItem, Template } from '@/lib/types';
@ -220,58 +221,6 @@ function SharingSettings() {
);
}
/* ------------------------------ templates ------------------------------ */
function TemplateSettings() {
const refresh = useRefresh();
const q = useQuery({ queryKey: qk.templates, queryFn: () => api.get<{ templates: Template[] }>('/api/templates').then((r) => r.templates) });
if (!q.data) return <Skeleton className="h-48" />;
const groups: { kind: Template['kind']; title: string; blurb: string }[] = [
{ kind: 'generation', title: 'AI generation presets', blurb: 'Appear under "Preset" when you generate with AI.' },
{ kind: 'quiz', title: 'Quiz templates', blurb: 'Appear under "Start from" when you create a quiz. Save any quiz as a template from its menu.' },
{ kind: 'deck', title: 'Flashcard templates', blurb: 'Appear under "Start from" when you create a deck.' },
];
return (
<>
{groups.map((g) => {
const list = q.data!.filter((t) => t.kind === g.kind);
return (
<Section key={g.kind} title={g.title}>
<ul className="card divide-y divide-line">
{list.map((t) => (
<li key={t.id} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{t.name}</span>
{t.builtin ? <Badge>Built in</Badge> : <Badge tone="accent">Yours</Badge>}
</div>
{t.description && <div className="mt-0.5 line-clamp-2 text-[13px] text-ink-2">{t.description}</div>}
{t.kind !== 'generation' && <div className="mt-0.5 text-xs text-ink-3">{t.kind === 'quiz' ? plural((t.payload.questions ?? []).length, 'question') : plural((t.payload.cards ?? []).length, 'card')}</div>}
</div>
{!t.builtin && (
<IconButton
label="Delete template"
size="sm"
onClick={async () => {
await api.del(`/api/templates/${t.id}`).catch((e) => toast.error(errorMessage(e)));
await refresh();
}}
>
<Trash2 />
</IconButton>
)}
</li>
))}
{list.length === 0 && <li className="px-4 py-4 text-[13px] text-ink-3">None yet.</li>}
</ul>
<p className="mt-2 text-xs text-ink-3">{g.blurb}</p>
</Section>
);
})}
</>
);
}
/* ------------------------------ data ------------------------------ */
interface V1Summary {

View file

@ -362,11 +362,11 @@ function SharedNote({ note, back }: { note: PublicNote; back?: { to: string; lab
);
}
function SharedDocument({ doc, token }: { doc: PublicDocument; token: string }) {
const url = `/api/public/${token}/file`;
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';
return (
<Frame>
<Frame back={back}>
<div className="eyebrow mb-2 flex items-center gap-1.5">
<FileText className="size-3.5" /> Shared document
</div>
@ -384,7 +384,7 @@ function SharedDocument({ doc, token }: { doc: PublicDocument; token: string })
);
}
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
const ITEM_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen />, document: <FileText /> };
function SharedCollection({ data, token }: { data: PublicCollection; token: string }) {
const groups = [{ id: null as string | null, name: '' }, ...data.folders].map((f) => ({ ...f, items: data.items.filter((i) => (f.id === null ? !i.folderId || !data.folders.some((x) => x.id === i.folderId) : i.folderId === f.id)) })).filter((g) => g.items.length > 0);
@ -405,10 +405,10 @@ function SharedCollection({ data, token }: { data: PublicCollection; token: stri
{g.items.map((i) => (
<li key={`${i.kind}:${i.id}`}>
<Link to={`/s/${token}/${i.kind}/${i.id}`} className="flex items-center gap-3 px-4 py-3.5 hover:bg-ink/4">
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span>
<span className={cx('grid size-10 shrink-0 place-items-center rounded-[11px] [&>svg]:size-[18px]', i.kind === 'quiz' ? 'bg-accent-soft text-accent' : i.kind === 'deck' ? 'bg-marker/45 text-ink dark:bg-marker/20 dark:text-marker' : i.kind === 'document' ? 'bg-sunken text-ink-2' : 'bg-good-soft text-good')}>{ITEM_ICON[i.kind]}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium">{i.title}</span>
<span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : 'Note'}</span>
<span className="text-xs text-ink-3">{i.kind === 'quiz' ? plural(i.count, 'question') : i.kind === 'deck' ? plural(i.count, 'card') : i.kind === 'document' ? `Document${i.count ? ` · ${plural(i.count, 'page')}` : ''}` : 'Note'}</span>
</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
@ -464,7 +464,7 @@ export default function SharedPage() {
case 'note':
return <SharedNote note={data} back={back} />;
case 'document':
return <SharedDocument doc={data} token={token} />;
return <SharedDocument doc={data} token={token} nested={nested} back={back} />;
case 'collection':
return <SharedCollection data={data} token={token} />;
}

View file

@ -580,10 +580,20 @@
@utility tab-slate {
--tab: var(--c-slate);
}
/* For bars with no bottom padding of their own (fixed-height footers and nav). */
@utility safe-bottom {
padding-bottom: max(env(safe-area-inset-bottom), 0px);
}
/*
* Bottom padding of 0.75rem plus the home-indicator inset. Use this instead of combining
* `safe-bottom` with `pb-3`/`py-3`: safe-bottom replaces the padding (to 0 on desktop),
* which left dialog footer buttons sitting on the bottom edge.
*/
@utility safe-pb-3 {
padding-bottom: calc(0.75rem + env(safe-area-inset-bottom, 0px));
}
@media print {
.no-print {
display: none !important;

View file

@ -372,7 +372,7 @@ export function Dialog({
</RDialog.Close>
</div>
<div className={cx('min-h-0 flex-1 overflow-y-auto', !bare && 'px-5 pb-5 sm:px-6')}>{children}</div>
{footer && <div className="safe-bottom flex flex-wrap items-center justify-end gap-2 border-t border-line bg-paper/60 px-5 py-3 sm:rounded-b-[18px] sm:px-6">{footer}</div>}
{footer && <div className="safe-pb-3 flex flex-wrap items-center justify-end gap-2 border-t border-line bg-paper/60 px-5 pt-3 sm:rounded-b-[18px] sm:px-6">{footer}</div>}
</RDialog.Content>
</RDialog.Portal>
</RDialog.Root>