File size: 7,148 Bytes
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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 } from "./memoryApi";

export function MemoryPanel({ open, onClose, granted }: {
  open: boolean; onClose: () => void; granted: NavEntry[];
}) {
  const [entries, setEntries] = useState<MemoryEntry[]>([]);
  const [admin, setAdmin] = useState(false);
  const [loading, setLoading] = useState(true);
  const [loadProblem, setLoadProblem] = useState("");
  const [retry, setRetry] = useState(0);
  const [confirming, setConfirming] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [rowProblem, setRowProblem] = useState<{ id: string; text: string } | null>(null);
  const [status, setStatus] = useState("");
  const panelRef = useRef<HTMLElement | null>(null);
  const inFlight = 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([]); setAdmin(false); setLoading(true); setLoadProblem("");
    setConfirming(null); setBusy(null); setRowProblem(null); setStatus(""); inFlight.current = false;
    void Promise.all([fetchMemory(), me()]).then(([result, user]) => {
      if (generation.current !== current) return;
      setAdmin(isAdmin(user));
      if (result.ok) setEntries(result.value.entries);
      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]);

  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));
        setStatus("Memory erased.");
      } else {
        // Promotion copies the fact into company memory. Reload its server-owned identity.
        const refreshed = await fetchMemory();
        if (generation.current !== current) return;
        if (refreshed.ok) setEntries(refreshed.value.entries);
        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 <section className="as-memory" ref={panelRef} role="dialog" aria-label="Memory" tabIndex={-1}>
    <header className="as-memory-head">
      <h2>Memory</h2>
      <button type="button" className="as-memory-button" onClick={onClose}>Close</button>
    </header>
    <div className="as-memory-list" aria-busy={loading}>
      {loading ? <div className="as-memory-skeleton" role="status" aria-label="Loading memory" />
        : !loadProblem && !entries.length ? <p className="as-memory-empty">Nothing is remembered yet.</p> : null}
      {loadProblem ? <p className="as-memory-problem" role="status">{loadProblem}{" "}
        <button type="button" className="as-memory-button" onClick={() => setRetry((value) => value + 1)}>Try again</button>
      </p> : null}
      {groups.filter((group) => group.rows.length).map((group) => <section className="as-memory-group" key={group.title}
        aria-label={group.title}>
        <h3>{group.title}</h3>
        <ul>{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 <li className="as-memory-row" key={row.id} data-memory-id={row.id}>
            <p className="as-memory-text">{row.text}</p>
            <p className="as-memory-source">{sourceLabels.length ? `From ${sourceLabels.join(", ")}`
              : row.sources.length ? "From a database" : "From conversation"}</p>
            {writable ? <div className="as-memory-actions">
              {confirming === row.id ? <>
                <span>Erase this memory?</span>
                <button type="button" className="as-memory-button as-memory-erase" disabled={busy !== null}
                  onClick={() => void act(row, "erase")}>Erase</button>
                <button type="button" className="as-memory-button" disabled={busy !== null}
                  onClick={() => setConfirming(null)}>Cancel</button>
              </> : <>
                <button type="button" className="as-memory-button as-memory-erase" disabled={busy !== null}
                  onClick={() => { setConfirming(row.id); setRowProblem(null); }}>Erase</button>
                {admin && row.scope === "personal" ? <button type="button" className="as-memory-button"
                  disabled={busy !== null} onClick={() => void act(row, "share")}>Share with company</button> : null}
              </>}
            </div> : null}
            {rowProblem?.id === row.id ? <p className="as-memory-problem" role="status">{rowProblem.text}</p> : null}
          </li>;
        })}</ul>
      </section>)}
    </div>
    <p className="as-memory-status" role="status" aria-live="polite">{status}</p>
  </section>;
}