Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(memory): redesign the Memory section as a three-pane library (#1126)

Ruben Lütke5e9da56bbd79
diff --git a/dodaios/memory/vault/portable.py b/dodaios/memory/vault/portable.py
index 84755bac86..55efa8023a 100644
--- a/dodaios/memory/vault/portable.py
+++ b/dodaios/memory/vault/portable.py
@@ -210,7 +210,8 @@ def markdown_files(vault: MemoryVault) -> dict[str, str]:
details = []
if m.entities:
details.append(", ".join(m.entities))
- if m.valid_from:
+ # An imported memory's start date is the import, not when it became true.
+ if m.valid_from and m.origin != "imported":
details.append(f"since {m.valid_from[:10]}")
if m.valid_to:
details.append(f"until {m.valid_to[:10]}")
diff --git a/dodaios/memory/vault/runtime.py b/dodaios/memory/vault/runtime.py
index 0b9420e68e..3ff4499de3 100644
--- a/dodaios/memory/vault/runtime.py
+++ b/dodaios/memory/vault/runtime.py
@@ -87,6 +87,11 @@ def changed() -> None:
_cache.clear()
+def budget_chars(*, compact: bool = False) -> int:
+ """Characters the always-on block may use (voice gets the compact budget)."""
+ return _budgets["compact" if compact else "full"]
+
+
def prompt_block(*, compact: bool = False) -> str:
"""The always-on memory block, ``""`` while no vault runs or it is empty."""
vault = _active
diff --git a/dodaios/memory/vault/store.py b/dodaios/memory/vault/store.py
index 04a1dbc4e8..a16d4098fb 100644
--- a/dodaios/memory/vault/store.py
+++ b/dodaios/memory/vault/store.py
@@ -510,24 +510,24 @@ class MemoryVault:
hits.sort(key=lambda h: h.score, reverse=True)
return hits[:limit]
- def profile_block(self, *, max_chars: int = 2400, scope: str | None = None) -> str:
- """The always-on summary for the system prompt.
+ def profile_selection(
+ self, *, max_chars: int = 2400, scope: str | None = None
+ ) -> list[tuple[str, list[Memory]]]:
+ """Which memories the always-on block holds, as ``(section, memories)``.
Pinned memories first, then the stable kinds in a fixed order. Episodes
and sensitive memories stay out; they reach the model through search.
- A budget cut drops whole lines, oldest last-used first.
+ A budget cut drops whole lines, least used first.
"""
current = [
m
for m in self.list(scope=scope)
if m.sensitivity == "normal" and (m.pinned or m.kind in _PROFILE_ORDER)
]
- if not current:
- return ""
groups: dict[str, list[Memory]] = {}
for m in current:
groups.setdefault("pinned" if m.pinned else m.kind, []).append(m)
- lines: list[str] = []
+ sections: list[tuple[str, list[Memory]]] = []
budget = max_chars
for key in ("pinned", *_PROFILE_ORDER):
items = sorted(
@@ -540,17 +540,25 @@ class MemoryVault:
heading = f"{_PROFILE_HEADINGS[key]}:"
if len(heading) + 1 > budget:
break
- section = [heading]
+ chosen: list[Memory] = []
used = len(heading) + 1
for m in items:
line = f"- {m.text}"
if used + len(line) + 1 > budget:
break
- section.append(line)
+ chosen.append(m)
used += len(line) + 1
- if len(section) > 1:
- lines.extend(section)
+ if chosen:
+ sections.append((key, chosen))
budget -= used
+ return sections
+
+ def profile_block(self, *, max_chars: int = 2400, scope: str | None = None) -> str:
+ """The always-on summary for the system prompt (see :meth:`profile_selection`)."""
+ lines: list[str] = []
+ for key, memories in self.profile_selection(max_chars=max_chars, scope=scope):
+ lines.append(f"{_PROFILE_HEADINGS[key]}:")
+ lines.extend(f"- {m.text}" for m in memories)
return "\n".join(lines)
def stats(self) -> dict[str, Any]:
diff --git a/dodaios/ui/web/frontend/src/components/memoryVault/HowItWorks.tsx b/dodaios/ui/web/frontend/src/components/memoryVault/HowItWorks.tsx
new file mode 100644
index 0000000000..200ec99177
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/memoryVault/HowItWorks.tsx
@@ -0,0 +1,155 @@
+/**
+ * What reaches the model, drawn.
+ *
+ * your memory (all of it) ──▶ always in mind (a small, fixed block) ──▶ every conversation
+ * └──────────── looked up when a question needs it ─────────────────┘
+ *
+ * plus the way back: after a conversation one background pass compares what
+ * was said with what is stored and adds, updates or ends memories.
+ */
+import { ArrowRight, Brain, Compass, MessagesSquare, RefreshCcw, Search } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import type { VaultOverview } from "@/lib/personalMemoryApi";
+
+export function HowItWorks({
+ name,
+ overview,
+ onShowInMind,
+}: {
+ name: string;
+ overview: VaultOverview;
+ onShowInMind: () => void;
+}) {
+ const t = useT();
+ const used = overview.used_chars;
+ const budget = Math.max(1, overview.budget_chars);
+ const share = Math.min(1, used / budget);
+ const tokens = Math.round(used / 4);
+ const total = overview.stats.current;
+ const inMind = overview.in_mind_ids.length;
+
+ return (
+ <div data-testid="vault-how" className="h-full overflow-y-auto">
+ <div className="mx-auto max-w-[880px] px-6 py-10">
+ <p className="text-center text-[13px] text-muted-foreground">{t("vault.how_kicker")}</p>
+ <h2 className="mt-1 text-center text-[26px] font-semibold tracking-tight text-foreground-strong">
+ {fill(t("vault.how_title"), { name })}
+ </h2>
+
+ {/* The flow */}
+ <div className="mt-10 grid grid-cols-1 items-center gap-4 md:grid-cols-[1fr_auto_1.15fr_auto_1fr]">
+ <Node
+ icon={<Brain className="h-5 w-5" />}
+ tone="220 9% 56%"
+ title={t("vault.how_store")}
+ big={String(total)}
+ caption={t("vault.how_store_caption")}
+ />
+ <Arrow />
+ <button
+ type="button"
+ onClick={onShowInMind}
+ className="rounded-2xl border border-accent/40 bg-accent/[0.07] p-5 text-left transition-colors hover:bg-accent/[0.1] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <div className="flex items-center gap-2 text-accent">
+ <Compass className="h-5 w-5" />
+ <span className="text-[13px] font-semibold">{t("vault.shelf_in_mind")}</span>
+ </div>
+ <p className="mt-3 text-[30px] font-semibold leading-none tabular-nums text-foreground-strong">{inMind}</p>
+ <p className="mt-1 text-[12px] text-muted-foreground">{t("vault.how_in_mind_caption")}</p>
+ <div
+ className="mt-4 h-2 overflow-hidden rounded-full bg-sheen/[0.08]"
+ role="meter"
+ aria-valuemin={0}
+ aria-valuemax={budget}
+ aria-valuenow={used}
+ aria-label={t("vault.how_budget")}
+ >
+ <div className="h-full rounded-full bg-accent motion-safe:transition-[width]" style={{ width: `${share * 100}%` }} />
+ </div>
+ <p className="mt-1.5 text-[11px] tabular-nums text-muted-foreground">
+ {fill(t("vault.how_budget_line"), { used, budget, tokens })}
+ </p>
+ </button>
+ <Arrow />
+ <Node
+ icon={<MessagesSquare className="h-5 w-5" />}
+ tone="142 58% 46%"
+ title={t("vault.how_conversation")}
+ big="∞"
+ caption={fill(t("vault.how_conversation_caption"), { name })}
+ />
+ </div>
+
+ {/* The lookup path */}
+ <div className="relative mx-auto mt-4 hidden h-10 md:block" aria-hidden>
+ <svg className="absolute inset-0 h-full w-full" preserveAspectRatio="none" viewBox="0 0 100 40">
+ <path d="M14 0 V24 Q14 32 22 32 H78 Q86 32 86 24 V0" fill="none" stroke="hsl(var(--border-strong))" strokeDasharray="3 3" vectorEffect="non-scaling-stroke" />
+ </svg>
+ </div>
+ <div className="mx-auto mt-1 flex max-w-[520px] items-start gap-3 rounded-xl border border-dashed border-border-strong bg-sheen/[0.02] p-4">
+ <Search className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div>
+ <p className="text-[13px] font-medium text-foreground">{t("vault.how_lookup")}</p>
+ <p className="mt-0.5 text-[12px] leading-relaxed text-muted-foreground">{fill(t("vault.how_lookup_body"), { name })}</p>
+ </div>
+ </div>
+
+ {/* The way back */}
+ <div className="mt-12 grid gap-3 md:grid-cols-3">
+ <Step n={1} title={t("vault.how_learn_1")} body={t("vault.how_learn_1_body")} />
+ <Step n={2} title={t("vault.how_learn_2")} body={t("vault.how_learn_2_body")} />
+ <Step n={3} title={t("vault.how_learn_3")} body={t("vault.how_learn_3_body")} />
+ </div>
+ <p className="mt-6 flex items-center justify-center gap-2 text-center text-[12px] text-muted-foreground">
+ <RefreshCcw className="h-3.5 w-3.5" /> {t("vault.how_footer")}
+ </p>
+ </div>
+ </div>
+ );
+}
+
+function Node({
+ icon,
+ tone,
+ title,
+ big,
+ caption,
+}: {
+ icon: React.ReactNode;
+ tone: string;
+ title: string;
+ big: string;
+ caption: string;
+}) {
+ return (
+ <div className="rounded-2xl border border-border bg-sheen/[0.02] p-5">
+ <div className="flex items-center gap-2" style={{ color: `hsl(${tone})` }}>
+ {icon}
+ <span className="text-[13px] font-semibold text-foreground">{title}</span>
+ </div>
+ <p className="mt-3 text-[30px] font-semibold leading-none tabular-nums text-foreground-strong">{big}</p>
+ <p className="mt-1 text-[12px] leading-relaxed text-muted-foreground">{caption}</p>
+ </div>
+ );
+}
+
+function Arrow() {
+ return (
+ <div className="flex justify-center text-faint-foreground" aria-hidden>
+ <ArrowRight className="h-5 w-5 rotate-90 md:rotate-0" />
+ </div>
+ );
+}
+
+function Step({ n, title, body }: { n: number; title: string; body: string }) {
+ return (
+ <div className="rounded-2xl border border-border p-4">
+ <span className="flex h-6 w-6 items-center justify-center rounded-full bg-sheen/[0.08] text-[12px] font-semibold text-foreground">
+ {n}
+ </span>
+ <p className="mt-3 text-[13px] font-medium text-foreground">{title}</p>
+ <p className="mt-1 text-[12px] leading-relaxed text-muted-foreground">{body}</p>
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/memoryVault/MemoryBrowser.tsx b/dodaios/ui/web/frontend/src/components/memoryVault/MemoryBrowser.tsx
new file mode 100644
index 0000000000..e989e64ce3
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/memoryVault/MemoryBrowser.tsx
@@ -0,0 +1,486 @@
+/**
+ * The memories list and the inspector beside it.
+ *
+ * A row is one sentence with its kind's glyph; a blue compass marks the
+ * memories the assistant carries into every conversation. The inspector
+ * explains one memory: what it says, where it came from (with the user's own
+ * words when it was learned), every earlier version, and what can be done.
+ */
+import { useEffect, useMemo, useState, type FormEvent } from "react";
+import { Check, CircleOff, Compass, Pencil, Pin, PinOff, Quote, Search, Trash2, X } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import { ConfirmDialog } from "@/components/memory/MemoryDialogs";
+import {
+ editMemory,
+ endMemory,
+ forgetMemory,
+ pinMemory,
+ useVaultHistory,
+ type MemoryKind,
+ type VaultMemory,
+} from "@/lib/personalMemoryApi";
+import { KIND_STYLE, kindColor } from "./kinds";
+
+export type Shelf = "all" | "in_mind" | "pinned" | "history" | MemoryKind;
+
+export function formatDay(stamp: string | null | undefined): string {
+ if (!stamp) return "";
+ const date = new Date(stamp);
+ if (Number.isNaN(date.getTime())) return stamp.slice(0, 10);
+ return date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
+}
+
+export function MemoryBrowser({
+ shelf,
+ query,
+ items,
+ loading,
+ inMind,
+ name,
+ onChanged,
+ notify,
+ onAdd,
+}: {
+ shelf: Shelf;
+ query: string;
+ items: VaultMemory[];
+ loading: boolean;
+ inMind: Set<string>;
+ name: string;
+ onChanged: () => Promise<unknown>;
+ notify: (message: string) => void;
+ onAdd: () => void;
+}) {
+ const t = useT();
+ const rows = useMemo(() => {
+ switch (shelf) {
+ case "all":
+ return items;
+ case "in_mind":
+ return items.filter((m) => inMind.has(m.id));
+ case "pinned":
+ return items.filter((m) => m.pinned && m.current);
+ case "history":
+ return items.filter((m) => !m.current);
+ default:
+ return items.filter((m) => m.kind === shelf);
+ }
+ }, [items, shelf, inMind]);
+
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const selected = rows.find((m) => m.id === selectedId) ?? rows[0] ?? null;
+ useEffect(() => {
+ if (selectedId && !rows.some((m) => m.id === selectedId)) setSelectedId(null);
+ }, [rows, selectedId]);
+ // Escape closes the slide-over inspector of a narrow window.
+ useEffect(() => {
+ if (!selectedId) return;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape" && window.matchMedia("(max-width: 1023px)").matches) setSelectedId(null);
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [selectedId]);
+
+ const move = (step: number) => {
+ if (!rows.length) return;
+ const index = Math.max(0, rows.findIndex((m) => m.id === selected?.id));
+ const next = rows[Math.min(rows.length - 1, Math.max(0, index + step))];
+ setSelectedId(next.id);
+ document.getElementById(`vault-row-${next.id}`)?.scrollIntoView({ block: "nearest" });
+ };
+
+ if (!loading && rows.length === 0) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 px-8 text-center">
+ <span className="flex h-12 w-12 items-center justify-center rounded-2xl bg-sheen/[0.06] text-muted-foreground">
+ {query ? <Search className="h-5 w-5" /> : <Compass className="h-5 w-5" />}
+ </span>
+ <p className="text-[15px] font-medium text-foreground-strong">
+ {query ? t("vault.no_results") : shelf === "history" ? t("vault.history_empty") : t("vault.empty_title")}
+ </p>
+ {!query && shelf !== "history" && (
+ <>
+ <p className="max-w-[360px] text-[13px] leading-relaxed text-muted-foreground">
+ {fill(t("vault.empty_body"), { name })}
+ </p>
+ <Button size="sm" onClick={onAdd}>
+ {t("vault.add")}
+ </Button>
+ </>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="grid h-full min-h-0 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(320px,400px)]">
+ <ul
+ role="listbox"
+ aria-label={t("vault.mode_memories")}
+ tabIndex={0}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ move(1);
+ } else if (event.key === "ArrowUp") {
+ event.preventDefault();
+ move(-1);
+ }
+ }}
+ className="min-h-0 overflow-y-auto px-2 py-2 focus-visible:outline-none"
+ >
+ {rows.map((memory) => (
+ <Row
+ key={memory.id}
+ memory={memory}
+ inMind={inMind.has(memory.id)}
+ selected={memory.id === selected?.id}
+ onSelect={() => setSelectedId(memory.id)}
+ />
+ ))}
+ </ul>
+ <div className="hidden min-h-0 border-l border-border lg:block">
+ {selected && (
+ <Inspector
+ key={selected.id}
+ memory={selected}
+ inMind={inMind.has(selected.id)}
+ name={name}
+ onChanged={onChanged}
+ notify={notify}
+ />
+ )}
+ </div>
+ {/* Narrow windows: the inspector slides in over the list. */}
+ {selectedId && selected && (
+ <div className="fixed inset-0 z-[60] flex justify-end bg-scrim/30 lg:hidden" onClick={() => setSelectedId(null)}>
+ <div
+ className="relative h-full w-[min(420px,92vw)] border-l border-border bg-card shadow-float motion-safe:animate-in motion-safe:slide-in-from-right-4"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <button
+ type="button"
+ aria-label={t("vault.close")}
+ onClick={() => setSelectedId(null)}
+ className="absolute right-3 top-3 z-10 flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground hover:bg-sheen/[0.08] hover:text-foreground"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ <Inspector
+ key={selected.id}
+ memory={selected}
+ inMind={inMind.has(selected.id)}
+ name={name}
+ onChanged={onChanged}
+ notify={notify}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function Row({
+ memory,
+ inMind,
+ selected,
+ onSelect,
+}: {
+ memory: VaultMemory;
+ inMind: boolean;
+ selected: boolean;
+ onSelect: () => void;
+}) {
+ const t = useT();
+ const style = KIND_STYLE[memory.kind];
+ const Icon = style.icon;
+ return (
+ <li
+ id={`vault-row-${memory.id}`}
+ role="option"
+ aria-selected={selected}
+ data-testid="vault-row"
+ onClick={onSelect}
+ className={cn(
+ "group flex cursor-default items-start gap-3 rounded-xl px-3 py-2.5 transition-colors",
+ selected ? "bg-accent-soft" : "hover:bg-sheen/[0.04]",
+ !memory.current && "opacity-60",
+ )}
+ >
+ <span
+ className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg"
+ style={{ backgroundColor: kindColor(memory.kind, 0.14), color: kindColor(memory.kind) }}
+ >
+ <Icon className="h-3.5 w-3.5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className={cn("line-clamp-2 text-[13px] leading-snug text-foreground", !memory.current && "line-through")}>
+ {memory.text}
+ </p>
+ <p className="mt-0.5 truncate text-[11px] text-muted-foreground">
+ {t(`vault.kind_${memory.kind}`)}
+ {memory.entities.length > 0 && ` · ${memory.entities.join(", ")}`}
+ </p>
+ </div>
+ <span className="mt-1 flex shrink-0 items-center gap-1 text-muted-foreground">
+ {memory.pinned && <Pin className="h-3 w-3 text-[hsl(4_86%_58%)]" aria-label={t("vault.pinned")} />}
+ {inMind && <Compass className="h-3.5 w-3.5 text-accent" aria-label={t("vault.shelf_in_mind")} />}
+ </span>
+ </li>
+ );
+}
+
+function Inspector({
+ memory,
+ inMind,
+ name,
+ onChanged,
+ notify,
+}: {
+ memory: VaultMemory;
+ inMind: boolean;
+ name: string;
+ onChanged: () => Promise<unknown>;
+ notify: (message: string) => void;
+}) {
+ const t = useT();
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(memory.text);
+ const [forgetting, setForgetting] = useState(false);
+ const history = useVaultHistory(memory.id);
+ const versions = history.data?.versions ?? [];
+ const Icon = KIND_STYLE[memory.kind].icon;
+ const evidence = typeof memory.source?.evidence === "string" ? memory.source.evidence.trim() : "";
+ const sourceFile = typeof memory.source?.file === "string" ? memory.source.file : "";
+
+ const act = async (work: () => Promise<unknown>, done: string) => {
+ try {
+ await work();
+ await onChanged();
+ notify(done);
+ } catch (error) {
+ notify(error instanceof Error ? error.message : String(error));
+ }
+ };
+
+ const save = async (event: FormEvent) => {
+ event.preventDefault();
+ const value = draft.trim();
+ setEditing(false);
+ if (value && value !== memory.text) await act(() => editMemory(memory.id, value), t("vault.updated"));
+ };
+
+ return (
+ <div data-testid="vault-inspector" className="flex h-full min-h-0 flex-col overflow-y-auto px-6 py-6">
+ <div className="flex items-center gap-2">
+ <span
+ className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-medium"
+ style={{ backgroundColor: kindColor(memory.kind, 0.14), color: kindColor(memory.kind) }}
+ >
+ <Icon className="h-3 w-3" />
+ {t(`vault.kind_${memory.kind}`)}
+ </span>
+ {memory.sensitivity === "sensitive" && (
+ <span className="rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground">
+ {t("vault.sensitive")}
+ </span>
+ )}
+ </div>
+
+ {editing ? (
+ <form onSubmit={save} className="mt-4">
+ <textarea
+ autoFocus
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") setEditing(false);
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ void save(event);
+ }
+ }}
+ rows={3}
+ aria-label={t("vault.edit")}
+ className="w-full resize-none rounded-xl border border-border-strong bg-background p-3 text-[17px] leading-snug text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ <div className="mt-2 flex gap-2">
+ <Button type="submit" size="sm">
+ <Check /> {t("vault.save")}
+ </Button>
+ <Button type="button" size="sm" variant="ghost" onClick={() => setEditing(false)}>
+ {t("vault.cancel")}
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <p
+ className={cn(
+ "mt-4 text-[20px] font-medium leading-snug tracking-tight text-foreground-strong",
+ !memory.current && "text-muted-foreground line-through",
+ )}
+ >
+ {memory.text}
+ </p>
+ )}
+
+ {/* Where it lives in the model's head */}
+ <div
+ className={cn(
+ "mt-5 flex items-start gap-3 rounded-xl border p-3",
+ inMind ? "border-accent/30 bg-accent/[0.06]" : "border-border bg-sheen/[0.02]",
+ )}
+ >
+ {inMind ? (
+ <Compass className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
+ ) : (
+ <Search className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ )}
+ <div>
+ <p className="text-[13px] font-medium text-foreground">
+ {memory.current ? (inMind ? t("vault.status_in_mind") : t("vault.status_lookup")) : t("vault.status_closed")}
+ </p>
+ <p className="mt-0.5 text-[12px] leading-relaxed text-muted-foreground">
+ {fill(
+ memory.current ? (inMind ? t("vault.status_in_mind_hint") : t("vault.status_lookup_hint")) : t("vault.status_closed_hint"),
+ { name },
+ )}
+ </p>
+ </div>
+ </div>
+
+ {/* Origin */}
+ <Section title={t("vault.origin_title")}>
+ <p className="text-[13px] text-foreground">
+ {t(`vault.origin_long_${memory.origin}`)}
+ <span className="text-muted-foreground"> · {formatDay(memory.recorded_at)}</span>
+ </p>
+ {evidence && (
+ <blockquote className="mt-2 flex gap-2 rounded-lg bg-sheen/[0.04] p-2.5 text-[12px] italic leading-relaxed text-foreground-secondary">
+ <Quote className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />
+ {evidence}
+ </blockquote>
+ )}
+ {sourceFile && <p className="mt-1.5 font-mono text-[11px] text-muted-foreground">{sourceFile}</p>}
+ </Section>
+
+ {memory.entities.length > 0 && (
+ <Section title={t("vault.entities_title")}>
+ <div className="flex flex-wrap gap-1.5">
+ {memory.entities.map((entity) => (
+ <span key={entity} className="rounded-full bg-sheen/[0.06] px-2.5 py-1 text-[12px] text-foreground">
+ {entity}
+ </span>
+ ))}
+ </div>
+ </Section>
+ )}
+
+ {/* Timeline */}
+ {versions.length > 1 && (
+ <Section title={t("vault.timeline_title")}>
+ <ol className="relative ml-1.5 border-l border-border" data-testid="vault-versions">
+ {versions.map((version) => (
+ <li key={version.id} className="relative pb-3 pl-4 last:pb-0">
+ <span
+ className={cn(
+ "absolute -left-[5px] top-1.5 h-2.5 w-2.5 rounded-full border-2 border-card",
+ version.current ? "bg-accent" : "bg-muted-foreground/50",
+ )}
+ />
+ <p className="text-[11px] text-muted-foreground">
+ {formatDay(version.valid_from)}
+ {version.valid_to && ` – ${formatDay(version.valid_to)}`}
+ {version.current && <span className="ml-1.5 font-medium text-accent">{t("vault.now")}</span>}
+ </p>
+ <p className={cn("text-[13px]", version.current ? "text-foreground" : "text-muted-foreground")}>
+ {version.text}
+ </p>
+ </li>
+ ))}
+ </ol>
+ </Section>
+ )}
+
+ {/* Actions */}
+ <div className="mt-auto flex flex-wrap gap-1.5 pt-6">
+ {memory.current && (
+ <>
+ <Action
+ icon={memory.pinned ? <PinOff /> : <Pin />}
+ label={memory.pinned ? t("vault.unpin") : t("vault.pin")}
+ onClick={() => act(() => pinMemory(memory.id, !memory.pinned), memory.pinned ? t("vault.unpinned") : t("vault.pinned_done"))}
+ />
+ <Action
+ icon={<Pencil />}
+ label={t("vault.edit")}
+ onClick={() => {
+ setDraft(memory.text);
+ setEditing(true);
+ }}
+ />
+ <Action icon={<CircleOff />} label={t("vault.end")} onClick={() => act(() => endMemory(memory.id), t("vault.ended"))} />
+ </>
+ )}
+ <Action icon={<Trash2 />} label={t("vault.forget")} danger onClick={() => setForgetting(true)} />
+ </div>
+
+ <ConfirmDialog
+ open={forgetting}
+ title={t("vault.forget_title")}
+ description={fill(t("vault.forget_body"), { name })}
+ confirmLabel={t("vault.forget")}
+ items={[memory.text]}
+ onClose={() => setForgetting(false)}
+ onConfirm={async () => {
+ await forgetMemory(memory.id);
+ setForgetting(false);
+ await onChanged();
+ notify(t("vault.forgotten"));
+ }}
+ />
+ </div>
+ );
+}
+
+function Section({ title, children }: { title: string; children: React.ReactNode }) {
+ return (
+ <section className="mt-6">
+ <h3 className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-faint-foreground">{title}</h3>
+ {children}
+ </section>
+ );
+}
+
+function Action({
+ icon,
+ label,
+ onClick,
+ danger = false,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ onClick: () => void;
+ danger?: boolean;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-[12px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&>svg]:h-3.5 [&>svg]:w-3.5",
+ danger
+ ? "text-destructive hover:border-destructive/40 hover:bg-destructive/10"
+ : "text-foreground hover:bg-sheen/[0.05]",
+ )}
+ >
+ {icon}
+ {label}
+ </button>
+ );
+}
+
diff --git a/dodaios/ui/web/frontend/src/components/memoryVault/MemoryFiles.tsx b/dodaios/ui/web/frontend/src/components/memoryVault/MemoryFiles.tsx
new file mode 100644
index 0000000000..3e3d512f04
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/memoryVault/MemoryFiles.tsx
@@ -0,0 +1,192 @@
+/**
+ * The memory as files: the Markdown an export writes, one document per kind
+ * plus the MEMORY.md index. Click (or Space) opens a large preview; arrow
+ * keys move between files while it is open, Escape closes it.
+ */
+import { useCallback, useEffect, useMemo, useState } from "react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { ChevronLeft, ChevronRight, Download, FileText, Loader2, X } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { exportUrl, useVaultFiles, type VaultFile } from "@/lib/personalMemoryApi";
+import { KIND_STYLE } from "./kinds";
+
+function hueOf(file: VaultFile): string {
+ return file.kind === "index" ? "220 9% 56%" : KIND_STYLE[file.kind].hue;
+}
+
+function size(bytes: number): string {
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
+}
+
+/** Frontmatter and the id comments are for re-import, not for reading. */
+function readable(content: string): string {
+ const body = content.replace(/^---[\s\S]*?\n---\n/, "");
+ // Cut each line at its id comment; the preview renders no HTML at all either.
+ return body
+ .split("\n")
+ .map((line) => {
+ const at = line.indexOf("<!--");
+ return at >= 0 ? line.slice(0, at).trimEnd() : line;
+ })
+ .join("\n");
+}
+
+export function MemoryFiles() {
+ const t = useT();
+ const query = useVaultFiles();
+ const files = useMemo(() => query.data?.files ?? [], [query.data]);
+ const [open, setOpen] = useState<number | null>(null);
+ const [focus, setFocus] = useState(0);
+
+ const step = useCallback(
+ (delta: number) => setOpen((index) => (index === null ? index : (index + delta + files.length) % files.length)),
+ [files.length],
+ );
+
+ useEffect(() => {
+ if (open === null) return;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape" || event.key === " ") {
+ event.preventDefault();
+ setOpen(null);
+ } else if (event.key === "ArrowRight" || event.key === "ArrowDown") {
+ event.preventDefault();
+ step(1);
+ } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
+ event.preventDefault();
+ step(-1);
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [open, step]);
+
+ if (query.isLoading) {
+ return (
+ <div className="flex h-full items-center justify-center text-muted-foreground">
+ <Loader2 className="h-5 w-5 animate-spin" />
+ </div>
+ );
+ }
+
+ const current = open === null ? null : files[open];
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="flex items-center gap-2 border-b border-border px-5 py-2.5 text-[12px] text-muted-foreground">
+ <FileText className="h-3.5 w-3.5" />
+ <span className="truncate">{t("vault.files_hint")}</span>
+ <a
+ href={exportUrl("markdown")}
+ download
+ className="ml-auto inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 font-medium text-accent hover:bg-accent/10"
+ >
+ <Download className="h-3.5 w-3.5" /> {t("vault.export_markdown")}
+ </a>
+ </div>
+ <div
+ role="grid"
+ tabIndex={0}
+ aria-label={t("vault.mode_files")}
+ data-testid="vault-files"
+ onKeyDown={(event) => {
+ if (event.key === " " || event.key === "Enter") {
+ event.preventDefault();
+ setOpen(focus);
+ } else if (event.key === "ArrowRight") setFocus((i) => Math.min(files.length - 1, i + 1));
+ else if (event.key === "ArrowLeft") setFocus((i) => Math.max(0, i - 1));
+ }}
+ className="grid min-h-0 flex-1 auto-rows-min grid-cols-[repeat(auto-fill,minmax(132px,1fr))] gap-2 overflow-y-auto p-6 focus-visible:outline-none"
+ >
+ {files.map((file, index) => (
+ <button
+ key={file.name}
+ type="button"
+ role="gridcell"
+ data-testid="vault-file"
+ onClick={() => {
+ setFocus(index);
+ setOpen(index);
+ }}
+ className={cn(
+ "group flex flex-col items-center gap-2 rounded-xl p-3 text-center transition-colors focus-visible:outline-none",
+ focus === index ? "bg-accent-soft" : "hover:bg-sheen/[0.04]",
+ )}
+ >
+ <Document hue={hueOf(file)} label={file.kind === "index" ? "INDEX" : "MD"} />
+ <span className="w-full truncate text-[12px] font-medium text-foreground">{file.name}</span>
+ <span className="-mt-1.5 text-[11px] text-muted-foreground">
+ {fill(t("vault.file_meta"), { size: size(file.bytes), lines: file.lines })}
+ </span>
+ </button>
+ ))}
+ </div>
+
+ {current && (
+ <div
+ className="fixed inset-0 z-[80] flex items-center justify-center bg-scrim/45 p-6 backdrop-blur-sm motion-safe:animate-in motion-safe:fade-in-0"
+ onClick={() => setOpen(null)}
+ >
+ <div
+ role="dialog"
+ aria-label={current.name}
+ data-testid="vault-quicklook"
+ onClick={(event) => event.stopPropagation()}
+ className="flex max-h-[86vh] w-[min(760px,100%)] flex-col overflow-hidden rounded-2xl border border-border-strong bg-popover shadow-float motion-safe:animate-in motion-safe:zoom-in-95"
+ >
+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-border px-3">
+ <button
+ type="button"
+ aria-label={t("vault.close")}
+ onClick={() => setOpen(null)}
+ className="flex h-6 w-6 items-center justify-center rounded-full text-muted-foreground hover:bg-sheen/[0.08] hover:text-foreground"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: `hsl(${hueOf(current)})` }} />
+ <span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground-strong">{current.name}</span>
+ <button
+ type="button"
+ aria-label={t("vault.previous")}
+ onClick={() => step(-1)}
+ className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-sheen/[0.08]"
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </button>
+ <button
+ type="button"
+ aria-label={t("vault.next")}
+ onClick={() => step(1)}
+ className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-sheen/[0.08]"
+ >
+ <ChevronRight className="h-4 w-4" />
+ </button>
+ </div>
+ <article className="vault-markdown min-h-0 overflow-y-auto px-8 py-6 text-[14px] leading-relaxed text-foreground [&_a]:text-accent [&_em]:text-muted-foreground [&_h1]:mb-4 [&_h1]:text-[22px] [&_h1]:font-semibold [&_h1]:text-foreground-strong [&_li]:my-1.5 [&_ul]:list-disc [&_ul]:pl-5">
+ <ReactMarkdown remarkPlugins={[remarkGfm]} skipHtml>{readable(current.content)}</ReactMarkdown>
+ </article>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** A page with a folded corner and a coloured band: one file at a glance. */
+function Document({ hue, label }: { hue: string; label: string }) {
+ return (
+ <svg viewBox="0 0 64 80" className="h-20 w-16 drop-shadow-sm transition-transform group-hover:-translate-y-0.5" aria-hidden>
+ <path d="M6 2h38l18 18v54a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4z" fill="hsl(var(--surface-raised))" stroke="hsl(var(--border-strong))" />
+ <path d="M44 2v14a4 4 0 0 0 4 4h14" fill="hsl(var(--secondary))" stroke="hsl(var(--border-strong))" />
+ {[30, 37, 44, 51].map((y, i) => (
+ <rect key={y} x="11" y={y} width={i === 3 ? 26 : 42} height="2.5" rx="1.25" fill="hsl(var(--muted-foreground) / 0.35)" />
+ ))}
+ <path d="M2 60h60v14a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z" fill={`hsl(${hue})`} />
+ <text x="32" y="73" textAnchor="middle" fontSize="9" fontWeight="700" fill="white" fontFamily="Inter, system-ui, sans-serif">
+ {label}
+ </text>
+ </svg>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/memoryVault/NewMemorySheet.tsx b/dodaios/ui/web/frontend/src/components/memoryVault/NewMemorySheet.tsx
new file mode 100644
index 0000000000..26701aa07c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/memoryVault/NewMemorySheet.tsx
@@ -0,0 +1,142 @@
+/**
+ * Add a memory: one sentence, and optionally its kind (picked as coloured
+ * chips; left alone, the app picks). Enter saves, Escape closes.
+ */
+import { useEffect, useState, type FormEvent } from "react";
+import * as Dialog from "@radix-ui/react-dialog";
+import { Loader2, Wand2 } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import { MEMORY_KINDS, addMemory, type MemoryKind } from "@/lib/personalMemoryApi";
+import { KIND_STYLE } from "./kinds";
+
+export function NewMemorySheet({
+ open,
+ name,
+ onClose,
+ onSaved,
+ onError,
+}: {
+ open: boolean;
+ name: string;
+ onClose: () => void;
+ onSaved: (message: string) => Promise<void>;
+ onError: (message: string) => void;
+}) {
+ const t = useT();
+ const [text, setText] = useState("");
+ const [kind, setKind] = useState<MemoryKind | "">("");
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ if (open) {
+ setText("");
+ setKind("");
+ }
+ }, [open]);
+
+ const submit = async (event?: FormEvent) => {
+ event?.preventDefault();
+ const value = text.trim();
+ if (!value || busy) return;
+ setBusy(true);
+ try {
+ const result = await addMemory(value, kind);
+ await onSaved(result.action === "existing" ? t("vault.already_known") : t("vault.saved"));
+ } catch (error) {
+ onError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Dialog.Root open={open} onOpenChange={(next) => !next && !busy && onClose()}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-scrim/40 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=open]:fade-in-0" />
+ <Dialog.Content
+ data-testid="vault-new-sheet"
+ className="fixed left-1/2 top-[14%] z-[90] w-[min(560px,calc(100vw-2rem))] -translate-x-1/2 rounded-2xl border border-border-strong bg-popover p-5 text-popover-foreground shadow-float data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:slide-in-from-top-2"
+ >
+ <Dialog.Title className="text-[15px] font-semibold text-foreground-strong">{t("vault.add_title")}</Dialog.Title>
+ <Dialog.Description className="mt-1 text-[12px] text-muted-foreground">
+ {fill(t("vault.add_hint"), { name })}
+ </Dialog.Description>
+ <form onSubmit={submit} className="mt-4">
+ <textarea
+ autoFocus
+ value={text}
+ maxLength={2000}
+ rows={3}
+ onChange={(event) => setText(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ void submit();
+ }
+ }}
+ placeholder={t("vault.composer_placeholder")}
+ aria-label={t("vault.composer_placeholder")}
+ className="w-full resize-none rounded-xl border border-border bg-background p-3 text-[15px] leading-snug text-foreground placeholder:text-faint-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ <div className="mt-3 flex flex-wrap gap-1.5" role="radiogroup" aria-label={t("vault.kind_label")}>
+ <Chip active={kind === ""} onClick={() => setKind("")} hue="220 9% 56%" icon={<Wand2 />}>
+ {t("vault.kind_auto")}
+ </Chip>
+ {MEMORY_KINDS.filter((k) => k !== "ephemeral").map((k) => {
+ const Icon = KIND_STYLE[k].icon;
+ return (
+ <Chip key={k} active={kind === k} onClick={() => setKind(k)} hue={KIND_STYLE[k].hue} icon={<Icon />}>
+ {t(`vault.kind_${k}`)}
+ </Chip>
+ );
+ })}
+ </div>
+ <div className="mt-5 flex justify-end gap-2">
+ <Button type="button" variant="ghost" size="sm" onClick={onClose} disabled={busy}>
+ {t("vault.cancel")}
+ </Button>
+ <Button type="submit" size="sm" disabled={!text.trim() || busy}>
+ {busy && <Loader2 className="animate-spin" />}
+ {t("vault.remember")}
+ </Button>
+ </div>
+ </form>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
+
+function Chip({
+ active,
+ onClick,
+ hue,
+ icon,
+ children,
+}: {
+ active: boolean;
+ onClick: () => void;
+ hue: string;
+ icon: React.ReactNode;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={active}
+ onClick={onClick}
+ className={cn(
+ "inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-[12px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&>svg]:h-3 [&>svg]:w-3",
+ active ? "border-transparent" : "border-border text-muted-foreground hover:text-foreground",
+ )}
+ style={active ? { backgroundColor: `hsl(${hue} / 0.16)`, color: `hsl(${hue})` } : undefined}
+ >
+ {icon}
+ {children}
+ </button>
+ );
+}
+
diff --git a/dodaios/ui/web/frontend/src/components/memoryVault/Portability.tsx b/dodaios/ui/web/frontend/src/components/memoryVault/Portability.tsx
new file mode 100644
index 0000000000..4c5ccc7e8b
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/memoryVault/Portability.tsx
@@ -0,0 +1,55 @@
+/**
+ * The sidebar's foot: take the memory along (one zip) or bring one in.
+ */
+import { useRef, useState } from "react";
+import { Download, Loader2, Upload } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { exportUrl, importBundle } from "@/lib/personalMemoryApi";
+
+export function Portability({
+ onDone,
+ onError,
+}: {
+ onDone: (message: string) => void;
+ onError: (message: string) => void;
+}) {
+ const t = useT();
+ const fileRef = useRef<HTMLInputElement>(null);
+ const [busy, setBusy] = useState(false);
+
+ const pick = async (file: File | undefined) => {
+ if (!file) return;
+ setBusy(true);
+ try {
+ const report = await importBundle(file);
+ onDone(fill(t("vault.import_done"), { added: report.added, skipped: report.skipped }));
+ } catch (error) {
+ onError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setBusy(false);
+ if (fileRef.current) fileRef.current.value = "";
+ }
+ };
+
+ const item =
+ "flex h-8 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-[12px] text-muted-foreground transition-colors hover:bg-sheen/[0.05] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
+
+ return (
+ <div className="border-t border-border p-2">
+ <p className="px-2.5 pb-1 pt-1 text-[11px] leading-snug text-faint-foreground">{t("vault.portable_hint")}</p>
+ <a href={exportUrl("bundle")} download data-testid="vault-export-bundle" className={item}>
+ <Download className="h-3.5 w-3.5" /> {t("vault.export_bundle")}
+ </a>
+ <button type="button" className={item} disabled={busy} onClick={() => fileRef.current?.click()} data-testid="vault-import">
+ {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Upload className="h-3.5 w-3.5" />} {t("vault.import")}
+ </button>
+ <input
+ ref={fileRef}
+ type="file"
+ accept=".zip,application/zip"
+ className="hidden"
+ onChange={(event) => void pick(event.target.files?.[0])}
+ />
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/memoryVault/kinds.ts b/dodaios/ui/web/frontend/src/components/memoryVault/kinds.ts
new file mode 100644
index 0000000000..c64e87a445
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/memoryVault/kinds.ts
@@ -0,0 +1,41 @@
+/**
+ * One colour and one glyph per kind of memory. The colours are calm system
+ * hues that read on both themes; every surface that shows a kind (sidebar,
+ * row, inspector, file) takes them from here.
+ */
+import {
+ CalendarClock,
+ Compass,
+ Heart,
+ type LucideIcon,
+ MapPin,
+ Rocket,
+ ScrollText,
+ Sparkles,
+ UserRound,
+ Users,
+} from "lucide-react";
+import type { MemoryKind } from "@/lib/personalMemoryApi";
+
+export interface KindStyle {
+ icon: LucideIcon;
+ /** An `H S% L%` triple, used as `hsl(...)` with or without alpha. */
+ hue: string;
+}
+
+export const KIND_STYLE: Record<MemoryKind, KindStyle> = {
+ profile: { icon: UserRound, hue: "211 100% 58%" },
+ preference: { icon: Heart, hue: "340 82% 60%" },
+ relationship: { icon: Users, hue: "28 95% 56%" },
+ project: { icon: Rocket, hue: "266 70% 64%" },
+ procedural: { icon: ScrollText, hue: "142 58% 46%" },
+ episode: { icon: Sparkles, hue: "45 95% 52%" },
+ reference: { icon: MapPin, hue: "187 72% 46%" },
+ ephemeral: { icon: CalendarClock, hue: "220 9% 56%" },
+};
+
+export const IN_MIND_STYLE: KindStyle = { icon: Compass, hue: "211 100% 58%" };
+
+export function kindColor(kind: MemoryKind, alpha = 1): string {
+ return `hsl(${KIND_STYLE[kind].hue} / ${alpha})`;
+}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/memory/de.json b/dodaios/ui/web/frontend/src/i18n/locales/memory/de.json
index f63c1d5a40..a72cfdd973 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/memory/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/memory/de.json
@@ -258,6 +258,60 @@
"export_bundle": "Gedächtnis exportieren (.zip)",
"export_markdown": "Als Markdown exportieren",
"import": "Gedächtnis-Datei importieren",
- "import_done": "{added} Erinnerungen importiert, {skipped} waren schon bekannt."
+ "import_done": "{added} Erinnerungen importiert, {skipped} waren schon bekannt.",
+ "add": "Neu",
+ "add_title": "Neue Erinnerung",
+ "add_hint": "Ein Satz, der auch später noch Sinn ergibt. {name} nutzt ihn ab dem nächsten Gespräch.",
+ "already_known": "Steht schon in deinem Gedächtnis.",
+ "cancel": "Abbrechen",
+ "clear_search": "Suche leeren",
+ "close": "Schließen",
+ "count": "{count} Erinnerungen",
+ "library": "Mediathek",
+ "shelf_all": "Alle Erinnerungen",
+ "shelf_in_mind": "Immer im Kopf",
+ "shelf_pinned": "Angepinnt",
+ "shelf_history": "Früher & beendet",
+ "history_empty": "Noch nichts geändert oder beendet",
+ "mode_memories": "Erinnerungen",
+ "mode_files": "Dateien",
+ "mode_how": "So merkt sich {name}",
+ "status_in_mind": "Immer im Kopf",
+ "status_in_mind_hint": "{name} nimmt das in jedes Gespräch mit.",
+ "status_lookup": "Wird bei Bedarf nachgeschlagen",
+ "status_lookup_hint": "Nicht in jedem Gespräch; {name} findet es, wenn eine Frage es braucht.",
+ "status_closed": "Stimmt nicht mehr",
+ "status_closed_hint": "Bleibt als Verlauf, damit {name} weiß, wie es früher war. Vergessen löscht es.",
+ "origin_title": "Woher es kommt",
+ "origin_long_user": "Von dir gesagt",
+ "origin_long_inferred": "Aus einem Gespräch gelernt",
+ "origin_long_imported": "Aus dem alten Gedächtnis übernommen",
+ "entities_title": "Worum es geht",
+ "timeline_title": "Zeitstrahl",
+ "pinned_done": "Angepinnt. Jetzt immer im Kopf.",
+ "unpinned": "Gelöst.",
+ "files_hint": "Dein Gedächtnis als einfache Markdown-Dateien, genau so, wie der Export sie schreibt.",
+ "file_meta": "{size} · {lines} Zeilen",
+ "previous": "Vorherige Datei",
+ "next": "Nächste Datei",
+ "how_kicker": "Keine Magie, nichts Verstecktes",
+ "how_title": "So merkt sich {name} Dinge über dich",
+ "how_store": "Dein Gedächtnis",
+ "how_store_caption": "Alles, gespeichert auf diesem Computer. Nie als Ganzes verschickt.",
+ "how_in_mind_caption": "Erinnerungen fahren in jedem Gespräch mit",
+ "how_budget": "Belegter Platz des festen Gedächtnis-Blocks",
+ "how_budget_line": "{used} von {budget} Zeichen · etwa {tokens} Tokens",
+ "how_conversation": "Jedes Gespräch",
+ "how_conversation_caption": "Chat und Stimme: {name} beginnt jedes Gespräch mit dem, was zählt.",
+ "how_lookup": "Nachgeschlagen, wenn eine Frage es braucht",
+ "how_lookup_body": "Alles andere bleibt im Speicher. Fragst du nach etwas, das nicht im Kopf ist, durchsucht {name} das Gedächtnis und liest nur die wenigen passenden Einträge.",
+ "how_learn_1": "Du sprichst",
+ "how_learn_1_body": "„Merk dir …“ wird sofort gespeichert, in deinen eigenen Worten.",
+ "how_learn_2": "Ein ruhiger Blick danach",
+ "how_learn_2_body": "Nach einem Gespräch vergleicht ein Durchlauf im Hintergrund, was du gesagt hast, mit dem Gespeicherten.",
+ "how_learn_3": "Das Gedächtnis bleibt aktuell",
+ "how_learn_3_body": "Neues kommt dazu, Geändertes ersetzt die alte Fassung, und gelöscht wird nur, wenn du es sagst.",
+ "how_footer": "Jede Änderung steht hier, und du kannst alles rückgängig machen oder vergessen.",
+ "mode_how_short": "So funktioniert's"
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/memory/en.json b/dodaios/ui/web/frontend/src/i18n/locales/memory/en.json
index 629bdf22cc..5c1817e695 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/memory/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/memory/en.json
@@ -258,6 +258,60 @@
"export_bundle": "Export memory (.zip)",
"export_markdown": "Export as Markdown",
"import": "Import a memory file",
- "import_done": "Imported {added} memories, {skipped} already known."
+ "import_done": "Imported {added} memories, {skipped} already known.",
+ "add": "New",
+ "add_title": "New memory",
+ "add_hint": "One sentence that should still make sense later. {name} uses it from the next conversation on.",
+ "already_known": "Already in your memory.",
+ "cancel": "Cancel",
+ "clear_search": "Clear search",
+ "close": "Close",
+ "count": "{count} memories",
+ "library": "Library",
+ "shelf_all": "All memories",
+ "shelf_in_mind": "Always in mind",
+ "shelf_pinned": "Pinned",
+ "shelf_history": "Earlier & ended",
+ "history_empty": "Nothing has changed or ended yet",
+ "mode_memories": "Memories",
+ "mode_files": "Files",
+ "mode_how": "How {name} remembers",
+ "status_in_mind": "Always in mind",
+ "status_in_mind_hint": "{name} carries this into every conversation.",
+ "status_lookup": "Looked up when needed",
+ "status_lookup_hint": "Not in every conversation; {name} finds it when a question calls for it.",
+ "status_closed": "No longer true",
+ "status_closed_hint": "Kept as history so {name} knows how things were before. Forget it to erase it.",
+ "origin_title": "Where it came from",
+ "origin_long_user": "You told it",
+ "origin_long_inferred": "Learned from a conversation",
+ "origin_long_imported": "Imported from the old memory",
+ "entities_title": "About",
+ "timeline_title": "Timeline",
+ "pinned_done": "Pinned. Always in mind now.",
+ "unpinned": "Unpinned.",
+ "files_hint": "Your memory as plain Markdown files, exactly as the export writes them.",
+ "file_meta": "{size} · {lines} lines",
+ "previous": "Previous file",
+ "next": "Next file",
+ "how_kicker": "No magic, and nothing hidden",
+ "how_title": "How {name} remembers you",
+ "how_store": "Your memory",
+ "how_store_caption": "Everything, stored on this computer. Never sent as a whole.",
+ "how_in_mind_caption": "memories ride along in every conversation",
+ "how_budget": "Space used by the always-on memory",
+ "how_budget_line": "{used} of {budget} characters · about {tokens} tokens",
+ "how_conversation": "Every conversation",
+ "how_conversation_caption": "Chat and voice: {name} starts each one knowing what matters.",
+ "how_lookup": "Looked up when a question needs it",
+ "how_lookup_body": "Everything else stays in the vault. When you ask about something that is not in mind, {name} searches the memory and reads only the few matching entries.",
+ "how_learn_1": "You talk",
+ "how_learn_1_body": "\"Remember that …\" is saved at once, in your own words.",
+ "how_learn_2": "One quiet look afterwards",
+ "how_learn_2_body": "After a conversation, one background pass compares what you said with what is stored.",
+ "how_learn_3": "Memory stays current",
+ "how_learn_3_body": "New facts are added, changed ones replace the old version, and nothing is erased unless you say so.",
+ "how_footer": "Every change is listed here, and you can undo or forget any of it.",
+ "mode_how_short": "How it works"
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/memory/es.json b/dodaios/ui/web/frontend/src/i18n/locales/memory/es.json
index 7b4d6f6a51..8426c93691 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/memory/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/memory/es.json
@@ -258,6 +258,60 @@
"export_bundle": "Exportar memoria (.zip)",
"export_markdown": "Exportar como Markdown",
"import": "Importar un archivo de memoria",
- "import_done": "{added} recuerdos importados, {skipped} ya conocidos."
+ "import_done": "{added} recuerdos importados, {skipped} ya conocidos.",
+ "add": "Nuevo",
+ "add_title": "Nuevo recuerdo",
+ "add_hint": "Una frase que siga teniendo sentido más adelante. {name} la usa desde la próxima conversación.",
+ "already_known": "Ya está en tu memoria.",
+ "cancel": "Cancelar",
+ "clear_search": "Borrar búsqueda",
+ "close": "Cerrar",
+ "count": "{count} recuerdos",
+ "library": "Biblioteca",
+ "shelf_all": "Todos los recuerdos",
+ "shelf_in_mind": "Siempre presente",
+ "shelf_pinned": "Fijados",
+ "shelf_history": "Anteriores y terminados",
+ "history_empty": "Aún no ha cambiado ni terminado nada",
+ "mode_memories": "Recuerdos",
+ "mode_files": "Archivos",
+ "mode_how": "Cómo recuerda {name}",
+ "status_in_mind": "Siempre presente",
+ "status_in_mind_hint": "{name} lo lleva a cada conversación.",
+ "status_lookup": "Se consulta cuando hace falta",
+ "status_lookup_hint": "No está en cada conversación; {name} lo encuentra cuando una pregunta lo necesita.",
+ "status_closed": "Ya no es cierto",
+ "status_closed_hint": "Se guarda como historial para que {name} sepa cómo era antes. Olvidarlo lo borra.",
+ "origin_title": "De dónde viene",
+ "origin_long_user": "Lo dijiste tú",
+ "origin_long_inferred": "Aprendido en una conversación",
+ "origin_long_imported": "Importado de la memoria anterior",
+ "entities_title": "Sobre",
+ "timeline_title": "Cronología",
+ "pinned_done": "Fijado. Ahora siempre presente.",
+ "unpinned": "Desfijado.",
+ "files_hint": "Tu memoria como archivos Markdown sencillos, tal como los escribe la exportación.",
+ "file_meta": "{size} · {lines} líneas",
+ "previous": "Archivo anterior",
+ "next": "Archivo siguiente",
+ "how_kicker": "Sin magia y sin nada oculto",
+ "how_title": "Cómo te recuerda {name}",
+ "how_store": "Tu memoria",
+ "how_store_caption": "Todo, guardado en este ordenador. Nunca se envía entero.",
+ "how_in_mind_caption": "recuerdos van en cada conversación",
+ "how_budget": "Espacio usado por la memoria fija",
+ "how_budget_line": "{used} de {budget} caracteres · unos {tokens} tokens",
+ "how_conversation": "Cada conversación",
+ "how_conversation_caption": "Chat y voz: {name} empieza cada una sabiendo lo importante.",
+ "how_lookup": "Se consulta cuando una pregunta lo necesita",
+ "how_lookup_body": "Todo lo demás se queda en la bóveda. Si preguntas por algo que no está presente, {name} busca en la memoria y lee solo las pocas entradas que coinciden.",
+ "how_learn_1": "Hablas",
+ "how_learn_1_body": "«Recuerda que …» se guarda al instante, con tus propias palabras.",
+ "how_learn_2": "Una mirada tranquila después",
+ "how_learn_2_body": "Tras una conversación, un repaso en segundo plano compara lo que dijiste con lo guardado.",
+ "how_learn_3": "La memoria se mantiene al día",
+ "how_learn_3_body": "Lo nuevo se añade, lo que cambia reemplaza la versión anterior y nada se borra salvo que lo pidas.",
+ "how_footer": "Cada cambio aparece aquí y puedes deshacerlo u olvidarlo.",
+ "mode_how_short": "Cómo funciona"
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/memory/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/memory/pt.json
index 281745dc12..710d3c5c6d 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/memory/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/memory/pt.json
@@ -258,6 +258,60 @@
"export_bundle": "Exportar memória (.zip)",
"export_markdown": "Exportar como Markdown",
"import": "Importar um arquivo de memória",
- "import_done": "{added} lembranças importadas, {skipped} já conhecidas."
+ "import_done": "{added} lembranças importadas, {skipped} já conhecidas.",
+ "add": "Novo",
+ "add_title": "Nova lembrança",
+ "add_hint": "Uma frase que ainda faça sentido depois. {name} a usa a partir da próxima conversa.",
+ "already_known": "Já está na sua memória.",
+ "cancel": "Cancelar",
+ "clear_search": "Limpar busca",
+ "close": "Fechar",
+ "count": "{count} lembranças",
+ "library": "Biblioteca",
+ "shelf_all": "Todas as lembranças",
+ "shelf_in_mind": "Sempre em mente",
+ "shelf_pinned": "Fixadas",
+ "shelf_history": "Anteriores e encerradas",
+ "history_empty": "Nada mudou ou foi encerrado ainda",
+ "mode_memories": "Lembranças",
+ "mode_files": "Arquivos",
+ "mode_how": "Como {name} lembra",
+ "status_in_mind": "Sempre em mente",
+ "status_in_mind_hint": "{name} leva isto para cada conversa.",
+ "status_lookup": "Consultado quando preciso",
+ "status_lookup_hint": "Não está em toda conversa; {name} encontra quando uma pergunta pede.",
+ "status_closed": "Não é mais verdade",
+ "status_closed_hint": "Fica como histórico para {name} saber como era antes. Esquecer apaga.",
+ "origin_title": "De onde veio",
+ "origin_long_user": "Você disse",
+ "origin_long_inferred": "Aprendido numa conversa",
+ "origin_long_imported": "Importado da memória antiga",
+ "entities_title": "Sobre",
+ "timeline_title": "Linha do tempo",
+ "pinned_done": "Fixado. Agora sempre em mente.",
+ "unpinned": "Desafixado.",
+ "files_hint": "Sua memória como arquivos Markdown simples, exatamente como a exportação os escreve.",
+ "file_meta": "{size} · {lines} linhas",
+ "previous": "Arquivo anterior",
+ "next": "Próximo arquivo",
+ "how_kicker": "Sem mágica e nada escondido",
+ "how_title": "Como {name} lembra de você",
+ "how_store": "Sua memória",
+ "how_store_caption": "Tudo, guardado neste computador. Nunca enviado inteiro.",
+ "how_in_mind_caption": "lembranças vão em cada conversa",
+ "how_budget": "Espaço usado pela memória fixa",
+ "how_budget_line": "{used} de {budget} caracteres · cerca de {tokens} tokens",
+ "how_conversation": "Cada conversa",
+ "how_conversation_caption": "Chat e voz: {name} começa cada uma sabendo o que importa.",
+ "how_lookup": "Consultado quando uma pergunta precisa",
+ "how_lookup_body": "O resto fica no cofre. Quando você pergunta algo que não está em mente, {name} busca na memória e lê só as poucas entradas que combinam.",
+ "how_learn_1": "Você fala",
+ "how_learn_1_body": "“Lembre que …” é salvo na hora, com suas próprias palavras.",
+ "how_learn_2": "Uma olhada tranquila depois",
+ "how_learn_2_body": "Depois de uma conversa, uma passada em segundo plano compara o que você disse com o que está salvo.",
+ "how_learn_3": "A memória fica atualizada",
+ "how_learn_3_body": "O novo é adicionado, o que muda substitui a versão antiga e nada é apagado a menos que você peça.",
+ "how_footer": "Cada mudança aparece aqui, e você pode desfazer ou esquecer qualquer uma.",
+ "mode_how_short": "Como funciona"
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/memory/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/memory/zh.json
index 7dad44232f..a3c123b3da 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/memory/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/memory/zh.json
@@ -258,6 +258,60 @@
"export_bundle": "导出记忆(.zip)",
"export_markdown": "导出为 Markdown",
"import": "导入记忆文件",
- "import_done": "已导入 {added} 条记忆,{skipped} 条已存在。"
+ "import_done": "已导入 {added} 条记忆,{skipped} 条已存在。",
+ "add": "新建",
+ "add_title": "新记忆",
+ "add_hint": "一句以后仍然有意义的话。{name} 从下一次对话起就会使用它。",
+ "already_known": "已经在你的记忆中。",
+ "cancel": "取消",
+ "clear_search": "清除搜索",
+ "close": "关闭",
+ "count": "{count} 条记忆",
+ "library": "资料库",
+ "shelf_all": "全部记忆",
+ "shelf_in_mind": "始终记在心里",
+ "shelf_pinned": "已置顶",
+ "shelf_history": "早期与已结束",
+ "history_empty": "还没有任何更改或结束",
+ "mode_memories": "记忆",
+ "mode_files": "文件",
+ "mode_how": "{name} 如何记忆",
+ "status_in_mind": "始终记在心里",
+ "status_in_mind_hint": "{name} 会把它带入每一次对话。",
+ "status_lookup": "需要时查找",
+ "status_lookup_hint": "不在每次对话中;当问题需要时 {name} 会找到它。",
+ "status_closed": "不再成立",
+ "status_closed_hint": "作为历史保留,让 {name} 知道以前的情况。遗忘会将其删除。",
+ "origin_title": "来源",
+ "origin_long_user": "你说的",
+ "origin_long_inferred": "从对话中学到",
+ "origin_long_imported": "从旧记忆导入",
+ "entities_title": "相关",
+ "timeline_title": "时间线",
+ "pinned_done": "已置顶,现在始终记在心里。",
+ "unpinned": "已取消置顶。",
+ "files_hint": "你的记忆以普通 Markdown 文件呈现,与导出内容完全一致。",
+ "file_meta": "{size} · {lines} 行",
+ "previous": "上一个文件",
+ "next": "下一个文件",
+ "how_kicker": "没有魔法,也没有隐藏",
+ "how_title": "{name} 如何记住你",
+ "how_store": "你的记忆",
+ "how_store_caption": "全部保存在这台电脑上,从不整体发送。",
+ "how_in_mind_caption": "条记忆随每次对话同行",
+ "how_budget": "常驻记忆占用的空间",
+ "how_budget_line": "{budget} 个字符中已用 {used} · 约 {tokens} 个 token",
+ "how_conversation": "每一次对话",
+ "how_conversation_caption": "聊天和语音:{name} 每次开始时都知道重要的事。",
+ "how_lookup": "问题需要时才查找",
+ "how_lookup_body": "其余内容留在记忆库中。当你问到不在心里的事时,{name} 会搜索记忆,只读取少数匹配的条目。",
+ "how_learn_1": "你说话",
+ "how_learn_1_body": "“记住……”会立即用你自己的话保存。",
+ "how_learn_2": "事后安静地看一眼",
+ "how_learn_2_body": "对话结束后,后台会将你说的内容与已保存的内容进行比较。",
+ "how_learn_3": "记忆保持最新",
+ "how_learn_3_body": "新事实会被添加,变化的内容会替换旧版本,除非你要求,否则不会删除任何内容。",
+ "how_footer": "每一次更改都列在这里,你可以撤销或遗忘其中任何一项。",
+ "mode_how_short": "工作原理"
}
}
diff --git a/dodaios/ui/web/frontend/src/lib/personalMemoryApi.ts b/dodaios/ui/web/frontend/src/lib/personalMemoryApi.ts
index 788087a7bb..918852c593 100644
--- a/dodaios/ui/web/frontend/src/lib/personalMemoryApi.ts
+++ b/dodaios/ui/web/frontend/src/lib/personalMemoryApi.ts
@@ -50,9 +50,21 @@ export interface VaultOverview {
};
kinds: MemoryKind[];
prompt_block: string;
+ /** Ids of the memories the always-on block holds right now. */
+ in_mind_ids: string[];
+ budget_chars: number;
+ used_chars: number;
imported: boolean;
}
+export interface VaultFile {
+ name: string;
+ kind: MemoryKind | "index";
+ bytes: number;
+ lines: number;
+ content: string;
+}
+
export interface VaultActivity {
seq: number;
at: string;
@@ -104,8 +116,17 @@ export const VAULT_KEYS = {
items: (q: string, history: boolean) => ["memory-vault", "items", q, history] as const,
history: (id: string) => ["memory-vault", "history", id] as const,
activity: ["memory-vault", "activity"] as const,
+ files: ["memory-vault", "files"] as const,
};
+export function useVaultFiles(enabled = true) {
+ return useQuery({
+ queryKey: VAULT_KEYS.files,
+ enabled,
+ queryFn: () => request<{ files: VaultFile[] }>(`${BASE}/files`),
+ });
+}
+
export function useVaultOverview() {
return useQuery({ queryKey: VAULT_KEYS.overview, queryFn: () => request<VaultOverview>(BASE) });
}
diff --git a/dodaios/ui/web/frontend/src/views/MemoryView.test.tsx b/dodaios/ui/web/frontend/src/views/MemoryView.test.tsx
index bbf414bc03..66d3b7cef4 100644
--- a/dodaios/ui/web/frontend/src/views/MemoryView.test.tsx
+++ b/dodaios/ui/web/frontend/src/views/MemoryView.test.tsx
@@ -6,9 +6,9 @@ import { loadLocaleChunk, setUiLanguage } from "@/i18n";
import { MemoryView } from "@/views/MemoryView";
/**
- * The Memory section shows the personal memory vault: one row per memory,
- * grouped by kind, the exact block the assistant carries into every
- * conversation, and the export links. Writes go to /api/memory/vault.
+ * The Memory section: a library sidebar, the memories list with an
+ * inspector, the memory as files with a preview, and a drawing of what
+ * reaches the model. Writes go to /api/memory/vault.
*/
const NOW = "2026-11-02T10:00:00+00:00";
@@ -39,17 +39,32 @@ function memory(id: string, kind: string, text: string, extra: Record<string, un
const ITEMS = [
memory("m1", "profile", "I live in Berlin.", { supersedes_id: "m0" }),
- memory("m2", "relationship", "Lea is my sister.", { pinned: true, origin: "inferred" }),
+ memory("m2", "relationship", "Lea is my sister.", {
+ pinned: true,
+ origin: "inferred",
+ source: { evidence: "my sister Lea is visiting" },
+ }),
+ memory("m3", "episode", "We hiked on Sunday."),
];
const OVERVIEW = {
path: "vault.db",
- stats: { current: 2, by_kind: { profile: 1, relationship: 1 }, all_versions: 3, forgotten: 0, entities: 0 },
- kinds: ["profile", "relationship"],
+ stats: { current: 3, by_kind: { profile: 1, relationship: 1, episode: 1 }, all_versions: 4, forgotten: 0, entities: 0 },
+ kinds: ["profile", "relationship", "episode"],
prompt_block: "## What you know\nUse it.\nPinned:\n- Lea is my sister.",
+ in_mind_ids: ["m1", "m2"],
+ budget_chars: 2400,
+ used_chars: 600,
imported: true,
};
+const FILES = {
+ files: [
+ { name: "MEMORY.md", kind: "index", bytes: 120, lines: 6, content: "# My memory\n" },
+ { name: "profile.md", kind: "profile", bytes: 90, lines: 8, content: "---\nkind: profile\n---\n\n# About me\n\n- I live in Berlin. <!-- m1 -->\n" },
+ ],
+};
+
let calls: Array<{ url: string; init?: RequestInit }> = [];
function stubFetch() {
@@ -58,12 +73,12 @@ function stubFetch() {
calls.push({ url, init });
const body = url.endsWith("/api/memory/vault")
? OVERVIEW
- : url.includes("/activity")
- ? { entries: [{ seq: 1, at: NOW, action: "add", memory_id: "m1", text: "I live in Berlin." }] }
+ : url.includes("/files")
+ ? FILES
: url.includes("/history")
? {
versions: [
- memory("m0", "profile", "I live in Hamburg.", { current: false }),
+ memory("m0", "profile", "I live in Hamburg.", { current: false, valid_to: NOW }),
memory("m1", "profile", "I live in Berlin."),
],
}
@@ -92,45 +107,66 @@ beforeAll(async () => {
afterEach(cleanup);
describe("MemoryView", () => {
- it("groups memories by kind and shows what is always in mind", async () => {
+ it("lists memories and inspects the first one with its timeline", async () => {
+ stubFetch();
+ renderView();
+ expect(await screen.findByText("Lea is my sister.")).toBeTruthy();
+ expect(screen.getAllByTestId("vault-row")).toHaveLength(3);
+ const inspector = await screen.findByTestId("vault-inspector");
+ expect(within(inspector).getByText("Always in mind")).toBeTruthy();
+ const versions = await within(inspector).findByTestId("vault-versions");
+ expect(within(versions).getByText("I live in Hamburg.")).toBeTruthy();
+ });
+
+ it("filters to what is always in mind and shows the user's own words", async () => {
stubFetch();
renderView();
- const profile = await screen.findByTestId("vault-group-profile");
- expect(within(profile).getByText("I live in Berlin.")).toBeTruthy();
- expect(within(screen.getByTestId("vault-group-relationship")).getByText("Lea is my sister.")).toBeTruthy();
- expect(screen.getByTestId("vault-prompt-block").textContent).toContain("Lea is my sister.");
- expect(screen.getByTestId("vault-export-bundle").getAttribute("href")).toBe(
- "/api/memory/vault/export?format=bundle",
- );
+ await screen.findByText("We hiked on Sunday.");
+ fireEvent.click(screen.getAllByRole("button", { name: /Always in mind/ })[0]);
+ await waitFor(() => expect(screen.getAllByTestId("vault-row")).toHaveLength(2));
+ fireEvent.click(screen.getAllByTestId("vault-row")[1]);
+ expect((await screen.findAllByText("my sister Lea is visiting")).length).toBeGreaterThan(0);
});
- it("saves a new memory from the composer", async () => {
+ it("adds a memory from the new-memory sheet", async () => {
stubFetch();
renderView();
- const composer = await screen.findByTestId("vault-composer");
- fireEvent.change(within(composer).getByRole("textbox"), { target: { value: "I like jazz." } });
- fireEvent.submit(composer);
+ await screen.findByText("Lea is my sister.");
+ fireEvent.click(screen.getByTestId("vault-add"));
+ const sheet = await screen.findByTestId("vault-new-sheet");
+ fireEvent.change(within(sheet).getByRole("textbox"), { target: { value: "I like jazz." } });
+ fireEvent.click(within(sheet).getByRole("radio", { name: "Preferences" }));
+ fireEvent.click(within(sheet).getByRole("button", { name: "Remember" }));
await waitFor(() => expect(calls.some((c) => c.init?.method === "POST" && c.url.endsWith("/items"))).toBe(true));
const post = calls.find((c) => c.init?.method === "POST" && c.url.endsWith("/items"));
- expect(JSON.parse(String(post?.init?.body))).toMatchObject({ text: "I like jazz.", kind: "" });
+ expect(JSON.parse(String(post?.init?.body))).toMatchObject({ text: "I like jazz.", kind: "preference" });
+ });
+
+ it("shows the memory as files with a readable preview", async () => {
+ stubFetch();
+ renderView();
+ fireEvent.click(await screen.findByTestId("vault-mode-files"));
+ const files = await screen.findAllByTestId("vault-file");
+ fireEvent.click(files[1]);
+ const preview = await screen.findByTestId("vault-quicklook");
+ expect(within(preview).getByText("I live in Berlin.")).toBeTruthy();
+ expect(preview.textContent).not.toContain("kind: profile");
});
- it("shows earlier versions of a changed memory", async () => {
+ it("draws how much of the always-on space is used", async () => {
stubFetch();
renderView();
- await screen.findByText("I live in Berlin.");
- fireEvent.click(screen.getByRole("button", { name: "Earlier versions" }));
- const versions = await screen.findByTestId("vault-versions");
- expect(await within(versions).findByText("I live in Hamburg.")).toBeTruthy();
+ fireEvent.click(await screen.findByTestId("vault-mode-how"));
+ const meter = await screen.findByRole("meter");
+ expect(meter.getAttribute("aria-valuenow")).toBe("600");
});
it("asks before forgetting and then deletes", async () => {
stubFetch();
renderView();
- await screen.findByText("I live in Berlin.");
- fireEvent.click(screen.getAllByRole("button", { name: "Forget" })[0]);
- expect(await screen.findByText("Forget this for good?")).toBeTruthy();
- const dialog = screen.getByRole("dialog");
+ const inspector = await screen.findByTestId("vault-inspector");
+ fireEvent.click(within(inspector).getByRole("button", { name: "Forget" }));
+ const dialog = await screen.findByRole("dialog");
fireEvent.click(within(dialog).getByRole("button", { name: "Forget" }));
await waitFor(() => expect(calls.some((c) => c.init?.method === "DELETE")).toBe(true));
});
diff --git a/dodaios/ui/web/frontend/src/views/MemoryView.tsx b/dodaios/ui/web/frontend/src/views/MemoryView.tsx
index 625bc53f60..9fdd5c596b 100644
--- a/dodaios/ui/web/frontend/src/views/MemoryView.tsx
+++ b/dodaios/ui/web/frontend/src/views/MemoryView.tsx
@@ -1,254 +1,288 @@
/**
* The Memory section: the personal memory vault (ADR-0044).
*
- * ┌──────────────────────────────────────────────┬──────────────────┐
- * │ Memory · what the assistant knows about you │ Always in mind │
- * │ [ tell me something to remember … ][Save] │ (the prompt │
- * │ search · kind chips · history │ block, verbatim)│
- * │ About you ────────────────────────────── │ Recent changes │
- * │ sentence pin edit end ✕ │ Take it with you │
- * │ People ───────────────────────────────── │ export · import │
- * └──────────────────────────────────────────────┴──────────────────┘
+ * ┌──────────────┬──────────────────────────────────────────────────┐
+ * │ ● ● ● │ [ Memories | Files | How it works ] ⌕ + │
+ * │ Library ├───────────────────────────┬──────────────────────┤
+ * │ All │ list of memories │ inspector: │
+ * │ In mind │ (one sentence each) │ the memory, where │
+ * │ Pinned │ │ it came from, its │
+ * │ Kinds │ │ versions, actions │
+ * │ About you … │ │ │
+ * │ ───── │ │ │
+ * │ export/import│ │ │
+ * └──────────────┴───────────────────────────┴──────────────────────┘
*
- * Every row is one atomic memory. An edit is a new version (the old one
- * stays in the history), "no longer true" closes it with a date, and
- * forgetting erases every version.
+ * "Files" shows the same memory as the Markdown files an export writes, with
+ * a large preview; "How it works" draws what reaches the model and when.
*/
-import { useCallback, useMemo, useRef, useState, type FormEvent } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
-import {
- Brain,
- Check,
- CircleOff,
- Download,
- History,
- Loader2,
- Pencil,
- Pin,
- PinOff,
- Search,
- Trash2,
- Upload,
- X,
-} from "lucide-react";
+import { Brain, History, Pin, Plus, Search, X } from "lucide-react";
import { fill, useLocaleChunk, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
-import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
-import { BrandedSelect } from "@/components/ui/select";
-import { ConfirmDialog } from "@/components/memory/MemoryDialogs";
import {
MEMORY_KINDS,
VAULT_KEYS,
- addMemory,
- editMemory,
- endMemory,
- exportUrl,
- forgetMemory,
- importBundle,
- pinMemory,
- useVaultActivity,
- useVaultHistory,
useVaultItems,
useVaultOverview,
- type MemoryKind,
- type VaultMemory,
} from "@/lib/personalMemoryApi";
+import { IN_MIND_STYLE, KIND_STYLE } from "@/components/memoryVault/kinds";
+import { MemoryBrowser, type Shelf } from "@/components/memoryVault/MemoryBrowser";
+import { MemoryFiles } from "@/components/memoryVault/MemoryFiles";
+import { HowItWorks } from "@/components/memoryVault/HowItWorks";
+import { NewMemorySheet } from "@/components/memoryVault/NewMemorySheet";
+import { Portability } from "@/components/memoryVault/Portability";
-type Filter = MemoryKind | "all";
-
-function day(stamp: string | null | undefined): string {
- if (!stamp) return "";
- const date = new Date(stamp);
- if (Number.isNaN(date.getTime())) return stamp.slice(0, 10);
- return date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
-}
+type Mode = "memories" | "files" | "how";
export function MemoryView(): JSX.Element {
const t = useT();
useLocaleChunk("memory");
const name = useEventStore((s) => s.assistantName) || "Dodaios";
const queryClient = useQueryClient();
+ const [mode, setMode] = useState<Mode>("memories");
+ const [shelf, setShelf] = useState<Shelf>("all");
const [query, setQuery] = useState("");
- const [filter, setFilter] = useState<Filter>("all");
- const [showHistory, setShowHistory] = useState(false);
+ const [adding, setAdding] = useState(false);
const [toast, setToast] = useState<string | null>(null);
- const [forgetting, setForgetting] = useState<VaultMemory | null>(null);
const overview = useVaultOverview();
- const items = useVaultItems(query, showHistory);
+ const items = useVaultItems(query, shelf === "history");
- const refresh = useCallback(
- () => queryClient.invalidateQueries({ queryKey: VAULT_KEYS.all }),
- [queryClient],
- );
+ const refresh = useCallback(() => queryClient.invalidateQueries({ queryKey: VAULT_KEYS.all }), [queryClient]);
const notify = useCallback((message: string) => {
setToast(message);
window.setTimeout(() => setToast((current) => (current === message ? null : current)), 3200);
}, []);
- const run = useCallback(
- async (work: () => Promise<unknown>, done?: string) => {
- try {
- await work();
- await refresh();
- if (done) notify(done);
- } catch (error) {
- notify(error instanceof Error ? error.message : String(error));
- }
- },
- [notify, refresh],
- );
- const rows = useMemo(() => {
- const all = items.data?.items ?? [];
- return filter === "all" ? all : all.filter((m) => m.kind === filter);
- }, [items.data, filter]);
+ // Cmd/Ctrl+N adds a memory, Cmd/Ctrl+F searches.
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (!(event.ctrlKey || event.metaKey)) return;
+ const key = event.key.toLowerCase();
+ if (key === "n") {
+ event.preventDefault();
+ setAdding(true);
+ } else if (key === "f") {
+ event.preventDefault();
+ setMode("memories");
+ document.getElementById("vault-search")?.focus();
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
- const grouped = useMemo(() => {
- if (query.trim()) return [{ kind: null as MemoryKind | null, rows }];
- return MEMORY_KINDS.map((kind) => ({ kind, rows: rows.filter((m) => m.kind === kind) })).filter(
- (group) => group.rows.length > 0,
- );
- }, [rows, query]);
+ const inMind = useMemo(() => new Set(overview.data?.in_mind_ids ?? []), [overview.data]);
+ const stats = overview.data?.stats;
+ const byKind = stats?.by_kind ?? {};
+ const all = items.data?.items ?? [];
+ const pinnedCount = all.filter((m) => m.pinned && m.current).length;
if (overview.isError) {
return (
<div className="flex h-full items-center justify-center p-8">
- <EmptyState
- icon={<Brain />}
- title={t("vault.offline_title")}
- description={t("vault.offline_body")}
- />
+ <EmptyState icon={<Brain />} title={t("vault.offline_title")} description={t("vault.offline_body")} />
</div>
);
}
- const stats = overview.data?.stats;
- const byKind = stats?.by_kind ?? {};
+ const shelfTitle =
+ shelf === "all"
+ ? t("vault.shelf_all")
+ : shelf === "in_mind"
+ ? t("vault.shelf_in_mind")
+ : shelf === "pinned"
+ ? t("vault.shelf_pinned")
+ : shelf === "history"
+ ? t("vault.shelf_history")
+ : t(`vault.kind_${shelf}`);
return (
- <div data-testid="memory-vault-view" className="flex h-full min-h-0 flex-col overflow-hidden">
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="mx-auto grid w-full max-w-[1180px] gap-8 px-6 pb-16 pt-8 lg:grid-cols-[minmax(0,1fr)_320px]">
- <main className="min-w-0">
- <header>
- <h1 className="text-2xl font-semibold tracking-tight text-foreground-strong">
- {t("vault.title")}
- </h1>
- <p className="mt-1 text-sm text-muted-foreground">
- {stats
- ? fill(t("vault.subtitle"), { name, count: stats.current })
- : t("vault.loading")}
+ <div data-testid="memory-vault-view" className="flex h-full min-h-0 flex-col p-3 sm:p-5">
+ <div className="flex min-h-0 flex-1 overflow-hidden rounded-2xl border border-border bg-card shadow-float">
+ {/* Sidebar */}
+ <aside className="hidden w-[232px] shrink-0 flex-col border-r border-border bg-sheen/[0.025] md:flex">
+ <div className="flex items-center gap-2 px-4 pb-3 pt-4">
+ <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-accent/15 text-accent">
+ <Brain className="h-4 w-4" />
+ </span>
+ <div className="min-w-0">
+ <p className="truncate text-[13px] font-semibold text-foreground-strong">{t("vault.title")}</p>
+ <p className="truncate text-[11px] text-muted-foreground">
+ {stats ? fill(t("vault.count"), { count: stats.current }) : t("vault.loading")}
</p>
- </header>
-
- <Composer
- onSave={(text, kind) =>
- run(() => addMemory(text, kind), t("vault.saved"))
- }
+ </div>
+ </div>
+ <nav className="min-h-0 flex-1 overflow-y-auto px-2 pb-3" aria-label={t("vault.title")}>
+ <SidebarLabel>{t("vault.library")}</SidebarLabel>
+ <SidebarItem
+ active={mode === "memories" && shelf === "all"}
+ icon={<Brain />}
+ hue="220 9% 56%"
+ label={t("vault.shelf_all")}
+ count={stats?.current}
+ onClick={() => {
+ setMode("memories");
+ setShelf("all");
+ }}
/>
-
- <div className="mt-6 flex flex-wrap items-center gap-2">
- <label className="relative flex min-w-[220px] flex-1 items-center">
- <Search className="pointer-events-none absolute left-3 h-4 w-4 text-muted-foreground" />
- <input
- data-testid="vault-search"
- value={query}
- onChange={(event) => setQuery(event.target.value)}
- placeholder={t("vault.search_placeholder")}
- aria-label={t("vault.search_placeholder")}
- className="h-9 w-full rounded-md border border-border bg-card pl-9 pr-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ <SidebarItem
+ active={mode === "memories" && shelf === "in_mind"}
+ icon={<IN_MIND_STYLE.icon />}
+ hue={IN_MIND_STYLE.hue}
+ label={t("vault.shelf_in_mind")}
+ count={inMind.size}
+ onClick={() => {
+ setMode("memories");
+ setShelf("in_mind");
+ }}
+ />
+ <SidebarItem
+ active={mode === "memories" && shelf === "pinned"}
+ icon={<Pin />}
+ hue="4 86% 58%"
+ label={t("vault.shelf_pinned")}
+ count={pinnedCount}
+ onClick={() => {
+ setMode("memories");
+ setShelf("pinned");
+ }}
+ />
+ <SidebarItem
+ active={mode === "memories" && shelf === "history"}
+ icon={<History />}
+ hue="220 9% 56%"
+ label={t("vault.shelf_history")}
+ onClick={() => {
+ setMode("memories");
+ setShelf("history");
+ }}
+ />
+ <SidebarLabel>{t("vault.kinds_label")}</SidebarLabel>
+ {MEMORY_KINDS.filter((kind) => (byKind[kind] ?? 0) > 0 || shelf === kind).map((kind) => {
+ const Icon = KIND_STYLE[kind].icon;
+ return (
+ <SidebarItem
+ key={kind}
+ active={mode === "memories" && shelf === kind}
+ icon={<Icon />}
+ hue={KIND_STYLE[kind].hue}
+ label={t(`vault.kind_${kind}`)}
+ count={byKind[kind] ?? 0}
+ onClick={() => {
+ setMode("memories");
+ setShelf(kind);
+ }}
/>
- </label>
- <Button
- variant={showHistory ? "secondary" : "ghost"}
- size="sm"
- aria-pressed={showHistory}
- data-testid="vault-history-toggle"
- onClick={() => setShowHistory((value) => !value)}
- >
- <History /> {t("vault.show_history")}
- </Button>
- </div>
+ );
+ })}
+ </nav>
+ <Portability onDone={(message) => void refresh().then(() => notify(message))} onError={notify} />
+ </aside>
- <div className="mt-3 flex flex-wrap gap-1.5" role="tablist" aria-label={t("vault.kinds_label")}>
- <Chip active={filter === "all"} onClick={() => setFilter("all")}>
- {t("vault.kind_all")}
- <span className="tabular-nums text-muted-foreground">{stats?.current ?? 0}</span>
- </Chip>
- {MEMORY_KINDS.filter((kind) => (byKind[kind] ?? 0) > 0 || filter === kind).map((kind) => (
- <Chip key={kind} active={filter === kind} onClick={() => setFilter(kind)}>
- {t(`vault.kind_${kind}`)}
- <span className="tabular-nums text-muted-foreground">{byKind[kind] ?? 0}</span>
- </Chip>
- ))}
+ {/* Main */}
+ <section className="flex min-w-0 flex-1 flex-col">
+ <header className="flex h-14 shrink-0 items-center gap-3 border-b border-border px-4">
+ <h1 className="hidden min-w-0 truncate text-[15px] font-semibold text-foreground-strong lg:block lg:w-[180px]">
+ {mode === "memories" ? shelfTitle : mode === "files" ? t("vault.mode_files") : fill(t("vault.mode_how"), { name })}
+ </h1>
+ <Segmented
+ value={mode}
+ onChange={setMode}
+ options={[
+ { value: "memories", label: t("vault.mode_memories") },
+ { value: "files", label: t("vault.mode_files") },
+ { value: "how", label: t("vault.mode_how_short") },
+ ]}
+ />
+ <div className="ml-auto flex items-center gap-2">
+ {mode === "memories" && (
+ <label className="relative hidden items-center sm:flex">
+ <Search className="pointer-events-none absolute left-2.5 h-3.5 w-3.5 text-muted-foreground" />
+ <input
+ id="vault-search"
+ data-testid="vault-search"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t("vault.search_placeholder")}
+ aria-label={t("vault.search_placeholder")}
+ className="h-8 w-[200px] rounded-lg border border-border bg-sheen/[0.04] pl-8 pr-7 text-[13px] text-foreground placeholder:text-faint-foreground focus-visible:w-[260px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-safe:transition-[width]"
+ />
+ {query && (
+ <button
+ type="button"
+ aria-label={t("vault.clear_search")}
+ onClick={() => setQuery("")}
+ className="absolute right-2 text-muted-foreground hover:text-foreground"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </label>
+ )}
+ <button
+ type="button"
+ data-testid="vault-add"
+ onClick={() => setAdding(true)}
+ title={t("vault.add_title")}
+ aria-label={t("vault.add_title")}
+ className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-accent px-3 text-[13px] font-medium text-accent-foreground shadow-sm hover:bg-accent/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Plus className="h-4 w-4" />
+ <span className="hidden sm:inline">{t("vault.add")}</span>
+ </button>
</div>
+ </header>
- {items.isLoading ? (
- <p className="mt-10 flex items-center gap-2 text-sm text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin" /> {t("vault.loading")}
- </p>
- ) : rows.length === 0 ? (
- <EmptyState
- className="mt-6"
- icon={<Brain />}
- title={query.trim() ? t("vault.no_results") : t("vault.empty_title")}
- description={query.trim() ? undefined : fill(t("vault.empty_body"), { name })}
+ <div className="min-h-0 flex-1">
+ {mode === "memories" && (
+ <MemoryBrowser
+ shelf={shelf}
+ query={query}
+ items={all}
+ loading={items.isLoading}
+ inMind={inMind}
+ name={name}
+ onChanged={refresh}
+ notify={notify}
+ onAdd={() => setAdding(true)}
/>
- ) : (
- grouped.map((group) => (
- <section key={group.kind ?? "results"} className="mt-8" data-testid={`vault-group-${group.kind ?? "results"}`}>
- <h2 className="mb-2.5 flex items-baseline gap-2 px-1 text-sm font-medium text-foreground">
- {group.kind ? t(`vault.kind_${group.kind}`) : t("vault.results")}
- <span className="tabular-nums text-muted-foreground">{group.rows.length}</span>
- </h2>
- <ul className="divide-y divide-border overflow-hidden rounded-xl border border-border bg-card">
- {group.rows.map((memory) => (
- <MemoryRow
- key={memory.id}
- memory={memory}
- onPin={() => run(() => pinMemory(memory.id, !memory.pinned))}
- onEdit={(text) => run(() => editMemory(memory.id, text), t("vault.updated"))}
- onEnd={() => run(() => endMemory(memory.id), t("vault.ended"))}
- onForget={() => setForgetting(memory)}
- />
- ))}
- </ul>
- </section>
- ))
)}
- </main>
-
- <aside className="flex min-w-0 flex-col gap-5 lg:sticky lg:top-8 lg:self-start">
- <AlwaysInMind block={overview.data?.prompt_block ?? ""} name={name} />
- <RecentChanges />
- <Portability onImported={(message) => run(async () => undefined, message)} onError={notify} />
- </aside>
- </div>
+ {mode === "files" && <MemoryFiles />}
+ {mode === "how" && overview.data && (
+ <HowItWorks
+ name={name}
+ overview={overview.data}
+ onShowInMind={() => {
+ setMode("memories");
+ setShelf("in_mind");
+ }}
+ />
+ )}
+ </div>
+ </section>
</div>
- <ConfirmDialog
- open={forgetting !== null}
- title={t("vault.forget_title")}
- description={fill(t("vault.forget_body"), { name })}
- confirmLabel={t("vault.forget")}
- items={forgetting ? [forgetting.text] : undefined}
- onClose={() => setForgetting(null)}
- onConfirm={async () => {
- const target = forgetting;
- if (!target) return;
- await forgetMemory(target.id);
- setForgetting(null);
+ <NewMemorySheet
+ open={adding}
+ name={name}
+ onClose={() => setAdding(false)}
+ onSaved={async (message) => {
+ setAdding(false);
await refresh();
- notify(t("vault.forgotten"));
+ notify(message);
}}
+ onError={notify}
/>
{toast && (
<div
role="status"
- className="pointer-events-none fixed bottom-6 left-1/2 z-[70] -translate-x-1/2 rounded-lg border border-border bg-popover px-4 py-2 text-sm text-popover-foreground shadow-float"
+ className="pointer-events-none fixed bottom-8 left-1/2 z-[70] -translate-x-1/2 rounded-full border border-border bg-popover/95 px-4 py-2 text-[13px] text-popover-foreground shadow-float backdrop-blur"
>
{toast}
</div>
@@ -257,347 +291,79 @@ export function MemoryView(): JSX.Element {
);
}
-function Chip({
- active,
- onClick,
- children,
-}: {
- active: boolean;
- onClick: () => void;
- children: React.ReactNode;
-}) {
+function SidebarLabel({ children }: { children: React.ReactNode }) {
return (
- <button
- type="button"
- role="tab"
- aria-selected={active}
- onClick={onClick}
- className={cn(
- "inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- active
- ? "border-accent/60 bg-accent/10 text-foreground-strong"
- : "border-border bg-transparent text-muted-foreground hover:bg-secondary hover:text-foreground",
- )}
- >
- {children}
- </button>
+ <p className="px-2.5 pb-1 pt-4 text-[11px] font-semibold uppercase tracking-wide text-faint-foreground">{children}</p>
);
}
-function Composer({ onSave }: { onSave: (text: string, kind: MemoryKind | "") => Promise<void> }) {
- const t = useT();
- const [text, setText] = useState("");
- const [kind, setKind] = useState<MemoryKind | "">("");
- const [busy, setBusy] = useState(false);
- const options = useMemo(
- () => [
- { value: "", label: t("vault.kind_auto") },
- ...MEMORY_KINDS.filter((k) => k !== "ephemeral").map((k) => ({ value: k, label: t(`vault.kind_${k}`) })),
- ],
- [t],
- );
- const submit = async (event: FormEvent) => {
- event.preventDefault();
- const value = text.trim();
- if (!value || busy) return;
- setBusy(true);
- try {
- await onSave(value, kind);
- setText("");
- } finally {
- setBusy(false);
- }
- };
- return (
- <form
- onSubmit={submit}
- data-testid="vault-composer"
- className="mt-6 flex flex-wrap items-center gap-2 rounded-xl border border-border bg-card p-2 focus-within:border-accent/50"
- >
- <input
- value={text}
- onChange={(event) => setText(event.target.value)}
- placeholder={t("vault.composer_placeholder")}
- aria-label={t("vault.composer_placeholder")}
- maxLength={2000}
- className="h-9 min-w-[200px] flex-1 bg-transparent px-2 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none"
- />
- <BrandedSelect
- value={kind}
- options={options}
- onValueChange={(value) => setKind(value as MemoryKind | "")}
- ariaLabel={t("vault.kind_label")}
- className="w-[170px]"
- testId="vault-composer-kind"
- />
- <Button type="submit" size="sm" disabled={!text.trim() || busy}>
- {busy ? <Loader2 className="animate-spin" /> : <Check />}
- {t("vault.remember")}
- </Button>
- </form>
- );
-}
-
-function MemoryRow({
- memory,
- onPin,
- onEdit,
- onEnd,
- onForget,
-}: {
- memory: VaultMemory;
- onPin: () => void;
- onEdit: (text: string) => Promise<void>;
- onEnd: () => void;
- onForget: () => void;
-}) {
- const t = useT();
- const [editing, setEditing] = useState(false);
- const [draft, setDraft] = useState(memory.text);
- const [historyOpen, setHistoryOpen] = useState(false);
- const inputRef = useRef<HTMLInputElement>(null);
-
- const meta = [
- t(`vault.origin_${memory.origin}`),
- // An imported memory's start date is the import, not when it became true.
- memory.valid_from && memory.origin !== "imported" ? fill(t("vault.since"), { date: day(memory.valid_from) }) : "",
- memory.valid_to ? fill(t("vault.until"), { date: day(memory.valid_to) }) : "",
- memory.entities.length ? memory.entities.join(", ") : "",
- ].filter(Boolean);
-
- const save = async (event: FormEvent) => {
- event.preventDefault();
- const value = draft.trim();
- if (!value || value === memory.text) {
- setEditing(false);
- return;
- }
- await onEdit(value);
- setEditing(false);
- };
-
- return (
- <li
- data-testid="vault-row"
- data-current={memory.current || undefined}
- className={cn("group px-4 py-3", !memory.current && "opacity-60")}
- >
- {editing ? (
- <form onSubmit={save} className="flex items-center gap-2">
- <input
- ref={inputRef}
- autoFocus
- value={draft}
- onChange={(event) => setDraft(event.target.value)}
- onKeyDown={(event) => event.key === "Escape" && setEditing(false)}
- aria-label={t("vault.edit")}
- className="h-8 flex-1 rounded-md border border-border-strong bg-background px-2 text-sm text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- />
- <Button type="submit" size="sm">
- <Check /> {t("vault.save")}
- </Button>
- <Button type="button" size="sm" variant="ghost" onClick={() => setEditing(false)}>
- <X />
- </Button>
- </form>
- ) : (
- <div className="flex items-start gap-3">
- <div className="min-w-0 flex-1">
- <p className={cn("text-sm leading-relaxed text-foreground", !memory.current && "line-through decoration-muted-foreground/50")}>
- {memory.pinned && <Pin className="mr-1.5 inline h-3.5 w-3.5 -translate-y-px text-accent" aria-label={t("vault.pinned")} />}
- {memory.text}
- </p>
- <p className="mt-0.5 text-xs text-muted-foreground">
- {meta.join(" · ")}
- {memory.sensitivity === "sensitive" && (
- <span className="ml-1.5 rounded border border-border px-1 py-px text-[10px] uppercase tracking-wide">
- {t("vault.sensitive")}
- </span>
- )}
- </p>
- </div>
- <div className="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100">
- {memory.supersedes_id && (
- <IconButton label={t("vault.history")} onClick={() => setHistoryOpen((v) => !v)}>
- <History />
- </IconButton>
- )}
- {memory.current && (
- <>
- <IconButton label={memory.pinned ? t("vault.unpin") : t("vault.pin")} onClick={onPin}>
- {memory.pinned ? <PinOff /> : <Pin />}
- </IconButton>
- <IconButton
- label={t("vault.edit")}
- onClick={() => {
- setDraft(memory.text);
- setEditing(true);
- }}
- >
- <Pencil />
- </IconButton>
- <IconButton label={t("vault.end")} onClick={onEnd}>
- <CircleOff />
- </IconButton>
- </>
- )}
- <IconButton label={t("vault.forget")} onClick={onForget} danger>
- <Trash2 />
- </IconButton>
- </div>
- </div>
- )}
- {historyOpen && <Versions id={memory.id} />}
- </li>
- );
-}
-
-function IconButton({
+function SidebarItem({
+ active,
+ icon,
+ hue,
label,
+ count,
onClick,
- danger = false,
- children,
}: {
+ active: boolean;
+ icon: React.ReactNode;
+ hue: string;
label: string;
+ count?: number;
onClick: () => void;
- danger?: boolean;
- children: React.ReactNode;
}) {
return (
<button
type="button"
- title={label}
- aria-label={label}
onClick={onClick}
+ aria-current={active ? "page" : undefined}
className={cn(
- "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&>svg]:h-3.5 [&>svg]:w-3.5",
- danger ? "hover:text-destructive" : "hover:text-foreground",
+ "flex h-8 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-[13px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ active ? "bg-accent-soft text-foreground-strong" : "text-foreground hover:bg-sheen/[0.05]",
)}
>
- {children}
+ <span
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md [&>svg]:h-3 [&>svg]:w-3"
+ style={{ backgroundColor: `hsl(${hue} / 0.16)`, color: `hsl(${hue})` }}
+ >
+ {icon}
+ </span>
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {count !== undefined && <span className="text-[11px] tabular-nums text-muted-foreground">{count}</span>}
</button>
);
}
-function Versions({ id }: { id: string }) {
- const t = useT();
- const history = useVaultHistory(id);
- const versions = history.data?.versions ?? [];
- return (
- <ol className="mt-3 space-y-1.5 border-l border-border pl-3" data-testid="vault-versions">
- {versions.map((version) => (
- <li key={version.id} className="text-xs">
- <span className="text-muted-foreground">{day(version.valid_from)} · </span>
- <span className={version.current ? "text-foreground" : "text-muted-foreground line-through"}>
- {version.text}
- </span>
- {version.current && <span className="ml-1.5 text-accent">{t("vault.now")}</span>}
- </li>
- ))}
- </ol>
- );
-}
-
-function Panel({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {
- return (
- <section className="rounded-xl border border-border bg-card p-4">
- <h2 className="text-sm font-medium text-foreground">{title}</h2>
- {hint && <p className="mt-1 text-xs leading-relaxed text-muted-foreground">{hint}</p>}
- <div className="mt-3">{children}</div>
- </section>
- );
-}
-
-function AlwaysInMind({ block, name }: { block: string; name: string }) {
- const t = useT();
- const body = block.split("\n").slice(2).join("\n").trim();
+function Segmented<T extends string>({
+ value,
+ onChange,
+ options,
+}: {
+ value: T;
+ onChange: (value: T) => void;
+ options: Array<{ value: T; label: string }>;
+}) {
return (
- <Panel title={t("vault.always_title")} hint={fill(t("vault.always_hint"), { name })}>
- {body ? (
- <pre
- data-testid="vault-prompt-block"
- className="max-h-[320px] overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-background/60 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground"
+ <div role="tablist" className="flex h-8 items-center rounded-lg bg-sheen/[0.06] p-0.5">
+ {options.map((option) => (
+ <button
+ key={option.value}
+ type="button"
+ role="tab"
+ aria-selected={value === option.value}
+ data-testid={`vault-mode-${option.value}`}
+ onClick={() => onChange(option.value)}
+ className={cn(
+ "h-7 whitespace-nowrap rounded-md px-3 text-[12px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ value === option.value
+ ? "bg-surface-raised text-foreground-strong shadow-sm"
+ : "text-muted-foreground hover:text-foreground",
+ )}
>
- {body}
- </pre>
- ) : (
- <p className="text-xs text-muted-foreground">{t("vault.always_empty")}</p>
- )}
- </Panel>
- );
-}
-
-function RecentChanges() {
- const t = useT();
- const activity = useVaultActivity();
- const entries = (activity.data?.entries ?? []).filter((e) => e.action !== "pin" && e.action !== "unpin");
- return (
- <Panel title={t("vault.recent_title")}>
- {entries.length === 0 ? (
- <p className="text-xs text-muted-foreground">{t("vault.recent_empty")}</p>
- ) : (
- <ul className="space-y-2" data-testid="vault-activity">
- {entries.slice(0, 8).map((entry) => (
- <li key={entry.seq} className="text-xs leading-snug">
- <span className="font-medium text-foreground">{t(`vault.action_${entry.action}`)}</span>
- <span className="text-muted-foreground"> · {day(entry.at)}</span>
- {entry.text && <p className="mt-0.5 line-clamp-2 text-muted-foreground">{entry.text}</p>}
- </li>
- ))}
- </ul>
- )}
- </Panel>
+ {option.label}
+ </button>
+ ))}
+ </div>
);
}
-function Portability({ onImported, onError }: { onImported: (message: string) => void; onError: (message: string) => void }) {
- const t = useT();
- const fileRef = useRef<HTMLInputElement>(null);
- const [busy, setBusy] = useState(false);
- const pick = async (file: File | undefined) => {
- if (!file) return;
- setBusy(true);
- try {
- const report = await importBundle(file);
- onImported(fill(t("vault.import_done"), { added: report.added, skipped: report.skipped }));
- } catch (error) {
- onError(error instanceof Error ? error.message : String(error));
- } finally {
- setBusy(false);
- if (fileRef.current) fileRef.current.value = "";
- }
- };
- return (
- <Panel title={t("vault.portable_title")} hint={t("vault.portable_hint")}>
- <div className="flex flex-col gap-2">
- <Button asChild variant="secondary" size="sm" className="justify-start">
- <a href={exportUrl("bundle")} download data-testid="vault-export-bundle">
- <Download /> {t("vault.export_bundle")}
- </a>
- </Button>
- <Button asChild variant="ghost" size="sm" className="justify-start">
- <a href={exportUrl("markdown")} download data-testid="vault-export-markdown">
- <Download /> {t("vault.export_markdown")}
- </a>
- </Button>
- <Button
- variant="ghost"
- size="sm"
- className="justify-start"
- disabled={busy}
- onClick={() => fileRef.current?.click()}
- data-testid="vault-import"
- >
- {busy ? <Loader2 className="animate-spin" /> : <Upload />} {t("vault.import")}
- </Button>
- <input
- ref={fileRef}
- type="file"
- accept=".zip,application/zip"
- className="hidden"
- onChange={(event) => void pick(event.target.files?.[0])}
- />
- </div>
- </Panel>
- );
-}
diff --git a/dodaios/ui/web/personal_memory_routes.py b/dodaios/ui/web/personal_memory_routes.py
index 32cede5735..832c92eb11 100644
--- a/dodaios/ui/web/personal_memory_routes.py
+++ b/dodaios/ui/web/personal_memory_routes.py
@@ -85,18 +85,47 @@ def _kind(kind: str, text: str) -> str:
@router.get("")
def overview() -> dict[str, Any]:
- from dodaios.memory.vault.runtime import prompt_block
+ from dodaios.memory.vault.runtime import budget_chars, prompt_block
vault = _vault()
+ budget = budget_chars()
+ block = prompt_block()
+ selection = vault.profile_selection(max_chars=budget)
return {
"path": str(vault.path),
"stats": vault.stats(),
"kinds": list(KINDS),
- "prompt_block": prompt_block(),
+ "prompt_block": block,
+ "in_mind_ids": [m.id for _, memories in selection for m in memories],
+ "budget_chars": budget,
+ "used_chars": len(vault.profile_block(max_chars=budget)),
"imported": vault.get_meta("legacy_import") is not None,
}
+def files() -> dict[str, Any]:
+ """The memory as readable Markdown files, exactly as the export writes them."""
+ from dodaios.memory.vault.portable import markdown_files
+
+ vault = _vault()
+ rendered = markdown_files(vault)
+ order = ["MEMORY.md", *(f"{k}.md" for k in KINDS)]
+ return {
+ "files": [
+ {
+ "name": name,
+ "kind": name[:-3] if name != "MEMORY.md" else "index",
+ "bytes": len(rendered[name].encode()),
+ "lines": rendered[name].count("\n"),
+ "content": rendered[name],
+ }
+ for name in order
+ if name in rendered
+ ]
+ }
+
+
@router.get("/items")
def items(
kind: str = Query(default=""),
diff --git a/tests/unit/ui/web/test_personal_memory_routes.py b/tests/unit/ui/web/test_personal_memory_routes.py
index d6c62e8539..c650fa880e 100644
--- a/tests/unit/ui/web/test_personal_memory_routes.py
+++ b/tests/unit/ui/web/test_personal_memory_routes.py
@@ -92,3 +92,15 @@ def test_export_and_reimport(client, tmp_path):
report = client.post("/api/memory/vault/import", content=bundle.content).json()
assert report["added"] == 1
assert client.post("/api/memory/vault/import", content=b"junk").status_code == 422
+
+
+def test_overview_names_what_is_in_mind_and_files_render(client, vault):
+ client.post("/api/memory/vault/items", json={"text": "I live in Berlin.", "kind": "profile"})
+ client.post("/api/memory/vault/items", json={"text": "We hiked on Sunday.", "kind": "episode"})
+ overview = client.get("/api/memory/vault").json()
+ in_mind = {m.text for m in vault.list() if m.id in overview["in_mind_ids"]}
+ assert in_mind == {"I live in Berlin."}
+ assert 0 < overview["used_chars"] <= overview["budget_chars"]
+ files = client.get("/api/memory/vault/files").json()["files"]
+ assert [f["name"] for f in files] == ["MEMORY.md", "profile.md", "episode.md"]
+ assert "I live in Berlin." in files[1]["content"]