import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react'; import { describeCommandError } from '../app/actions'; import { useNative } from '../bridge/context'; import { toCommandError } from '../bridge/native'; import { PROTOCOL_MEMORY_SECTIONS, groupDecisionsBySection, memorySectionOf, type ProtocolDecision, type ProtocolMemorySection, type ProtocolSessionMemory, type ProtocolSessionSnapshot, } from '../protocol'; import { parseDecisions, parseForget, parseMoved, parseSessionMemory } from '../protocol/results'; import { activeRun } from '../protocol/view'; import { MemoryChanges } from './MemoryChanges'; import { MemoryProposals } from './MemoryProposals'; import { useSessions } from '../stores/sessionStore'; interface Props { connected: boolean; /** Este Dot puede cambiar cosas (`control`): olvidar. */ canControl: boolean; /** La conversación del asistente, si ya se abrió (para su memoria de sesión). */ companionId: string | null; /** Su foto: cuando termina un run, lo que recuerda puede haber cambiado. */ snapshot: ProtocolSessionSnapshot | null; /** Abre la conversación donde se guardó algo, como cualquier otra. */ onOpenSession(sessionId: string): void; } const UNREADABLE = 'The daemon answered in a way this version of Dot cannot read.'; const PROVENANCE: Record | 'none', string> = { agent: 'Saved by the assistant', auto: 'Extracted automatically from a conversation', none: 'Origin not recorded', }; /** M19 — las secciones de lo que recuerda, como títulos del inspector. */ const SECTION_LABEL: Record = { profile: 'You', person: 'People', project: 'Projects', topic: 'Topics', area: 'Areas', }; const shortId = (id: string) => (id.length > 8 ? id.slice(-8) : id); const when = (iso: string) => { const ms = Date.parse(iso); return Number.isNaN(ms) ? iso : new Date(ms).toLocaleString(); }; /** * M17 — inspector de la memoria del asistente (PRD §23.6): ver, buscar y olvidar * lo que recuerda, con su procedencia. Nada de lo recordado decide permisos, * aprobaciones ni guardas. **Sin estado optimista**: tras olvidar se vuelve a * pedir la lista, no se quita la fila; una orden sin respuesta es «Result * unknown» y no se repite sola. El lado nativo fija de quién es la memoria. */ export function MemoryPanel({ connected, canControl, companionId, snapshot, onOpenSession }: Props) { const native = useNative(); const sessions = useSessions((s) => s.sessions); const [draft, setDraft] = useState(''); const [applied, setApplied] = useState(''); const [decisions, setDecisions] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [expanded, setExpanded] = useState>({}); const [confirming, setConfirming] = useState(null); const [forgetting, setForgetting] = useState(false); const [moving, setMoving] = useState(false); const [note, setNote] = useState<{ tone: 'info' | 'bad'; text: string } | null>(null); const alive = useRef(true); const requestSeq = useRef(0); const appliedRef = useRef(''); appliedRef.current = applied; useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); /** Pide las decisiones (las últimas, o la búsqueda). Una respuesta vieja no pisa a una nueva. */ const load = useCallback( async (query: string) => { const seq = ++requestSeq.current; setLoading(true); setError(null); try { const raw = await native.memoryDecisions(query === '' ? undefined : query); if (!alive.current || seq !== requestSeq.current) return; const list = parseDecisions(raw); if (list) setDecisions(list); else setError(UNREADABLE); } catch (err) { if (alive.current && seq === requestSeq.current) setError(describeCommandError(toCommandError(err))); } finally { if (alive.current && seq === requestSeq.current) setLoading(false); } }, [native], ); // Al abrir la vista (y al recuperar la conexión). useEffect(() => { if (connected) void load(appliedRef.current); }, [connected, load]); // Cuando termina un run del asistente: puede haber guardado algo. Nada más (sin sondeo). const running = snapshot ? activeRun(snapshot) !== null : false; const wasRunning = useRef(running); useEffect(() => { if (wasRunning.current && !running && connected) void load(appliedRef.current); wasRunning.current = running; }, [running, connected, load]); const search = (event: FormEvent) => { event.preventDefault(); const query = draft.trim(); setApplied(query); setNote(null); setConfirming(null); void load(query); }; const forget = async (decision: ProtocolDecision) => { setForgetting(true); setNote(null); try { const removed = parseForget(await native.memoryForget(decision.id)); if (!alive.current) return; setConfirming(null); if (removed === null) setNote({ tone: 'bad', text: UNREADABLE }); else if (!removed) setNote({ tone: 'info', text: 'It was already gone.' }); } catch (err) { if (!alive.current) return; const failure = toCommandError(err); setNote({ tone: 'bad', text: failure.kind === 'unknown' ? 'Result unknown: the daemon did not answer in time. Refresh to see whether it was forgotten.' : describeCommandError(failure), }); setConfirming(null); } finally { if (alive.current) setForgetting(false); } // Sin optimismo: la lista es lo que contesta el daemon, no lo que se supone. if (alive.current) void load(appliedRef.current); }; /** M19 — mover un recuerdo a otra sección. Sin estado optimista: se vuelve a pedir la lista. */ const moveDecision = async (decision: ProtocolDecision, section: string) => { if (section === memorySectionOf(decision.type)) return; setMoving(true); setNote(null); try { const updated = parseMoved(await native.memoryMove(decision.id, section)); if (!alive.current) return; if (updated === null) setNote({ tone: 'bad', text: UNREADABLE }); else if (!updated) setNote({ tone: 'info', text: 'It was already gone.' }); } catch (err) { if (!alive.current) return; const failure = toCommandError(err); setNote({ tone: 'bad', text: failure.kind === 'unknown' ? 'Result unknown: the daemon did not answer in time. Refresh to see whether it moved.' : describeCommandError(failure), }); } finally { if (alive.current) setMoving(false); } if (alive.current) void load(appliedRef.current); }; const canChange = connected && canControl && !forgetting && !moving; return (

