import { useEffect, useState, type FormEvent } from "react"; import { useParams } from "react-router-dom"; import { api } from "../api/client"; import { streamSSE } from "../api/stream"; import { TelescopeIcon } from "../components/icons/Icons"; type Doc = { id: string; title: string; url: string; published_at: string | null }; type Notebook = { id: string; title: string; documents: Doc[] }; type Citation = { marker: number; title: string; url: string; heading: string | null; span: string }; type Turn = { role: "user" | "assistant"; text: string; citations?: Citation[]; status?: string }; export default function NotebookView() { const { id = "" } = useParams(); const [nb, setNb] = useState(null); const [turns, setTurns] = useState([]); const [q, setQ] = useState(""); const [chatId, setChatId] = useState(null); const [busy, setBusy] = useState(false); useEffect(() => { api(`/api/notebooks/${id}`).then(setNb); }, [id]); const ask = async (e: FormEvent) => { e.preventDefault(); const question = q.trim(); if (!question || busy) return; setQ(""); setBusy(true); setTurns((t) => [...t, { role: "user", text: question }, { role: "assistant", text: "", status: "Scanning" }]); const patchLast = (patch: Partial) => setTurns((t) => [...t.slice(0, -1), { ...t[t.length - 1], ...patch }]); try { await streamSSE( `/api/notebooks/${id}/chat`, (event, data) => { const d = data as Record; if (event === "status") { if (d.chat_id) setChatId(d.chat_id as string); patchLast({ status: d.message as string }); } else if (event === "answer") { patchLast({ text: d.text as string, citations: d.citations as Citation[], status: undefined }); } }, { method: "POST", body: JSON.stringify({ question, chat_id: chatId }) }, ); } catch { patchLast({ text: "Lost signal. Try again.", status: undefined }); } finally { setBusy(false); } }; return (
{turns.length === 0 && (

Ask anything about these posts. Answers cite the passage they came from.

)} {turns.map((t, i) => (
{t.status &&

{t.status}...

} {t.text &&

{t.text}

} {t.citations && t.citations.length > 0 && (
    {t.citations.map((c) => (
  1. {c.title} {c.heading ? `: ${c.heading}` : ""}

    {c.span.slice(0, 220)}...

  2. ))}
)}
))}
setQ(e.target.value)} placeholder="What have I written about pricing?" aria-label="Ask your notebook" />
); }