import { CornerDownLeft, Sparkles, Square, X } from 'lucide-react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { errorMessage, streamEvents } from '@/lib/api'; import type { ToolActivity } from '@/lib/types'; import { cx } from '@/lib/util'; import { GenUiContext, Markdown } from '@/ui/Markdown'; import { Button, Callout, IconButton, Spinner, Tooltip } from '@/ui'; import { ToolSteps } from './ToolSteps'; type Event = { type: 'text'; delta: string } | { type: 'tool'; tool: ToolActivity } | { type: 'error'; message: string } | { type: 'done' }; interface Turn { role: 'user' | 'assistant'; text: string; tools?: ToolActivity[]; } /** * The visitor-facing assistant on a share link (when the owner allows it). It answers from the * shared material only; the conversation lives in this tab and is never saved on the server. * `hidden` tucks it away (during a quiz or flashcard session) without losing the conversation. */ export function SharedAssistant({ token, title, item, hidden }: { token: string; title: string; item?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string }; hidden?: boolean }) { const [open, setOpen] = useState(false); const [turns, setTurns] = useState([]); const [input, setInput] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const abort = useRef(null); const list = useRef(null); useEffect(() => () => abort.current?.abort(), []); useEffect(() => { const el = list.current; if (el) el.scrollTop = el.scrollHeight; }, [turns, open]); const send = useCallback( async (text: string) => { if (busy) return; // The server accepts the last 16 turns; older ones are dropped from the request. const history: Turn[] = [...turns, { role: 'user' as const, text }].slice(-15); setTurns([...turns, { role: 'user', text }, { role: 'assistant', text: '', tools: [] }]); setBusy(true); setError(''); const controller = new AbortController(); abort.current = controller; const patchLast = (fn: (t: Turn) => Turn) => setTurns((t) => t.map((x, i) => (i === t.length - 1 ? fn(x) : x))); try { await streamEvents( `/api/public/${token}/chat`, { messages: history.filter((t) => t.text.trim()).map((t) => ({ role: t.role, text: t.text })), item }, (e) => { if (e.type === 'text') patchLast((x) => ({ ...x, text: x.text + e.delta })); else if (e.type === 'tool') patchLast((x) => ({ ...x, tools: (x.tools ?? []).some((t) => t.id === e.tool.id) ? (x.tools ?? []).map((t) => (t.id === e.tool.id ? e.tool : t)) : [...(x.tools ?? []), e.tool] })); else if (e.type === 'error') setError(e.message); }, controller.signal, ); } catch (e) { if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e)); } finally { setBusy(false); // Drop an empty reply so the next request stays valid. setTurns((t) => (t[t.length - 1]?.role === 'assistant' && !t[t.length - 1].text ? t.slice(0, -1) : t)); } }, [busy, turns, token, item], ); const genUi = useMemo(() => ({ streaming: busy, onSend: (text: string) => void send(text.slice(0, 4000)) }), [busy, send]); if (hidden) return null; if (!open) { // The same round sparkle button the owner sees in the app. return ( ); } return (
Assistant
{title}
setOpen(false)}>
{turns.length === 0 &&

Ask a question about this material: what something means, why an answer is right, or for a quick recap.

} {turns.map((t, i) => t.role === 'user' ? (
{t.text}
) : (
{t.tools && t.tools.length > 0 && } {t.text ? ( {t.text} ) : busy && i === turns.length - 1 && !t.tools?.some((x) => x.status === 'running') ? ( ) : null}
), )}
{error && ( {error} )}
{ e.preventDefault(); if (busy) return abort.current?.abort(); const text = input.trim(); if (!text) return; setInput(''); void send(text.slice(0, 4000)); }} > setInput(e.target.value)} placeholder="Ask a question…" aria-label="Your question" className={cx('h-10 min-w-0 flex-1 rounded-[10px] border border-line-strong bg-paper px-3 text-sm outline-none focus:border-accent')} />

AI can be wrong. Nothing you type here is saved.

); }