File size: 9,534 Bytes
89af3b2
 
 
 
8133df9
89af3b2
 
 
 
 
8133df9
 
 
 
 
89af3b2
 
 
 
 
 
 
 
 
 
8133df9
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
89af3b2
 
8133df9
89af3b2
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
89af3b2
 
 
8133df9
89af3b2
8133df9
 
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
89af3b2
 
 
 
8133df9
 
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
89af3b2
 
 
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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<MemoryEntry[]>([]);
  const [order, setOrder] = useState<MemoryOrder>("newest");
  const [total, setTotal] = useState(0);
  const [next, setNext] = useState<string | null>(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<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 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 <section className="as-memory" ref={panelRef} role="dialog" aria-label="Memory" tabIndex={-1}>
    <header className="as-memory-head">
      <h2>Memory</h2>
      <select className="as-memory-button" aria-label="Memory order" value={order} disabled={busy !== null}
        onChange={(event) => setOrder(event.target.value as MemoryOrder)}>
        <option value="newest">Newest first</option>
        <option value="oldest">Oldest first</option>
      </select>
      <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 ? null : !entries.length && !next ? <p className="as-memory-empty">Nothing is remembered yet.</p>
        : <p className="as-memory-source" data-memory-total={total} data-memory-shown={entries.length}>
          {next ? `Showing ${entries.length} of ${total}` : `${total} ${total === 1 ? "memory" : "memories"}`}</p>}
      {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>)}
      {!loading && next ? <div className="as-memory-actions">
        <button type="button" className="as-memory-button" data-memory-older="" disabled={more}
          onClick={() => void loadOlder()}>{more ? "Loading" : order === "newest" ? "Show older" : "Show newer"}</button>
      </div> : null}
      {moreProblem ? <p className="as-memory-problem" role="status">{moreProblem}</p> : null}
    </div>
    <p className="as-memory-status" role="status" aria-live="polite">{status}</p>
  </section>;
}