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; path: string; line_start: number; line_end: number; span: string; }; type Turn = { role: "user" | "assistant"; text: string; citations?: Citation[]; status?: string; steps?: 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 === "step") { setTurns((t) => { const last = t[t.length - 1]; return [...t.slice(0, -1), { ...last, status: d.message as string, steps: [...(last.steps ?? []), d.message as string] }]; }); } else if (event === "error") { patchLast({ text: d.message as string, status: undefined }); } 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.steps && t.steps.length > 0 && (
{t.status ? `${t.status}...` : `${t.steps.length} steps through the archive`}
    {t.steps.map((s, j) => (
  1. {s}
  2. ))}
)} {t.status && !t.steps?.length &&

{t.status}...

} {t.text &&

{t.text}

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

    {c.span.length > 220 ? `${c.span.slice(0, 220)}...` : c.span}

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