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: , deck: , note: };
/* ------------------------------ message parts ------------------------------ */
function ToolLine({ tool }: { tool: ToolActivity }) {
return (
{tool.status === 'running' ? : tool.status === 'error' ? : }
{tool.label}
{tool.summary && · {tool.summary} }
);
}
function DraftCard({ item, onNavigate }: { item: Extract; onNavigate: () => void }) {
const gone = item.status === 'discarded';
const saved = item.status === 'saved';
return (
{DRAFT_ICON[item.kind]}
{item.title}
{item.kind === 'note' ? 'Draft note' : `Draft · ${plural(item.count, item.kind === 'quiz' ? 'question' : 'card')}`}
{saved ? ' · saved' : gone ? ' · discarded' : ' · not saved yet'}
{!gone && (
{saved ? 'Open' : 'Review'}
)}
);
}
function ActionCard({ item, onResolved }: { item: Extract; 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 (
{item.status === 'pending' ? 'Approve these changes?' : 'Proposed changes'}
{item.summary}
{item.changes.map((c, i) => (
•
{c}
))}
{item.status === 'pending' ? (
resolve(true)}>
Confirm
resolve(false)}>
Cancel
) : (
{item.status === 'confirmed' ? : }
{item.result ?? (item.status === 'confirmed' ? 'Done' : 'Cancelled')}
)}
);
}
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(() => 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 (
{finished.length > 0 && (
setToolsOpen(!toolsOpen)} className="flex items-center gap-1 text-xs font-medium text-ink-3 hover:text-ink-2">
{finished.length === 1 ? finished[0].label : `${finished.length} steps`}
{finished.some((t) => t.status === 'error') && }
{toolsOpen &&
{finished.map((t) => )}
}
)}
{running.map((t) => (
))}
{thinking && (
{message.reasoning ? 'Thinking it through' : 'Thinking'}
)}
{message.text &&
{message.text} }
{cards.map((item, i) =>
item.type === 'draft' ? (
) : item.type === 'action' ? (
onAction(item.actionId, status, result)} />
) : item.type === 'link' ? (
{item.title}
) : null,
)}
{cited.length > 0 && (
{cited.map(({ n, cite }) => (
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">
{n}
{cite.label}
))}
)}
{message.error && (
} className="py-2.5">
{message.error}
)}
);
}
/* ------------------------------ composer: model picker and @ tags ------------------------------ */
const TAG_ICON: Record = { quiz: , deck: , note: , document: , folder: };
const TAG_NOUN: Record = { quiz: 'Quiz', deck: 'Flashcards', note: 'Note', document: 'Document', folder: 'Folder' };
function TagChip({ item, onRemove, inverted }: { item: TaggedItem; onRemove?: () => void; inverted?: boolean }) {
return (
svg]:size-3 [&>svg]:shrink-0', inverted ? 'bg-paper/15 text-paper' : 'bg-accent-soft text-accent')}>
{TAG_ICON[item.kind]}
{item.title}
{onRemove && (
)}
);
}
/** 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 (
{chosen ? chosen.label : defaultLabel ? `${defaultLabel}` : 'Default model'}
}
>
Model for this chat
onChange('')} hint={!chosen ? : undefined}>
Default{defaultLabel ? ` · ${defaultLabel}` : ''}
{providers.map((p) => (
{p}
{usable
.filter((m) => m.providerName === p)
.map((m) => (
onChange(m.id)} hint={m.id === value ? : !m.capabilities.tools ? 'no tools' : undefined}>
{m.label}
))}
))}
);
}
/** 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(initialConversation);
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [busy, setBusy] = useState(false);
const [loadingHistory, setLoadingHistory] = useState(false);
const [focusDocs, setFocusDocs] = useState([]);
const [tags, setTags] = useState([]);
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(null);
const stopRequested = useRef(false);
const conversationRef = useRef(initialConversation);
const scroller = useRef(null);
const inputRef = useRef(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) => {
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(`/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(
'/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 (
{
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 ? (
) : !ai.data?.ready ? (
} 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.
variant === 'drawer' && assistant.close()} size="sm" variant="primary">
Open AI settings
) : messages.length === 0 ? (
What are we working on?
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.
{suggestions.map((s) => (
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">
{s}
))}
) : (
{messages.map((m) =>
m.role === 'user' ? (
{m.tags?.length ? (
{m.tags.map((t) => (
))}
) : null}
{m.text}
) : (
variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} />
),
)}
)}
{ai.data?.ready && (
{contextLabel && (
{activeDocs.length > 0 ? : }
Looking at: {contextLabel}
{focusDocs.length > 0 && (
setFocusDocs([])}>
Clear
)}
)}
{mention && (
{context.classId ? `Materials in ${className ?? 'this class'}` : 'Your library'}
{pickable.length === 0 ? (
{context.classId || mention.query ? 'Nothing matches.' : 'Type to search your quizzes, decks, notes and documents.'}
) : (
pickable.map((o, i) => (
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')}
>
{TAG_ICON[o.kind]}
{o.title}
{TAG_NOUN[o.kind]}
{o.folderName ? ` · ${o.folderName}` : ''}
{!context.classId ? ` · ${o.className}` : ''}
))
)}
)}
Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.
)}
);
}