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 { 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 { 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;
}
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 && (
)}
);
}
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' ? (
) : (
{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 && (
{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 }) => (
))}
)}
{message.error && (
} className="py-2.5">
{message.error}
)}
);
}
/* ------------------------------ 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 classes = useClasses();
const refresh = useRefresh();
const qc = useQueryClient();
const { seed, context } = useAssistantState();
const [conversationId, setConversationId] = useState(routeConversationId ?? null);
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [busy, setBusy] = useState(false);
const [loadingHistory, setLoadingHistory] = useState(false);
const [focusDocs, setFocusDocs] = useState([]);
const abort = useRef(null);
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 load = useCallback(async (id: string) => {
setLoadingHistory(true);
try {
const res = await api.get<{ messages: ChatMessage[] }>(`/api/ai/conversations/${id}`);
setMessages(res.messages);
setConversationId(id);
stick.current = true;
} catch {
setConversationId(null);
setMessages([]);
} finally {
setLoadingHistory(false);
}
}, []);
useEffect(() => {
if (routeConversationId && routeConversationId !== conversationId) void load(routeConversationId);
if (!routeConversationId && variant === 'page' && conversationId && !busy) {
setConversationId(null);
setMessages([]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [routeConversationId]);
const newChat = useCallback(() => {
abort.current?.abort();
setConversationId(null);
setMessages([]);
setFocusDocs([]);
onConversationChange?.(null);
setTimeout(() => inputRef.current?.focus(), 30);
}, [onConversationChange]);
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 : conversationId;
setBusy(true);
setInput('');
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(
'/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 }));
},
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();
}
},
[busy, conversationId, context.classId, activeDocs, onConversationChange, qc, refresh],
);
// 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) {
abort.current?.abort();
setConversationId(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]);
// 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(), []);
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;
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-1')}
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 or a local model, then switch on a model.
) : 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.
{suggestions.map((s) => (
))}
) : (
{messages.map((m) =>
m.role === 'user' ? (
) : (
variant === 'drawer' && window.innerWidth < 1360 && assistant.close()} onAction={updateAction} />
),
)}
)}
{ai.data?.ready && (
{contextLabel && (
{activeDocs.length > 0 ? : }
Looking at: {contextLabel}
{focusDocs.length > 0 && (
)}
)}
Drafts and changes always wait for your approval. AI can make mistakes: verify clinical facts.
)}
);
}