Memory

What the assistant remembers across conversations. It never decides what the assistant may do.

void load(appliedRef.current)} /> void load(appliedRef.current)} />
setDraft(e.target.value)} />
{loading ? (

Loading memory…

) : null} {error ? (

{error}

) : null} {note ? (

{note.text}

) : null} {decisions !== null && decisions.length === 0 && !error ? (

{applied ? 'Nothing matches.' : 'The assistant does not remember anything yet.'}

) : null} {groupDecisionsBySection(decisions ?? []).map(({ section, items }) => (

{SECTION_LABEL[section]} ({items.length})

    {items.map((decision) => { const open = expanded[decision.id] === true; const origin = decision.source ?? 'none'; const known = decision.sessionId ? sessions[decision.sessionId] !== undefined : false; return (
  • {decision.summary && !open ?
    {decision.summary}
    : null}
    {decision.importance} · {when(decision.updatedAt ?? decision.timestamp)}
    {decision.tags.length > 0 ?
    {decision.tags.join(', ')}
    : null} {open ? (
    {decision.content ?

    {decision.content}

    : null}
    {PROVENANCE[origin]} {decision.sessionId ? ` in conversation ${shortId(decision.sessionId)}` : ''}
    {decision.sessionId && known ? ( ) : null}
    ) : null} {confirming === decision.id ? (
    Forget “{decision.title}”? The assistant will no longer recall it.
    ) : (
    )}
  • ); })}
))} {companionId ? : null}
); } /** La memoria de sesión (M11) de la conversación del asistente: solo lectura, plegada. */ function ConversationMemory({ connected, sessionId }: { connected: boolean; sessionId: string }) { const native = useNative(); const [open, setOpen] = useState(false); const [memory, setMemory] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const alive = useRef(true); const requestSeq = useRef(0); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); const load = useCallback(async () => { const seq = ++requestSeq.current; setLoading(true); setError(null); try { const parsed = parseSessionMemory(await native.sessionMemory(sessionId)); if (!alive.current || seq !== requestSeq.current) return; if (parsed) setMemory(parsed); else setError(UNREADABLE); } catch (err) { if (alive.current && seq === requestSeq.current) setError(describeCommandError(toCommandError(err))); } finally { if (alive.current && seq === requestSeq.current) setLoading(false); } }, [native, sessionId]); useEffect(() => { if (open && connected) void load(); }, [open, connected, load]); const items = (memory?.items ?? []).filter((item) => item.status === 'active'); const summary = memory?.summary?.text ?? ''; return (

This conversation

{open ? ( ) : null}
{open ? ( <>

Kept only for this conversation; compacted from its older messages.

{loading ? (

Loading…

) : null} {error ? (

{error}

) : null} {memory && !error ? ( summary === '' && items.length === 0 ? (

Nothing compacted yet.

) : ( <> {summary !== '' ?

{summary}

: null}
    {items.map((item) => (
  • {item.kind} · {item.text}
  • ))}
) ) : null} {memory?.inherited && !error ? (

Carried over from the previous conversation

Archived when this conversation started; read only.{' '} {memory.inherited.fromSessionId}

{memory.inherited.summary ?

{memory.inherited.summary}

: null}
    {memory.inherited.items.map((item) => (
  • {item.kind} · {item.text}
  • ))}
) : null} ) : null}
); }