Study/web/src/features/AssistantPanel.tsx
Elijah f0aabe4d5d
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m2s
First revision: DeepSeek, numeric questions, background assistant, UI fixes
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>
2026-11-15 12:48:17 -07:00

783 lines
37 KiB
TypeScript

import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowUp, AtSign, BookOpen, Check, ChevronDown, ChevronRight, CircleAlert, FileText, Folder, History, Layers, LoaderCircle, NotebookPen, Play, Plus, Sparkles, Square, Trash2, X } from 'lucide-react';
import { 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 { 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';
interface Conversation {
id: string;
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;
const DRAFT_ICON = { quiz: <BookOpen />, deck: <Layers />, note: <NotebookPen /> };
/* ------------------------------ message parts ------------------------------ */
function ToolLine({ tool }: { tool: ToolActivity }) {
return (
<div className="flex items-center gap-2 text-[13px] text-ink-2">
{tool.status === 'running' ? <LoaderCircle className="size-3.5 shrink-0 animate-spin text-accent" /> : tool.status === 'error' ? <CircleAlert className="size-3.5 shrink-0 text-bad" /> : <Check className="size-3.5 shrink-0 text-good" />}
<span className="min-w-0 truncate">
{tool.label}
{tool.summary && <span className={cx('ml-1.5', tool.status === 'error' ? 'text-bad' : 'text-ink-3')}>· {tool.summary}</span>}
</span>
</div>
);
}
function DraftCard({ item, onNavigate }: { item: Extract<UiItem, { type: 'draft' }>; onNavigate: () => void }) {
const gone = item.status === 'discarded';
const saved = item.status === 'saved';
return (
<div className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1">
<span className="grid size-10 shrink-0 place-items-center rounded-[11px] bg-accent-soft text-accent [&>svg]:size-[18px]">{DRAFT_ICON[item.kind]}</span>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold">{item.title}</div>
<div className="text-xs text-ink-3">
{item.kind === 'note' ? 'Draft note' : `Draft · ${plural(item.count, item.kind === 'quiz' ? 'question' : 'card')}`}
{saved ? ' · saved' : gone ? ' · discarded' : ' · not saved yet'}
</div>
</div>
{!gone && (
<Button to={`/drafts/${item.draftId}`} onClick={onNavigate} size="sm" variant={saved ? 'secondary' : 'primary'}>
{saved ? 'Open' : 'Review'}
</Button>
)}
</div>
);
}
function ActionCard({ item, onResolved }: { item: Extract<UiItem, { type: 'action' }>; onResolved: (status: string, result: string) => void }) {
const [busy, setBusy] = useState<'confirm' | 'cancel' | null>(null);
const resolve = async (confirm: boolean) => {
setBusy(confirm ? 'confirm' : 'cancel');
try {
const res = await api.post<{ status: string; result: string }>(`/api/ai/actions/${item.actionId}`, { confirm });
onResolved(res.status, res.result);
} catch (e) {
toast.error(errorMessage(e));
} finally {
setBusy(null);
}
};
const destructive = item.changes.some((c) => c.startsWith('Delete'));
return (
<div className={cx('rounded-[14px] border bg-surface p-3.5 shadow-1', item.status === 'pending' ? 'border-warn/50' : 'border-line')}>
<div className="text-sm font-semibold">{item.status === 'pending' ? 'Approve these changes?' : 'Proposed changes'}</div>
<div className="mt-0.5 text-[13px] text-ink-2">{item.summary}</div>
<ul className="mt-2 space-y-0.5 text-[13px]">
{item.changes.map((c, i) => (
<li key={i} className="flex gap-2">
<span className="text-ink-3">•</span>
<span>{c}</span>
</li>
))}
</ul>
{item.status === 'pending' ? (
<div className="mt-3 flex gap-2">
<Button size="sm" variant={destructive ? 'danger' : 'primary'} loading={busy === 'confirm'} disabled={busy !== null} onClick={() => resolve(true)}>
Confirm
</Button>
<Button size="sm" variant="ghost" loading={busy === 'cancel'} disabled={busy !== null} onClick={() => resolve(false)}>
Cancel
</Button>
</div>
) : (
<div className={cx('mt-2.5 flex items-center gap-1.5 text-[13px] font-medium', item.status === 'confirmed' ? 'text-good' : item.status === 'failed' ? 'text-bad' : 'text-ink-3')}>
{item.status === 'confirmed' ? <Check className="size-4" /> : <X className="size-4" />}
{item.result ?? (item.status === 'confirmed' ? 'Done' : 'Cancelled')}
</div>
)}
</div>
);
}
function AssistantMessage({ message, onNavigate, onAction }: { message: ChatMessage; onNavigate: () => void; onAction: (actionId: string, status: string, result: string) => void }) {
const navigate = useNavigate();
const [toolsOpen, setToolsOpen] = useState(false);
const citations = useMemo<Citation[]>(() => message.ui.flatMap((u) => (u.type === 'sources' ? u.items : [])), [message.ui]);
const cited = useMemo(() => citedSources(message.text, citations), [message.text, citations]);
const openCite = (c: Citation) => {
onNavigate();
navigate(`/documents/${c.documentId}?chunk=${c.chunkId}`);
};
const cards = message.ui.filter((u) => u.type !== 'sources');
const running = message.tools.filter((t) => t.status === 'running');
const finished = message.tools.filter((t) => t.status !== 'running');
const thinking = message.pending && !message.text && running.length === 0;
return (
<div className="space-y-2.5">
{finished.length > 0 && (
<div>
<button type="button" aria-expanded={toolsOpen} onClick={() => setToolsOpen(!toolsOpen)} className="flex items-center gap-1 text-xs font-medium text-ink-3 hover:text-ink-2">
<ChevronRight className={cx('size-3.5 transition-transform', toolsOpen && 'rotate-90')} />
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
{finished.some((t) => t.status === 'error') && <CircleAlert className="size-3.5 text-bad" />}
</button>
{toolsOpen && <div className="mt-1.5 space-y-1 border-l-2 border-line pl-3">{finished.map((t) => <ToolLine key={t.id} tool={t} />)}</div>}
</div>
)}
{running.map((t) => (
<ToolLine key={t.id} tool={t} />
))}
{thinking && (
<div className="flex items-center gap-2 text-[13px] text-ink-3" role="status">
<Spinner className="size-3.5" label="Thinking" /> {message.reasoning ? 'Thinking it through' : 'Thinking'}
</div>
)}
{message.text && <Markdown citations={citations} onCite={openCite} className="text-[15px]">{message.text}</Markdown>}
{cards.map((item, i) =>
item.type === 'draft' ? (
<DraftCard key={i} item={item} onNavigate={onNavigate} />
) : item.type === 'action' ? (
<ActionCard key={i} item={item} onResolved={(status, result) => onAction(item.actionId, status, result)} />
) : item.type === 'link' ? (
<Link key={i} to={`/${ITEM_URL[item.kind]}/${item.id}`} onClick={onNavigate} className="flex items-center gap-3 rounded-[14px] border border-line bg-surface p-3 shadow-1 hover:border-ink-3">
<span className="grid size-9 shrink-0 place-items-center rounded-[10px] bg-marker text-marker-ink">
<Play className="size-4 fill-current" />
</span>
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{item.title}</span>
<ChevronRight className="size-4 text-ink-3" />
</Link>
) : null,
)}
{cited.length > 0 && (
<div className="flex flex-wrap gap-1.5 pt-0.5">
{cited.map(({ n, cite }) => (
<button key={cite.ref} type="button" onClick={() => openCite(cite)} className="flex max-w-full items-center gap-1.5 rounded-full border border-line bg-surface py-1 pr-2.5 pl-1 text-xs text-ink-2 hover:border-ink-3 hover:text-ink">
<span className="num grid size-[18px] shrink-0 place-items-center rounded-full bg-accent-soft text-[10.5px] font-semibold text-accent">{n}</span>
<FileText className="size-3 shrink-0" />
<span className="truncate">{cite.label}</span>
</button>
))}
</div>
)}
{message.error && (
<Callout tone="bad" icon={<CircleAlert />} className="py-2.5">
{message.error}
</Callout>
)}
</div>
);
}
/* ------------------------------ 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({
variant,
headerAction,
conversationId: routeConversationId,
onConversationChange,
}: {
variant: 'drawer' | 'page';
headerAction?: ReactNode;
conversationId?: string;
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 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 [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 setConversation = useCallback(
(id: string | null) => {
conversationRef.current = id;
setConversationId(id);
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 (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(() => {
// 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, 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;
const send = useCallback(
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 : 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, 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,
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 })),
},
},
onEvent,
signal,
),
);
},
[busy, tags, follow, effectiveModelId, context.classId, activeDocs],
);
// Requests from elsewhere in the app ("Ask about this document", "New questions on these topics").
useEffect(() => {
if (!seed || handledSeed.current === seed.id || !ai.data) return;
handledSeed.current = seed.id;
assistant.consumeSeed();
if (seed.newChat) {
stream.current?.abort();
setBusy(false);
setConversation(null);
setMessages([]);
onConversationChange?.(null);
}
setFocusDocs(seed.documentIds ?? []);
if (seed.prompt && seed.autoSend && ai.data.ready) void send(seed.prompt, { conversationId: seed.newChat ? null : undefined, documentIds: seed.documentIds, classId: seed.classId });
else {
if (seed.prompt) setInput(seed.prompt);
setTimeout(() => inputRef.current?.focus(), 60);
}
}, [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]);
// 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)) })));
void refresh();
};
const suggestions = useMemo(() => {
if (activeDocs.length > 0) {
return ['Summarise the key points of this document', 'Make flashcards from this, focusing on medications and adverse effects', 'Write 15 NCLEX-style questions from this', 'What are the most testable concepts here?'];
}
if (className) {
return [`Create a 20-question NCLEX-style quiz using the documents in ${className}`, 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', `What should I focus on in ${className} this week?`, 'Make a study guide from all the documents in this class'];
}
return ['What should I study today?', 'Find the questions I frequently get wrong and create a new practice quiz covering those concepts', 'Explain the difference between left-sided and right-sided heart failure', 'Start a practice session with the questions I miss most'];
}, [activeDocs.length, className]);
const contextLabel = activeDocs.length > 0 ? (context.documentIds.length && context.label ? context.label : plural(activeDocs.length, 'document')) : className;
const 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-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>
{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 />
</IconButton>
{variant === 'drawer' && (
<Menu
trigger={
<IconButton label="History" size="sm" tooltip={false}>
<History />
</IconButton>
}
>
<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={c.running ? 'working…' : timeAgo(c.updatedAt)}>
{c.title}
</MenuItem>
))}
{conversationId && (
<>
<MenuSeparator />
<MenuItem
icon={<Trash2 />}
danger
onSelect={async () => {
const id = conversationId;
stop();
await api.del(`/api/ai/conversations/${id}`).catch(() => undefined);
void qc.invalidateQueries({ queryKey: ['ai', 'conversations'] });
newChat();
}}
>
Delete this conversation
</MenuItem>
</>
)}
</Menu>
)}
{headerAction}
</header>
<div
ref={scroller}
onScroll={(e) => {
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-6')}
aria-live="polite"
>
{ai.isLoading || loadingHistory ? (
<div className="grid h-full place-items-center">
<Spinner />
</div>
) : !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, 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>
</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. 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">
<span className="flex-1">{s}</span>
<ArrowUp className="size-4 shrink-0 rotate-45 text-ink-3 group-hover:text-ink" />
</button>
))}
</div>
</div>
) : (
<div className="mx-auto max-w-2xl space-y-6">
{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.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} />
),
)}
</div>
)}
</div>
{ai.data?.ready && (
<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">
{activeDocs.length > 0 ? <FileText /> : <BookOpen />}
<span className="truncate">Looking at: {contextLabel}</span>
</Badge>
{focusDocs.length > 0 && (
<button type="button" className="text-xs text-ink-3 hover:text-ink" onClick={() => setFocusDocs([])}>
Clear
</button>
)}
</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="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) stop();
else void send(input);
}}
>
{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>
</div>
)}
</div>
);
}