Study/web/src/features/AssistantPanel.tsx
2026-11-11 18:32:46 -07:00

492 lines
24 KiB
TypeScript

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: <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>
);
}
/* ------------------------------ 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<string | null>(routeConversationId ?? null);
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 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 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<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 }));
},
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 (
<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">
<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>
</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={timeAgo(c.updatedAt)}>
{c.title}
</MenuItem>
))}
{conversationId && (
<>
<MenuSeparator />
<MenuItem
icon={<Trash2 />}
danger
onSelect={async () => {
await api.del(`/api/ai/conversations/${conversationId}`).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-1')}
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 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.</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.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-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">
{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>
)}
<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"
onSubmit={(e) => {
e.preventDefault();
if (busy) abort.current?.abort();
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>
</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>
);
}