import { useEffect, useMemo, useRef, useState } from "react"; import { databaseEntries, type NavEntry } from "../shell/nav"; import { isAdmin, me } from "../shell/session"; import { useEscapeClose } from "../ui/useEscapeClose"; import { eraseMemory, fetchMemory, promoteMemory, type MemoryEntry, type MemoryOrder } from "./memoryApi"; export function MemoryPanel({ open, onClose, granted }: { open: boolean; onClose: () => void; granted: NavEntry[]; }) { const [entries, setEntries] = useState([]); const [order, setOrder] = useState("newest"); const [total, setTotal] = useState(0); const [next, setNext] = useState(null); const [more, setMore] = useState(false); const [moreProblem, setMoreProblem] = useState(""); const [admin, setAdmin] = useState(false); const [loading, setLoading] = useState(true); const [loadProblem, setLoadProblem] = useState(""); const [retry, setRetry] = useState(0); const [confirming, setConfirming] = useState(null); const [busy, setBusy] = useState(null); const [rowProblem, setRowProblem] = useState<{ id: string; text: string } | null>(null); const [status, setStatus] = useState(""); const panelRef = useRef(null); const inFlight = useRef(false); const moreInFlight = useRef(false); const generation = useRef(0); const labels = useMemo(() => new Map(databaseEntries(granted).filter((row) => row.kind !== "group") .map((row) => [row.key, row.label])), [granted]); useEscapeClose(open, () => { if (confirming && !busy) setConfirming(null); else onClose(); }, { container: () => panelRef.current }); useEffect(() => { if (!open) return; const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null; panelRef.current?.focus(); return () => { if (opener?.isConnected) opener.focus(); }; }, [open]); useEffect(() => { if (!open) return; const current = ++generation.current; setEntries([]); setTotal(0); setNext(null); setMore(false); setMoreProblem(""); setAdmin(false); setLoading(true); setLoadProblem(""); setConfirming(null); setBusy(null); setRowProblem(null); setStatus(""); inFlight.current = false; moreInFlight.current = false; void Promise.all([fetchMemory(null, order), me()]).then(([result, user]) => { if (generation.current !== current) return; setAdmin(isAdmin(user)); if (result.ok) { setEntries(result.value.entries); setTotal(result.value.total); setNext(result.value.next); } else setLoadProblem("Memory could not be loaded. Try again."); setLoading(false); }).catch(() => { if (generation.current !== current) return; setLoadProblem("Memory could not be loaded. Try again."); setLoading(false); }); return () => { generation.current += 1; }; }, [open, retry, order]); // Follow the server continuation in the selected order. const loadOlder = async () => { if (!next || moreInFlight.current) return; const current = generation.current; moreInFlight.current = true; setMore(true); setMoreProblem(""); try { const result = await fetchMemory(next, order); if (generation.current !== current) return; if (!result.ok) { setMoreProblem("More memory could not be loaded. Try again."); return; } setEntries((rows) => { const seen = new Set(rows.map((row) => row.id)); return [...rows, ...result.value.entries.filter((row) => !seen.has(row.id))]; }); setTotal(result.value.total); setNext(result.value.next); } finally { if (generation.current === current) { moreInFlight.current = false; setMore(false); } } }; const act = async (row: MemoryEntry, action: "erase" | "share") => { if (inFlight.current || (row.scope === "company" && !admin) || (action === "share" && !admin)) return; if (action === "erase" && confirming !== row.id) return; const current = generation.current; inFlight.current = true; setBusy(row.id); setRowProblem(null); setStatus(""); try { const result = await (action === "erase" ? eraseMemory(row.id) : promoteMemory(row.id)); if (generation.current !== current) return; if (!result.ok) { setRowProblem({ id: row.id, text: action === "erase" ? "This memory could not be erased. Try again." : "This memory could not be shared. Try again." }); return; } if (action === "erase") { panelRef.current?.focus({ preventScroll: true }); setEntries((rows) => rows.filter((item) => item.id !== row.id)); setTotal((value) => Math.max(0, value - 1)); setStatus("Memory erased."); } else { // Promotion copies the fact into company memory. Reload its server-owned identity. const refreshed = await fetchMemory(null, order); if (generation.current !== current) return; if (refreshed.ok) { setEntries(refreshed.value.entries); setTotal(refreshed.value.total); setNext(refreshed.value.next); } else setLoadProblem("Memory was shared. Reload the list to see it."); setStatus("Shared with company."); } setConfirming(null); } finally { if (generation.current === current) { inFlight.current = false; setBusy(null); } } }; if (!open) return null; const groups = [ { title: "People", rows: entries.filter((row) => row.scope === "personal" && row.kind === "person") }, { title: "Preferences", rows: entries.filter((row) => row.scope === "personal" && row.kind === "preference") }, { title: "Facts", rows: entries.filter((row) => row.scope === "personal" ? row.kind === "fact" : !admin) }, ...(admin ? [{ title: "Company", rows: entries.filter((row) => row.scope === "company") }] : []), ]; return

Memory

{loading ?
: loadProblem ? null : !entries.length && !next ?

Nothing is remembered yet.

:

{next ? `Showing ${entries.length} of ${total}` : `${total} ${total === 1 ? "memory" : "memories"}`}

} {loadProblem ?

{loadProblem}{" "}

: null} {groups.filter((group) => group.rows.length).map((group) =>

{group.title}

    {group.rows.map((row) => { const sourceLabels = [...new Set(row.sources.map((source) => labels.get(source.database)).filter(Boolean))]; const writable = row.scope === "personal" || admin; return
  • {row.text}

    {sourceLabels.length ? `From ${sourceLabels.join(", ")}` : row.sources.length ? "From a database" : "From conversation"}

    {writable ?
    {confirming === row.id ? <> Erase this memory? : <> {admin && row.scope === "personal" ? : null} }
    : null} {rowProblem?.id === row.id ?

    {rowProblem.text}

    : null}
  • ; })}
)} {!loading && next ?
: null} {moreProblem ?

{moreProblem}

: null}

{status}

; }