Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(vault): read agent knowledge natively in MSO

Abdurrahman Fakhrul8403c5c042ac
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index eaa7b210..4ccd5f90 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -350,4 +350,6 @@ Inbound channel events may dispatch into the existing Workflow Graph engine thro
## Memory graph
+Agent Vault (`/agent-vault`) is a native reader for private repository snapshots. It loads metadata first and one note per selection, searches titles/types/source paths locally, and uses container queries for side-by-side desktop versus single-panel mobile navigation. Its inert Markdown reader resolves links only to published snapshot notes; HTML and resource embeds remain text. Backlinks reuse the existing owner-only Memory projection on demand, and opening Memory passes the selected snapshot root explicitly. Organization remains the authority for team/agent structure. Personal Markdown under each vault's `Notes/` directory uses the existing guarded Files API and Code editor; generated snapshot metadata and source repositories are unaffected. No additional service, database, polling loop or Markdown dependency is required.
+
`frontend/slices/memory-graph/` is the owner-only Memory app at `/memory` (`mso memory-graph`). It draws vault markdown, project `.mso/KNOWLEDGE.md`, repo-local `.agent` memory, the signed-in device's typed agent memory, and assistant memories. Unresolved `[[wikilinks]]` are ghost nodes. Web, radial, and layered layouts plus a local hop neighbourhood are client-side. This surface is inspired by open-silong's memory graph (MIT) and does not depend on Obsidian or Convex. It is not the Workflow session graph. See [`MEMORY-GRAPH.md`](./MEMORY-GRAPH.md).
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 84fde93f..24dbfe9a 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
## 2026-10-10
+**Added**
+
+- `vault` read agent knowledge natively in MSO
+
**Fixed**
- `mcp` retain scanner limits and document mailbox parity
diff --git a/docs/MEMORY-GRAPH.md b/docs/MEMORY-GRAPH.md
index f9ca52ef..aaa60e94 100644
--- a/docs/MEMORY-GRAPH.md
+++ b/docs/MEMORY-GRAPH.md
@@ -24,6 +24,7 @@ for the exact scope, privacy boundaries and remaining limits.
- **Local** keeps the selected node and its neighbourhood. Hops are 1–4. With nothing selected, the highest-degree node is the centre.
- **Ghosts**, **Tags**, and **Orphans** toggle those nodes. Group chips hide a color group.
- Click a node to select it. Click it again, double-click it, or press **Open** to open a note that has a file path in Code.
+- Agent Vault opens Memory with its selected snapshot directory and repository as explicit window context. This does not change the saved default root. Vault backlinks reuse this owner-only projection on demand, without loading the graph renderer in the note reader.
- Drag the background to pan. Scroll to zoom.
The scan is capped (notes, depth, directories, project records) and may report that it truncated. Excerpts are redacted for obvious secrets. The route is owner-only; Viewer and Operator are refused.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 64d41247..46dd0068 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,13 @@
+## 2026-10-10: Replace desktop streaming with a native repository knowledge view
+
+The owner found the streamed Obsidian desktop slow and unsuitable for mobile, and requested a KISS implementation built on Organization and Memory. Agent Vault now reads the same separate private Markdown snapshots directly in MSO. Metadata loads first, note bodies load only on selection, and local title/type/source search adds no typing requests. Mobile navigation gives the list and reader their own full pane, with an explicit return action; desktop retains a sidebar. Capture history remains recorded repository evidence rather than live agent/deployment status.
+
+The small inert Markdown reader supports headings, lists, quotes, fenced code, safe web references and links to exact published snapshot notes. HTML and embedded resources remain text. Backlinks reuse Memory's bounded owner projection only after a user asks, retaining that projection while moving between notes; the graph renderer stays deferred. Opening Memory supplies the exact selected snapshot context without replacing its saved defaults. Organization is linked through its existing app, preserving its identity and structure authority. Personal notes use a separate `Notes/` folder, guarded Files operations and the existing Code editor rather than adding another editor, store or service. No dependencies, public API/MCP schemas, authorization rules or portable operator configuration change.
+
+Regression coverage exercises safe/ambiguous/path-bounded link resolution and inert Markdown rendering. The required browser journey checks wikilink/backlink navigation, deferred connection reads, capture history, personal note creation/edit/save, separate storage, mobile list/reader reflow and live access denial. Instance domain cutover and desktop-runtime configuration remain private installation operations, outside the open-source project.
+
+The personal-note journey also exposed a Code hydration bug: the initial empty buffer was compared with an absent disk entry and misclassified as unsaved, refusing the first host read. Treat the absent baseline as empty while retaining actual edits made during an in-flight read. The real editor/browser save journey verifies initial content and the written result. Host note editing respects the selected Live adapter; mock mode offers clear guidance instead of creating a note that its editor cannot read.
+
## 2026-10-10: Close the eight findings from the 1acc1424 cloud scan
Candidate indexes use canonical credential guards during walking, seeding, cache reuse and preview reads; version 2 invalidates older caches. Git diffs use NUL-delimited filename metadata and literal pathspecs, omit protected patches/renames and redact recognizable credentials while retaining file statistics and ordinary source.
diff --git a/frontend/slices/agent-vault/components/note-preview.test.tsx b/frontend/slices/agent-vault/components/note-preview.test.tsx
new file mode 100644
index 00000000..46fa1b73
--- /dev/null
+++ b/frontend/slices/agent-vault/components/note-preview.test.tsx
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+import { NotePreview } from "./note-preview";
+
+describe("native Markdown reader", () => {
+ it("renders structured notes and activates only resolved notes or safe web URLs", () => {
+ const content = "---\nprivate: hidden\n---\n# Worker\n\n- [[Worker|Task]]\n- [Reference](https://example.org/)\n\n> recorded evidence\n\n```js\n[[Worker]]\n```\n\n**Result** and `code`";
+ const html = renderToStaticMarkup(<NotePreview content={content} resolve={target => target === "Worker" ? "snapshot/worker.md" : undefined} onOpen={() => {}} />);
+ expect(html).toContain("<h1"); expect(html).toContain("<ul"); expect(html).toContain("<blockquote");
+ expect(html).toContain("<button"); expect(html).toContain('rel="noopener noreferrer"');
+ expect(html).toContain("<code>[[Worker]]</code>"); expect(html).toContain("<strong>Result</strong>");
+ expect(html).not.toContain("private: hidden");
+ });
+ it("never executes HTML, code or embedded resources from source notes", () => {
+ const html = renderToStaticMarkup(<NotePreview content={'<script>alert(1)</script>\n\n![Tracking](https://example.org/pixel)\n\n![[Worker]]\n\n[Run](javascript:alert)\n\n<iframe src="https://example.org"></iframe>'} />);
+ expect(html).toContain("&lt;script&gt;");
+ for (const tag of ["<script", "<iframe", "<img", "<a "]) expect(html).not.toContain(tag);
+ });
+});
diff --git a/frontend/slices/agent-vault/components/note-preview.tsx b/frontend/slices/agent-vault/components/note-preview.tsx
index 27c05ccd..4b8d7e84 100644
--- a/frontend/slices/agent-vault/components/note-preview.tsx
+++ b/frontend/slices/agent-vault/components/note-preview.tsx
@@ -1,11 +1,55 @@
"use client";
-/** Text-only Markdown preview: no HTML, embedded resources or executable links. */
-export function NotePreview({ content }: { content: string }) {
- const body = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "");
- return <div className="space-y-3 text-sm leading-relaxed">{body.split(/\n\s*\n/).map((block, i) => {
- if (/^# /.test(block)) return <h1 key={i} className="text-xl font-semibold">{block.replace(/^# /, "")}</h1>;
- if (/^## /.test(block)) return <h2 key={i} className="text-base font-semibold">{block.replace(/^## /, "")}</h2>;
- if (/^### /.test(block)) return <h3 key={i} className="font-semibold">{block.replace(/^### /, "")}</h3>;
- return <p key={i} className="whitespace-pre-wrap break-words">{block}</p>;
- })}</div>;
-}
+import { Fragment, memo, type ReactNode } from "react";
+import { safeExternalLink } from "../lib/note-links";
+
+type Props = { content: string; resolve?: (target: string, wiki: boolean) => string | undefined; onOpen?: (path: string) => void };
+const INLINE = /(!?\[\[[^\]\n]+\]\]|!?\[[^\]\n]*\]\([^\s)]+\)|`[^`\n]+`|\*\*[^*\n]+\*\*)/g;
+
+/** Inert Markdown reader. HTML/embeds stay text; only reviewed note/web links activate. */
+export const NotePreview = memo(function NotePreview({ content, resolve, onOpen }: Props) {
+ function inline(text: string): ReactNode {
+ return text.split(INLINE).map((part, i) => {
+ if (part.startsWith("!")) return <Fragment key={i}>{part}</Fragment>;
+ if (part.startsWith("`")) return <code key={i} className="rounded bg-muted px-1 break-words">{part.slice(1, -1)}</code>;
+ if (part.startsWith("**")) return <strong key={i}>{part.slice(2, -2)}</strong>;
+ const wiki = part.match(/^\[\[([^\]|]+)(?:\|([^\]]+))?\]\]$/);
+ const md = part.match(/^\[([^\]]*)\]\(([^)]+)\)$/);
+ if (!wiki && !md) return <Fragment key={i}>{part}</Fragment>;
+ const target = wiki ? wiki[1] : md![2], label = wiki ? wiki[2] || target : md![1];
+ const path = resolve?.(target, !!wiki);
+ if (path && onOpen) return <button key={i} type="button" className="inline text-left text-primary underline underline-offset-2 break-words" onClick={() => onOpen(path)}>{label}</button>;
+ const href = !wiki && safeExternalLink(target);
+ return href ? <a key={i} href={href} target="_blank" rel="noopener noreferrer" className="text-primary underline break-words">{label}</a> : <span key={i}>{label}</span>;
+ });
+ }
+ const lines = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "").split(/\r?\n/);
+ const blocks: ReactNode[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i], key = i;
+ if (!line.trim()) continue;
+ const fence = line.match(/^\s*(`{3,}|~{3,})(.*)$/);
+ if (fence) {
+ const code: string[] = [];
+ while (++i < lines.length && !lines[i].trim().startsWith(fence[1])) code.push(lines[i]);
+ blocks.push(<pre key={key} className="max-w-full overflow-x-auto rounded-lg bg-muted p-3 text-xs"><code>{code.join("\n")}</code></pre>); continue;
+ }
+ const heading = line.match(/^(#{1,6})\s+(.+)$/);
+ if (heading) {
+ const Tag = `h${heading[1].length}` as "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
+ blocks.push(<Tag key={key} className={heading[1].length === 1 ? "text-xl font-semibold" : "font-semibold"}>{inline(heading[2])}</Tag>); continue;
+ }
+ if (/^\s*(?:[-*+]\s|\d+\.\s)/.test(line)) {
+ const ordered = /^\s*\d+\./.test(line), items: ReactNode[] = [];
+ const pattern = ordered ? /^\s*\d+\.\s/ : /^\s*[-*+]\s/;
+ do { items.push(<li key={i}>{inline(lines[i].replace(pattern, ""))}</li>); i++; } while (i < lines.length && pattern.test(lines[i]));
+ i--; const Tag = ordered ? "ol" : "ul";
+ blocks.push(<Tag key={key} className="space-y-1 pl-5" style={{ listStyleType: ordered ? "decimal" : "disc" }}>{items}</Tag>); continue;
+ }
+ if (line.startsWith(">")) { blocks.push(<blockquote key={key} className="border-l pl-3 text-muted-foreground">{inline(line.replace(/^>\s?/, ""))}</blockquote>); continue; }
+ if (/^\s*([-*_])(?:\s*\1){2,}\s*$/.test(line)) { blocks.push(<hr key={key} />); continue; }
+ const paragraph = [line];
+ while (i + 1 < lines.length && lines[i + 1].trim() && !/^(?:#{1,6}\s|>|\s*[-*+]\s|\s*\d+\.\s|\s*```|\s*~~~)/.test(lines[i + 1])) paragraph.push(lines[++i]);
+ blocks.push(<p key={key} className="whitespace-pre-wrap">{inline(paragraph.join("\n"))}</p>);
+ }
+ return <div className="space-y-4 text-sm leading-relaxed [overflow-wrap:anywhere]">{blocks}</div>;
+});
diff --git a/frontend/slices/agent-vault/components/personal-notes.tsx b/frontend/slices/agent-vault/components/personal-notes.tsx
new file mode 100644
index 00000000..427c243a
--- /dev/null
+++ b/frontend/slices/agent-vault/components/personal-notes.tsx
@@ -0,0 +1,55 @@
+"use client";
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { openWindow, useOsApi } from "@/features/appshell";
+import type { FsEntry, FsList } from "@/lib/contracts/os-api";
+
+/** Personal Markdown uses the existing guarded Files API and Code editor. */
+export function PersonalNotes({ root }: { root: string }) {
+ const api = useOsApi();
+ const directory = `${root}/Notes`;
+ const [entries, setEntries] = useState<FsEntry[]>([]), [title, setTitle] = useState("");
+ const [busy, setBusy] = useState(false), [error, setError] = useState("");
+ const load = useCallback(async (signal?: AbortSignal) => {
+ const response = await fetch(`/api/v1/fs/list?${new URLSearchParams({ path: directory })}`, { cache: "no-store", signal });
+ const result = await response.json();
+ if (response.status === 404) return [];
+ if (!response.ok) throw new Error(result.error || "Could not read personal notes");
+ return (result as FsList).entries.filter(entry => entry.kind === "file" && entry.name.endsWith(".md"));
+ }, [directory]);
+ useEffect(() => {
+ const controller = new AbortController();
+ void load(controller.signal).then(next => { if (!controller.signal.aborted) setEntries(next); }).catch(cause => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Could not read personal notes"); });
+ return () => controller.abort();
+ }, [load]);
+ async function create() {
+ const heading = title.trim();
+ if (!heading || busy || api.mode !== "live") return;
+ setBusy(true); setError("");
+ try {
+ const name = `${heading.replace(/[^a-zA-Z0-9_-]+/g, "-").slice(0, 60) || "note"}-${crypto.randomUUID()}.md`;
+ const path = `${directory}/${name}`;
+ for (const [operation, body] of [["mkdir", { path: directory }], ["write", { path, content: `# ${heading.replace(/[\r\n]/g, " ")}\n\n` }]] as const) {
+ const response = await fetch(`/api/v1/fs/${operation}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ if (!response.ok) { const result = await response.json(); throw new Error(result.error || "Could not create note"); }
+ }
+ setTitle(""); setEntries(await load());
+ openWindow("code-editor", heading, undefined, { path });
+ } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not create note"); }
+ finally { setBusy(false); }
+ }
+ return <section className="space-y-4" aria-label="Personal notes">
+ <h1 className="text-xl font-semibold">Personal notes</h1>
+ <p className="text-sm text-muted-foreground">Your Markdown notes are stored separately from generated snapshots. Open a note in the MSO editor to write and save.</p>
+ {api.mode !== "live" ? <p className="text-sm text-muted-foreground">Choose Live in Settings → Server to edit host notes.</p> : null}
+ <form className="flex min-w-0 gap-2" onSubmit={event => { event.preventDefault(); void create(); }}>
+ <Input aria-label="New note title" maxLength={120} placeholder="Note title" className="min-w-0 flex-1" value={title} onChange={event => setTitle(event.target.value)} />
+ <Button type="submit" disabled={busy || !title.trim() || api.mode !== "live"}>{busy ? "Creating…" : "New note"}</Button>
+ </form>
+ {error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}
+ <Button size="sm" variant="outline" onClick={() => { setError(""); void load().then(setEntries).catch(cause => setError(cause instanceof Error ? cause.message : "Could not read notes")); }}>Reload notes</Button>
+ <div className="space-y-2">{entries.map(entry => <Button key={entry.name} variant="outline" disabled={api.mode !== "live"} className="w-full justify-start" onClick={() => openWindow("code-editor", entry.name, undefined, { path: `${directory}/${entry.name}` })}><span className="truncate">{entry.name.replace(/-[a-f\d-]{36}\.md$/, "").replace(/\.md$/, "")}</span></Button>)}</div>
+ {!error && !entries.length ? <p className="text-sm text-muted-foreground">Create your first personal note.</p> : null}
+ </section>;
+}
diff --git a/frontend/slices/agent-vault/components/vault-connections.tsx b/frontend/slices/agent-vault/components/vault-connections.tsx
new file mode 100644
index 00000000..912aeddd
--- /dev/null
+++ b/frontend/slices/agent-vault/components/vault-connections.tsx
@@ -0,0 +1,36 @@
+"use client";
+import { useEffect, useMemo, useState } from "react";
+import { Button } from "@/components/ui/button";
+import type { AgentVaultNote } from "@/lib/contracts/agent-vault";
+import type { MemoryGraphDocument } from "@/lib/memory-graph/types";
+
+/** Reuse Memory's bounded link projection on demand; no graph renderer in the reader bundle. */
+export function VaultConnections({ root, project, notes, selectedPath, vaultRoot, onOpen }: {
+ root: string; project: string; notes: AgentVaultNote[]; selectedPath: string; vaultRoot: string; onOpen: (path: string) => void;
+}) {
+ const [open, setOpen] = useState(false), [graph, setGraph] = useState<MemoryGraphDocument | null>(null), [error, setError] = useState("");
+ useEffect(() => {
+ if (!open || graph) return;
+ const controller = new AbortController();
+ void fetch(`/api/v1/memory-graph?${new URLSearchParams({ root, project })}`, { cache: "no-store", signal: controller.signal }).then(async response => {
+ const result = await response.json();
+ if (!response.ok) throw new Error(result.error || "Could not load connections");
+ if (!controller.signal.aborted) setGraph(result);
+ }).catch(cause => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Could not load connections"); });
+ return () => controller.abort();
+ }, [open, graph, root, project]);
+ const backlinks = useMemo(() => {
+ if (!graph) return [];
+ const target = graph.nodes.find(node => node.path === `${vaultRoot}/${selectedPath}`);
+ const sources = new Set(graph.edges.filter(edge => edge.target === target?.id && edge.resolved && ["wikilink", "mention"].includes(edge.kind)).map(edge => edge.source));
+ const paths = new Set(graph.nodes.filter(node => sources.has(node.id)).map(node => node.path));
+ return notes.filter(note => paths.has(`${vaultRoot}/${note.path}`));
+ }, [graph, notes, selectedPath, vaultRoot]);
+ return <section className="mt-6 border-t pt-3" aria-label="Note backlinks">
+ <Button variant="ghost" size="sm" aria-expanded={open} onClick={() => { setError(""); setOpen(!open); }}>Backlinks{graph ? ` · ${backlinks.length}` : ""}</Button>
+ {open ? <div className="mt-2 space-y-2 text-xs">
+ {error ? <p role="alert" className="text-destructive">{error}</p> : !graph ? <p role="status" className="text-muted-foreground">Loading connections…</p> : backlinks.length ? backlinks.map(note => <Button key={note.path} size="sm" variant="outline" className="mr-2 max-w-full" onClick={() => onOpen(note.path)}><span className="truncate">{note.title}</span></Button>) : <p className="text-muted-foreground">No backlinks in this snapshot.</p>}
+ {graph?.truncated || graph?.warnings.length ? <p className="text-muted-foreground">Connections may be partial. {graph.warnings.join(" · ")}</p> : null}
+ </div> : null}
+ </section>;
+}
diff --git a/frontend/slices/agent-vault/components/vault-history.tsx b/frontend/slices/agent-vault/components/vault-history.tsx
new file mode 100644
index 00000000..97fbc4e0
--- /dev/null
+++ b/frontend/slices/agent-vault/components/vault-history.tsx
@@ -0,0 +1,14 @@
+import type { AgentVaultState } from "@/lib/contracts/agent-vault";
+
+export function VaultHistory({ state, selected, onSelect }: { state: AgentVaultState; selected: string; onSelect: (id: string) => void }) {
+ const snapshots = [...state.snapshots].sort((a, b) => b.capturedAt.localeCompare(a.capturedAt));
+ return <div className="p-3">
+ <p className="mb-3 text-xs text-muted-foreground">Recorded changes from repository captures. Refresh to capture new evidence.</p>
+ <ol className="space-y-2">{snapshots.map(snapshot => <li key={snapshot.id}>
+ <button type="button" aria-pressed={snapshot.id === selected} onClick={() => onSelect(snapshot.id)} className={`w-full rounded-lg border p-3 text-left hover:bg-muted ${snapshot.id === selected ? "bg-muted" : ""}`}>
+ <time dateTime={snapshot.capturedAt} className="block text-sm font-medium">{new Date(snapshot.capturedAt).toLocaleString()}</time>
+ <span className="text-xs text-muted-foreground">{snapshot.notes.length} notes{snapshot.id === state.current ? " · latest" : ""}{snapshot.truncated ? " · partial" : ""}</span>
+ </button>
+ </li>)}</ol>
+ </div>;
+}
diff --git a/frontend/slices/agent-vault/components/vault-screen.module.css b/frontend/slices/agent-vault/components/vault-screen.module.css
new file mode 100644
index 00000000..7706b49c
--- /dev/null
+++ b/frontend/slices/agent-vault/components/vault-screen.module.css
@@ -0,0 +1,6 @@
+/* Pane width, including small desktop windows; loaded with the native Vault. */
+@container (min-width: 560px) {
+ .navigation { display: flex; width: 16rem; }
+ .reader { display: flex; }
+ .back { display: none; }
+}
diff --git a/frontend/slices/agent-vault/components/vault-screen.tsx b/frontend/slices/agent-vault/components/vault-screen.tsx
index 6968b7a6..00a431e9 100644
--- a/frontend/slices/agent-vault/components/vault-screen.tsx
+++ b/frontend/slices/agent-vault/components/vault-screen.tsx
@@ -1,96 +1,82 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { FolderOpen, RefreshCw } from "lucide-react";
+import { useCallback, useMemo, useState } from "react";
+import { ArrowLeft, FolderOpen, Network, RefreshCw, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { openWindow } from "@/features/appshell";
-import type { AgentVaultState, AgentVaultView } from "@/lib/contracts/agent-vault";
+import { useSession } from "@/features/auth";
+import { resolveNoteLink } from "../lib/note-links";
+import { useVault } from "../lib/use-vault";
import { NotePreview } from "./note-preview";
+import { VaultConnections } from "./vault-connections";
+import { VaultHistory } from "./vault-history";
+import { PersonalNotes } from "./personal-notes";
+import styles from "./vault-screen.module.css";
-const KEY = "mso:agent-vault:project";
-async function request(project: string, options: { sync?: boolean; note?: string; signal?: AbortSignal } = {}): Promise<AgentVaultView> {
- const params = new URLSearchParams();
- if (project.trim()) params.set("project", project.trim());
- if (options.note) params.set("note", options.note);
- const response = await fetch(`/api/v1/agent-vault?${params}`, options.sync ? {
- method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(project.trim() ? { project: project.trim() } : {}), signal: options.signal,
- } : { cache: "no-store", signal: options.signal });
- const result = await response.json();
- if (!response.ok) throw new Error(result.error || `Request failed (${response.status})`);
- return result as AgentVaultView;
-}
export function VaultScreen() {
- const [project, setProject] = useState(() => typeof window === "undefined" ? "" : localStorage.getItem(KEY) || "");
- const [state, setState] = useState<AgentVaultState | null>(null);
- const [snapshotId, setSnapshotId] = useState("");
- const [note, setNote] = useState<{ path: string; content: string } | null>(null);
- const [filter, setFilter] = useState("");
- const [busy, setBusy] = useState(false), [noteBusy, setNoteBusy] = useState(false), [error, setError] = useState("");
- const requests = useRef(0), noteRequests = useRef(0);
- const load = useCallback(async (hint: string, sync = false) => {
- const token = ++requests.current;
- ++noteRequests.current;
- setBusy(true); setError(""); setState(null); setNote(null); setNoteBusy(false);
- try {
- const result = await request(hint, { sync });
- if (token !== requests.current) return;
- setState(result.state); setSnapshotId(result.state.current || "");
- setProject(result.state.project.path);
- localStorage.setItem(KEY, result.state.project.path);
- } catch (cause) { if (token === requests.current) setError(cause instanceof Error ? cause.message : "Could not load vault"); }
- finally { if (token === requests.current) setBusy(false); }
- }, []);
- useEffect(() => {
- const controller = new AbortController(), token = ++requests.current;
- let alive = true;
- request(localStorage.getItem(KEY) || "", { signal: controller.signal }).then(result => {
- if (!alive || token !== requests.current) return;
- setState(result.state); setSnapshotId(result.state.current || ""); setProject(result.state.project.path);
- }, cause => { if (alive && token === requests.current) setError(cause instanceof Error ? cause.message : "Could not load vault"); });
- return () => { alive = false; controller.abort(); };
- }, []);
+ const vault = useVault();
+ const { state, snapshotId, note, selectedPath, busy, noteBusy, error, select } = vault;
+ const { status, role } = useSession();
+ const [filter, setFilter] = useState(""), [kind, setKind] = useState("all");
+ const [mobileReader, setMobileReader] = useState(false), [history, setHistory] = useState(false);
+ const [personal, setPersonal] = useState(false);
const snapshot = state?.snapshots.find(s => s.id === snapshotId);
- const notes = useMemo(() => snapshot?.notes.filter(n => `${n.title} ${n.kind} ${n.source}`.toLowerCase().includes(filter.toLowerCase())) || [], [snapshot, filter]);
- const selected = snapshot?.notes.find(n => n.path === note?.path);
- async function select(path: string) {
- if (!state) return;
- const token = ++noteRequests.current;
- setNoteBusy(true); setError(""); setNote(null);
- try { const result = await request(state.project.path, { note: path }); if (token === noteRequests.current) setNote(result.note || null); }
- catch (cause) { if (token === noteRequests.current) setError(cause instanceof Error ? cause.message : "Could not read note"); }
- finally { if (token === noteRequests.current) setNoteBusy(false); }
- }
- return <div className="flex h-full min-h-0 flex-col">
- <form className="flex shrink-0 flex-wrap items-center gap-2 border-b p-2" onSubmit={e => { e.preventDefault(); void load(project); }}>
- <Input aria-label="Repository" placeholder="Repository name, id or path" value={project} onChange={e => setProject(e.target.value)} className="min-w-0 flex-1" />
- <Button variant="outline" type="submit" disabled={busy}>Load</Button>
- <Button type="button" disabled={busy} onClick={() => void load(project, true)}><RefreshCw className="mr-1 size-4" />{busy ? "Loading…" : "Refresh snapshot"}</Button>
- </form>
+ const notes = useMemo(() => snapshot?.notes.filter(n => (kind === "all" || n.kind === kind) && `${n.title} ${n.kind} ${n.source}`.toLowerCase().includes(filter.toLowerCase())) || [], [snapshot, filter, kind]);
+ const selected = snapshot?.notes.find(n => n.path === selectedPath);
+ const graphRoot = state && snapshot ? `${state.root}/Snapshots/${snapshot.id}` : "";
+ const openNote = useCallback((path: string) => { setPersonal(false); setMobileReader(true); void select(path); }, [select]);
+ const resolveLink = useCallback((target: string, wiki: boolean) => resolveNoteLink(snapshot?.notes || [], note?.path || "", target, wiki)?.path, [snapshot, note?.path]);
+ function chooseSnapshot(id: string) { setPersonal(false); setMobileReader(false); setHistory(false); vault.chooseSnapshot(id); }
+
+ if (status !== "in" || role !== "owner") return <p className="p-4 text-sm text-muted-foreground">Owner access is required to open private repository notes.</p>;
+ return <div data-slot="native-vault" className="flex h-full min-h-0 min-w-0 flex-col">
+ <header className="flex min-w-0 shrink-0 items-center gap-2 border-b px-3 py-2">
+ <div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{state?.project.name || "Agent Vault"}</h2><p className="truncate text-xs text-muted-foreground">{snapshot ? `${snapshot.notes.length} notes · ${new Date(snapshot.capturedAt).toLocaleString()}` : "Repository knowledge and recorded progress"}</p></div>
+ <Button size="sm" variant="outline" aria-label="Open Memory graph" disabled={!snapshot || busy} onClick={() => openWindow("memory-graph", "Memory", undefined, { root: graphRoot, project: state!.project.path })}><Network className="size-4" /><span className="hidden @min-[480px]:inline">Memory</span></Button>
+ <Button size="sm" variant="outline" aria-label="Open Organization" onClick={() => openWindow("organization", "Organization")}><Users className="size-4" /><span className="hidden @min-[480px]:inline">Organization</span></Button>
+ <Button size="sm" disabled={busy} onClick={() => { setMobileReader(false); void vault.load(state?.project.path || vault.project, true); }}><RefreshCw className={`size-4 ${busy ? "animate-spin" : ""}`} /><span>{busy ? "Loading…" : "Refresh snapshot"}</span></Button>
+ </header>
<details className="shrink-0 border-b px-3 py-1 text-xs text-muted-foreground">
- <summary className="cursor-pointer">Separate Obsidian vault{state ? ` · ${state.project.name}` : ""}{snapshot?.truncated ? " · partial snapshot" : ""}</summary>
- <p className="py-1">Agent progress from your repository. Refresh captures a snapshot; source notes remain authoritative.</p>
- {state ? <div className="flex flex-wrap items-center gap-2"><span className="break-all">{state.root}</span><Button size="sm" variant="ghost" disabled={!state.current} onClick={() => openWindow("files-manager", "Agent Vault files", undefined, { path: state.root })}><FolderOpen className="mr-1 size-4" />Files</Button></div> : null}
- {snapshot?.warnings.length ? <p className="py-1">{snapshot.warnings.join(" · ")}</p> : null}
+ <summary className="cursor-pointer">Repository &amp; storage{snapshot?.truncated ? " · partial snapshot" : ""}</summary>
+ <form className="flex min-w-0 gap-2 py-2" onSubmit={e => { e.preventDefault(); setMobileReader(false); void vault.load(vault.project); }}>
+ <Input aria-label="Repository" placeholder="Repository name, id or path" value={vault.project} onChange={e => vault.setProject(e.target.value)} className="min-w-0 flex-1" />
+ <Button size="sm" variant="outline" type="submit" disabled={busy}>Load</Button>
+ </form>
+ <p>Refresh captures recorded repository evidence. Source notes remain authoritative.</p>
+ {state ? <div className="flex flex-wrap items-center gap-2 py-1"><span className="break-all">{state.root}</span><Button size="sm" variant="ghost" onClick={() => openWindow("files-manager", "Vault files", undefined, { path: state.root })}><FolderOpen className="size-4" />Files</Button></div> : null}
</details>
- {error ? <p role="alert" className="px-3 py-2 text-sm text-destructive">{error}</p> : null}
- {state && !state.current ? <p className="p-4 text-sm text-muted-foreground">No snapshot yet. Choose Refresh snapshot to collect repository agent notes, progress summaries and recent commits.</p> : null}
- {snapshot ? <>
- <div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-1">
- <label className="text-xs" htmlFor="vault-snapshot">Snapshot</label>
- <select id="vault-snapshot" className="max-w-full rounded border bg-background px-2 py-1 text-xs" value={snapshotId} onChange={e => { ++noteRequests.current; setSnapshotId(e.target.value); setNote(null); setNoteBusy(false); }}>
- {state?.snapshots.map(s => <option key={s.id} value={s.id}>{new Date(s.capturedAt).toLocaleString()}{s.id === state.current ? " · latest" : ""}</option>)}
- </select>
- <span className="text-xs text-muted-foreground">{snapshot.notes.length} notes{snapshot.truncated ? " · partial" : ""}</span>
- </div>
- <div className="flex min-h-0 flex-1 flex-col @min-[560px]:flex-row">
- <aside className="flex max-h-48 min-h-0 shrink-0 flex-col border-b @min-[560px]:max-h-none @min-[560px]:w-64">
- <div className="p-2"><Input aria-label="Search vault notes" placeholder="Search notes" value={filter} onChange={e => setFilter(e.target.value)} /></div>
- <div className="min-h-0 flex-1 overflow-auto">{notes.map(n => <button key={n.path} type="button" aria-pressed={note?.path === n.path} className={`block w-full border-b px-3 py-2 text-left text-sm hover:bg-muted ${note?.path === n.path ? "bg-muted" : ""}`} onClick={() => void select(n.path)}><span className="block truncate">{n.title}</span><span className="text-xs text-muted-foreground">{n.kind}</span></button>)}</div>
- </aside>
- <article className="min-h-0 min-w-0 flex-1 overflow-auto p-4 @min-[560px]:border-l">
- {noteBusy ? <p className="text-sm text-muted-foreground">Loading note…</p> : note ? <><p className="mb-4 break-all text-xs text-muted-foreground">Source: {selected?.source}</p><NotePreview content={note.content} /></> : <p className="text-sm text-muted-foreground">Select a note to see agent roles, project updates or recorded progress.</p>}
+ {error ? <p role="alert" className="shrink-0 px-3 py-2 text-sm text-destructive">{error}</p> : null}
+ {state && !state.current && !busy ? <p className="p-4 text-sm text-muted-foreground">No snapshot yet. Refresh snapshot to collect agent notes, progress and recent commits.</p> : null}
+ {snapshot ? <div className="flex min-h-0 min-w-0 flex-1">
+ <aside aria-label="Vault navigation" className={`${styles.navigation} ${mobileReader ? "hidden" : "flex"} min-h-0 min-w-0 w-full flex-none flex-col overflow-y-auto border-r`}>
+ <div className="shrink-0 space-y-2 border-b p-3">
+ <div className="flex flex-wrap items-center justify-between gap-1"><span className="text-xs font-medium">{history ? "Progress history" : "Notes"}</span><Button size="sm" variant="ghost" onClick={() => { setPersonal(true); setMobileReader(true); }}>Personal notes</Button><Button size="sm" variant="ghost" aria-pressed={history} onClick={() => setHistory(!history)}>{history ? "Notes" : "History"}</Button></div>
+ {!history ? <>
+ <Input aria-label="Search vault notes" placeholder="Search notes" value={filter} onChange={e => setFilter(e.target.value)} />
+ <div className="flex min-w-0 items-center gap-2"><select aria-label="Note type" className="min-w-0 flex-1 rounded border bg-background p-1 text-xs" value={kind} onChange={e => setKind(e.target.value)}>{["all", "agent", "project", "progress", "memory", "inbox", "overview"].map(k => <option key={k} value={k}>{k === "all" ? "All notes" : k}</option>)}</select><span className="text-xs text-muted-foreground">{notes.length}</span></div>
+ </> : null}
+ <select aria-label="Snapshot" className="w-full rounded border bg-background p-1 text-xs" value={snapshotId} onChange={e => chooseSnapshot(e.target.value)}>{state?.snapshots.map(s => <option key={s.id} value={s.id}>{new Date(s.capturedAt).toLocaleString()}{s.id === state.current ? " · latest" : ""}</option>)}</select>
+ </div>
+ <div className="shrink-0">
+ {history ? <VaultHistory state={state!} selected={snapshotId} onSelect={chooseSnapshot} /> : notes.length ? notes.map(n => <button key={n.path} type="button" aria-pressed={selectedPath === n.path} className={`block min-h-11 w-full border-b px-3 py-3 text-left text-sm hover:bg-muted ${selectedPath === n.path ? "bg-muted" : ""}`} onClick={() => openNote(n.path)}><span className="block truncate font-medium">{n.title}</span><span className="text-xs text-muted-foreground">{n.kind}</span></button>) : <p className="p-4 text-sm text-muted-foreground">No matching notes.</p>}
+ </div>
+ </aside>
+ <section aria-label="Note reader" className={`${styles.reader} ${mobileReader ? "flex" : "hidden"} min-h-0 min-w-0 flex-1 flex-col`}>
+ <div className="flex min-w-0 shrink-0 items-center gap-2 border-b px-3 py-2">
+ <Button size="sm" variant="ghost" className={styles.back} onClick={() => setMobileReader(false)}><ArrowLeft className="size-4" />Back to notes</Button>
+ <span className="min-w-0 flex-1 truncate text-xs font-medium">{personal ? "Personal notes" : selected?.title || "Select a note"}</span>
+ </div>
+ <article aria-busy={noteBusy} className="min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4" style={{ overscrollBehavior: "contain" }}>
+ <div className="mx-auto max-w-3xl">
+ {personal ? <PersonalNotes key={state!.root} root={state!.root} /> : noteBusy ? <p role="status" className="text-sm text-muted-foreground">Loading note…</p> : note ? <>
+ <p className="mb-4 break-all text-xs text-muted-foreground">Source: {selected?.source}</p>
+ <NotePreview content={note.content} resolve={resolveLink} onOpen={openNote} />
+ </> : <p className="text-sm text-muted-foreground">Choose an agent, project or progress note. Use History to browse earlier captures.</p>}
+ {!personal && selectedPath ? <VaultConnections key={graphRoot} root={graphRoot} project={state!.project.path} notes={snapshot.notes} selectedPath={selectedPath} vaultRoot={state!.root} onOpen={openNote} /> : null}
+ {snapshot.warnings.length ? <p className="mt-6 text-xs text-muted-foreground">{snapshot.warnings.join(" · ")}</p> : null}
+ </div>
</article>
- </div>
- </> : null}
+ </section>
+ </div> : null}
</div>;
}
diff --git a/frontend/slices/agent-vault/lib/note-links.test.ts b/frontend/slices/agent-vault/lib/note-links.test.ts
new file mode 100644
index 00000000..1f1366cd
--- /dev/null
+++ b/frontend/slices/agent-vault/lib/note-links.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import type { AgentVaultNote } from "@/lib/contracts/agent-vault";
+import { resolveNoteLink, safeExternalLink } from "./note-links";
+
+const root = "Snapshots/aaaaaaaaaaaaaaaaaaaa";
+const notes: AgentVaultNote[] = [
+ { path: `${root}/overview/Beranda.md`, title: "Agent progress", kind: "overview", source: "generated" },
+ { path: `${root}/agent/worker.md`, title: "Worker", kind: "agent", source: "wiki/agents/worker.md" },
+];
+describe("published vault note links", () => {
+ it("resolves snapshot paths, relative Markdown and aliases without leaving the selected snapshot", () => {
+ expect(resolveNoteLink(notes, notes[0].path, notes[1].path.replace(/\.md$/, ""), true)).toBe(notes[1]);
+ expect(resolveNoteLink(notes, notes[0].path, "../agent/worker.md#Tasks")).toBe(notes[1]);
+ expect(resolveNoteLink(notes, notes[0].path, "Worker#Tasks", true)).toBe(notes[1]);
+ for (const target of ["../../../private.md", "/etc/passwd", "file:///etc/passwd", "javascript:alert(1)", "%ZZ", "Snapshots/bbbbbbbbbbbbbbbbbbbb/agent/worker.md"]) {
+ expect(resolveNoteLink(notes, notes[0].path, target)).toBeUndefined();
+ }
+ const duplicate = { ...notes[1], path: `${root}/project/worker.md` };
+ expect(resolveNoteLink([...notes, duplicate], notes[0].path, "Worker", true)).toBeUndefined();
+ });
+ it("keeps executable, credentialed and embedded URLs inert", () => {
+ expect(safeExternalLink("https://example.org/reference")).toBe("https://example.org/reference");
+ for (const target of ["javascript:alert(1)", "data:text/html,test", "file:///etc/passwd", "https://user:[email protected]/", "//example.org", "obsidian://open"]) expect(safeExternalLink(target)).toBeUndefined();
+ });
+});
diff --git a/frontend/slices/agent-vault/lib/note-links.ts b/frontend/slices/agent-vault/lib/note-links.ts
new file mode 100644
index 00000000..9ab4ba63
--- /dev/null
+++ b/frontend/slices/agent-vault/lib/note-links.ts
@@ -0,0 +1,31 @@
+import type { AgentVaultNote } from "@/lib/contracts/agent-vault";
+
+function normalize(value: string): string {
+ const parts: string[] = [];
+ for (const part of value.split("/")) {
+ if (part === "..") parts.pop();
+ else if (part && part !== ".") parts.push(part);
+ }
+ return parts.join("/").replace(/\.md$/i, "").toLowerCase();
+}
+
+/** Resolve only to a published note in the selected snapshot, never to a host path. */
+export function resolveNoteLink(notes: AgentVaultNote[], from: string, raw: string, wiki = false): AgentVaultNote | undefined {
+ let target: string;
+ try { target = decodeURIComponent(raw.split("#")[0].split("?")[0]).trim(); } catch { return; }
+ if (!target || /^(?:[a-z][a-z\d+.-]*:|\/|\\)/i.test(target)) return;
+ const direct = normalize(target);
+ const relative = normalize(`${from.slice(0, from.lastIndexOf("/"))}/${target}`);
+ const exact = notes.find(note => normalize(note.path) === relative || (wiki && normalize(note.path) === direct));
+ if (exact || !wiki) return exact;
+ const matches = notes.filter(note => normalize(note.title) === direct || normalize(note.path.split("/").pop()!) === direct);
+ return matches.length === 1 ? matches[0] : undefined;
+}
+
+export function safeExternalLink(raw: string): string | undefined {
+ try {
+ const url = new URL(raw);
+ if (["https:", "http:"].includes(url.protocol) && !url.username && !url.password) return url.href;
+ } catch { /* unresolved or non-web links remain text */ }
+ return undefined;
+}
diff --git a/frontend/slices/agent-vault/lib/use-vault.ts b/frontend/slices/agent-vault/lib/use-vault.ts
new file mode 100644
index 00000000..9b573578
--- /dev/null
+++ b/frontend/slices/agent-vault/lib/use-vault.ts
@@ -0,0 +1,72 @@
+"use client";
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { AgentVaultState, AgentVaultView } from "@/lib/contracts/agent-vault";
+
+const KEY = "mso:agent-vault:project";
+export async function vaultRequest(project: string, signal: AbortSignal, sync = false, note?: string): Promise<AgentVaultView> {
+ const params = new URLSearchParams();
+ if (project.trim()) params.set("project", project.trim());
+ if (note) params.set("note", note);
+ const response = await fetch(`/api/v1/agent-vault?${params}`, sync ? {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(project.trim() ? { project: project.trim() } : {}), signal,
+ } : { cache: "no-store", signal });
+ const result = await response.json();
+ if (!response.ok) throw new Error(result.error || `Request failed (${response.status})`);
+ return result as AgentVaultView;
+}
+
+export function useVault() {
+ const [project, setProject] = useState("");
+ const [state, setState] = useState<AgentVaultState | null>(null);
+ const [snapshotId, setSnapshotId] = useState("");
+ const [note, setNote] = useState<AgentVaultView["note"]>();
+ const [selectedPath, setSelectedPath] = useState("");
+ const [busy, setBusy] = useState(true), [noteBusy, setNoteBusy] = useState(false), [error, setError] = useState("");
+ const loading = useRef<AbortController | null>(null), reading = useRef<AbortController | null>(null);
+
+ const apply = useCallback((result: AgentVaultView) => {
+ setState(result.state); setSnapshotId(result.state.current || "");
+ setProject(result.state.project.path); localStorage.setItem(KEY, result.state.project.path);
+ }, []);
+
+ const load = useCallback(async (hint: string, sync = false) => {
+ loading.current?.abort(); reading.current?.abort();
+ const controller = new AbortController(); loading.current = controller;
+ setBusy(true); setError(""); setNote(undefined); setSelectedPath(""); setNoteBusy(false);
+ try {
+ const result = await vaultRequest(hint, controller.signal, sync);
+ if (controller.signal.aborted) return;
+ apply(result);
+ } catch (cause) {
+ if (!controller.signal.aborted) { setState(null); setError(cause instanceof Error ? cause.message : "Could not load vault"); }
+ } finally { if (!controller.signal.aborted) setBusy(false); }
+ }, [apply]);
+
+ useEffect(() => {
+ const controller = new AbortController(); loading.current = controller;
+ void vaultRequest(localStorage.getItem(KEY) || "", controller.signal).then(result => {
+ if (!controller.signal.aborted) apply(result);
+ }).catch(cause => {
+ if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Could not load vault");
+ }).finally(() => { if (!controller.signal.aborted) setBusy(false); });
+ return () => { controller.abort(); loading.current?.abort(); reading.current?.abort(); };
+ }, [apply]);
+
+ const select = useCallback(async (path: string) => {
+ if (!state || busy) return;
+ reading.current?.abort();
+ const controller = new AbortController(); reading.current = controller;
+ setSelectedPath(path); setNoteBusy(true); setError(""); setNote(undefined);
+ try {
+ const result = await vaultRequest(state.project.path, controller.signal, false, path);
+ if (!controller.signal.aborted) setNote(result.note);
+ } catch (cause) {
+ if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Could not read note");
+ } finally { if (!controller.signal.aborted) setNoteBusy(false); }
+ }, [state, busy]);
+
+ function chooseSnapshot(id: string) {
+ reading.current?.abort(); setSnapshotId(id); setNote(undefined); setSelectedPath(""); setNoteBusy(false); setError("");
+ }
+ return { project, setProject, state, snapshotId, chooseSnapshot, note, selectedPath, busy, noteBusy, error, load, select };
+}
diff --git a/frontend/slices/code-editor/lib/use-editor.ts b/frontend/slices/code-editor/lib/use-editor.ts
index 93d5cb7d..a63a9170 100644
--- a/frontend/slices/code-editor/lib/use-editor.ts
+++ b/frontend/slices/code-editor/lib/use-editor.ts
@@ -48,7 +48,7 @@ export function useEditor() {
// otherwise a clean/reopened buffer must follow the file, or it shows
// stale text and a later Save overwrites the newer host file.
setBuffers((b) => {
- const hadEdits = path in b && b[path] !== disk[path];
+ const hadEdits = path in b && b[path] !== (disk[path] ?? "");
return hadEdits ? b : { ...b, [path]: content };
});
setDisk((d) => ({ ...d, [path]: content }));
@@ -76,7 +76,9 @@ export function useEditor() {
// baseline at read time) or absent; otherwise keep the user's edits
// and just refresh the disk baseline.
setBuffers((b) => {
- const hasEdits = path in b && b[path] !== disk[path];
+ // A first-open empty buffer has no disk entry yet. It is clean,
+ // so adopt the host file; preserve actual keystrokes made while reading.
+ const hasEdits = path in b && b[path] !== (disk[path] ?? "");
return hasEdits ? b : { ...b, [path]: content };
});
setDisk((d) => ({ ...d, [path]: content }));
@@ -144,7 +146,7 @@ export function useEditor() {
);
const value = active != null ? (buffers[active] ?? "") : "";
- const dirty = active != null && buffers[active] !== disk[active];
+ const dirty = active != null && buffers[active] !== (disk[active] ?? "");
return {
tabs,
diff --git a/frontend/slices/memory-graph/app.tsx b/frontend/slices/memory-graph/app.tsx
index 6e879a2e..8c7213e6 100644
--- a/frontend/slices/memory-graph/app.tsx
+++ b/frontend/slices/memory-graph/app.tsx
@@ -4,10 +4,13 @@ import type { AppProps } from "@/features/appshell";
import { AppFrame } from "@/features/appshell";
import { MemoryGraphScreen } from "./components/memory-graph-screen";
-export default function MemoryGraphApp(_props: AppProps) {
+export default function MemoryGraphApp({ payload }: AppProps) {
+ const context = payload && typeof payload === "object" ? payload as { root?: unknown; project?: unknown } : {};
+ const root = typeof context.root === "string" ? context.root : undefined;
+ const project = typeof context.project === "string" ? context.project : undefined;
return (
<AppFrame safeArea={false} className="h-full bg-background" bodyClassName="overflow-hidden">
- <MemoryGraphScreen />
+ <MemoryGraphScreen key={`${root ?? ""}\n${project ?? ""}`} initialRoot={root} initialProject={project} />
</AppFrame>
);
}
diff --git a/frontend/slices/memory-graph/components/memory-graph-screen.tsx b/frontend/slices/memory-graph/components/memory-graph-screen.tsx
index 1802fc22..c7b21990 100644
--- a/frontend/slices/memory-graph/components/memory-graph-screen.tsx
+++ b/frontend/slices/memory-graph/components/memory-graph-screen.tsx
@@ -27,10 +27,10 @@ async function loadGraph(root: string, project: string): Promise<MemoryGraphDocu
return body as MemoryGraphDocument;
}
-export function MemoryGraphScreen() {
- const [root, setRoot] = useState(() => stored(ROOT_KEY));
- const [project, setProject] = useState(() => stored(PROJECT_KEY));
- const [applied, setApplied] = useState(() => ({ root: stored(ROOT_KEY), project: stored(PROJECT_KEY), nonce: 0 }));
+export function MemoryGraphScreen({ initialRoot, initialProject }: { initialRoot?: string; initialProject?: string } = {}) {
+ const [root, setRoot] = useState(() => initialRoot ?? stored(ROOT_KEY));
+ const [project, setProject] = useState(() => initialProject ?? stored(PROJECT_KEY));
+ const [applied, setApplied] = useState(() => ({ root: initialRoot ?? stored(ROOT_KEY), project: initialProject ?? stored(PROJECT_KEY), nonce: 0 }));
const [layout, setLayout] = useState<GraphLayoutName>("web");
const [local, setLocal] = useState(false);
const [depth, setDepth] = useState(2);
diff --git a/scripts/e2e/agent-vault.mjs b/scripts/e2e/agent-vault.mjs
index 6852c1f0..78b206cc 100644
--- a/scripts/e2e/agent-vault.mjs
+++ b/scripts/e2e/agent-vault.mjs
@@ -1,8 +1,11 @@
import { expect } from "@playwright/test";
-import { readFile, writeFile } from "node:fs/promises";
+import { readFile, readdir, writeFile } from "node:fs/promises";
import path from "node:path";
export async function agentVaultJourney(page, fixture) {
+ let connectionReads = 0;
+ const countReads = request => { if (request.url().includes("/api/v1/memory-graph")) connectionReads++; };
+ page.on("request", countReads);
await page.goto(fixture.base + "/agent-vault");
await expect(page.getByLabel("Repository", { exact: true })).toHaveValue(fixture.vaultProject);
await page.getByRole("button", { name: "Refresh snapshot", exact: true }).click();
@@ -14,6 +17,16 @@ export async function agentVaultJourney(page, fixture) {
expect(state.root.startsWith(path.join(fixture.dir, "vault-data"))).toBe(true);
expect(state.root.startsWith(fixture.vaultProject + path.sep)).toBe(false);
const previous = state.current;
+ expect(connectionReads).toBe(0);
+ await page.getByRole("button", { name: "Backlinks", exact: true }).click();
+ const backlinks = page.getByRole("region", { name: "Note backlinks" });
+ await expect(backlinks.getByRole("button", { name: "Agent progress", exact: true })).toBeVisible();
+ expect(connectionReads).toBe(1);
+ await backlinks.getByRole("button", { name: "Agent progress", exact: true }).click();
+ const reader = page.getByRole("region", { name: "Note reader" });
+ await reader.getByRole("button", { name: "Fixture worker", exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Fixture worker", exact: true })).toBeVisible();
+ expect(connectionReads).toBe(1);
await writeFile(path.join(fixture.vaultProject, "wiki/log.md"), "# Fixture progress\n\nSecond verified repository update.\n", { mode: 0o600 });
await page.getByRole("button", { name: "Refresh snapshot", exact: true }).click();
await expect(page.getByLabel("Snapshot", { exact: true }).locator("option")).toHaveCount(2);
@@ -27,6 +40,28 @@ export async function agentVaultJourney(page, fixture) {
await expect(page.getByRole("button", { name: /^Fixture worker/ })).toBeVisible();
await expect(page.getByRole("button", { name: /^Fixture progress/ })).toHaveCount(0);
await page.getByLabel("Search vault notes", { exact: true }).fill("");
+ await page.getByRole("button", { name: "History", exact: true }).click();
+ await expect(page.getByText("Recorded changes from repository captures.", { exact: false })).toBeVisible();
+ await page.getByRole("button", { name: "Notes", exact: true }).click();
+ // Code uses the selected host adapter; exercise real read/write, then restore fixture mode.
+ const prefsFile = path.join(fixture.dir, "prefs.json");
+ const savedPrefs = await readFile(prefsFile, "utf8").catch(() => "{}");
+ const prefs = JSON.parse(savedPrefs);
+ await writeFile(prefsFile, JSON.stringify({ ...prefs, tweaks: { ...prefs.tweaks, server: { mode: "live", activeTargetId: "vps", url: "" } } }), { mode: 0o600 });
+ await page.reload();
+ await expect(page.getByLabel("Server connection mode")).toHaveAttribute("data-connection-mode", "live");
+ await page.getByRole("button", { name: "Personal notes", exact: true }).click();
+ await page.getByLabel("New note title", { exact: true }).fill("Fixture personal note");
+ await page.getByRole("button", { name: "New note", exact: true }).click();
+ const personalDirectory = path.join(state.root, "Notes");
+ const personalFiles = async () => (await readdir(personalDirectory).catch(() => [])).filter(name => name.endsWith(".md"));
+ await expect.poll(async () => (await personalFiles()).length).toBe(1);
+ const personalFile = path.join(personalDirectory, (await personalFiles())[0]);
+ await expect(page.locator("textarea").filter({ visible: true }).first()).toHaveValue("# Fixture personal note\n\n");
+ await page.locator("textarea").filter({ visible: true }).first().fill("# Fixture personal note\n\nSaved in the native editor.\n");
+ await page.getByRole("button", { name: "Save", exact: true }).click();
+ await expect.poll(() => readFile(personalFile, "utf8")).toContain("Saved in the native editor.");
+ await writeFile(prefsFile, savedPrefs, { mode: 0o600 });
for (const viewport of [{ width: 390, height: 844 }, { width: 844, height: 390 }]) {
await page.setViewportSize(viewport);
await page.goto(fixture.base + "/agent-vault");
@@ -34,6 +69,12 @@ export async function agentVaultJourney(page, fixture) {
await page.getByRole("button", { name: /^Fixture worker/ }).click();
await expect(page.getByRole("heading", { name: "Fixture worker", exact: true })).toBeVisible();
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+ if (viewport.width < 640) {
+ await expect(page.getByRole("complementary", { name: "Vault navigation" })).toBeHidden();
+ await page.getByRole("button", { name: "Back to notes", exact: true }).click();
+ await expect(page.getByLabel("Search vault notes", { exact: true })).toBeVisible();
+ await expect(page.getByRole("region", { name: "Note reader" })).toBeHidden();
+ }
}
await fixture.setRole("viewer");
const denied = await page.evaluate(async () => {
@@ -42,5 +83,6 @@ export async function agentVaultJourney(page, fixture) {
});
expect(denied).toEqual([403, 403]);
await fixture.setRole("owner");
+ page.off("request", countReads);
await page.setViewportSize({ width: 1280, height: 900 });
}