Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(desktop): rebuild the brain graph; people by standing
Salman Qureshi65227d609b7e
diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.jsonindex 6de14fbd..baa4022e 100644--- a/apps/desktop/package-lock.json+++ b/apps/desktop/package-lock.json@@ -27,6 +27,7 @@"@tauri-apps/plugin-updater": "^2.14.0","@tauri-apps/plugin-window-state": "^2.5.0","clsx": "^2.1.1",+ "d3-force": "^3.0.0","force-graph": "^1.52.0","lucide-react": "^0.511.0","react": "^18.3.1",@@ -38,6 +39,7 @@},"devDependencies": {"@tauri-apps/cli": "^2.12.4",+ "@types/d3-force": "^3.0.10","@types/react": "^18.3.28","@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.5.2",@@ -2401,6 +2403,13 @@"assertion-error": "^2.0.1"}},+ "node_modules/@types/d3-force": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/debug": {"version": "4.1.13","resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",@@ -3100,6 +3109,20 @@"node": ">=12"}},+ "node_modules/d3-force": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-quadtree": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-force-3d": {"version": "3.0.6","resolved": "https://registry.npmjs.org/d3-force-3d/-/d3-force-3d-3.0.6.tgz",diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 9540220a..51e86e9e 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -34,6 +34,7 @@"@tauri-apps/plugin-updater": "^2.14.0","@tauri-apps/plugin-window-state": "^2.5.0","clsx": "^2.1.1",+ "d3-force": "^3.0.0","force-graph": "^1.52.0","lucide-react": "^0.511.0","react": "^18.3.1",@@ -45,6 +46,7 @@},"devDependencies": {"@tauri-apps/cli": "^2.12.4",+ "@types/d3-force": "^3.0.10","@types/react": "^18.3.28","@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.5.2",diff --git a/apps/desktop/src/api/brain.ts b/apps/desktop/src/api/brain.tsindex 388b85ca..9b848e22 100644--- a/apps/desktop/src/api/brain.ts+++ b/apps/desktop/src/api/brain.ts@@ -30,6 +30,15 @@ export interface PersonMeta {links?: string[];}+export type PersonTier = "known" | "shadow" | "faint";++/** How sure Mercury is that this is someone in your life (runtime person-standing.ts). */+export interface PersonStanding {+ score: number;+ tier: PersonTier;+ reasons: string[];+}+export interface BrainPerson {id: string;name: string;@@ -42,13 +51,16 @@ export interface BrainPerson {verifiedBy: "owner" | "model" | "model-rejected" | null;meta: PersonMeta;ownerEdited: boolean;+ standing?: PersonStanding | null;+ /** "one": a relation only one person can hold (wife, mother); "many": friends, children. */+ cardinality?: "one" | "many" | null;firstSeenAt: number;lastSeenAt: number;connections?: Array<{ id: string; name?: string; display_name?: string; relation_type?: string; strength?: number }>;}export interface BrainGraphData {- persons: Array<{ id: string; name: string; kind: string; relationship: string | null; memoryCount: number }>;+ persons: Array<{ id: string; name: string; kind: string; relationship: string | null; memoryCount: number; tier?: PersonTier; score?: number }>;memories: Array<{ id: string; summary: string; type: string; importance: number; updatedAt: number }>;memoryPersons: Array<{ memoryId: string; personId: string; role: string }>;relationships: Array<{ source: string; target: string; type: string; strength: number }>;@@ -84,16 +96,18 @@ export const brain = {deleteMemory: (id: string) => http.delete<{ success: boolean }>(`/api/brain/memory/${encodeURIComponent(id)}`),addMemory: (body: { type: string; summary: string; detail?: string }) => http.post<BrainMemory>("/api/brain/memory", body),- persons: (opts: { q?: string; kind?: string; limit?: number } = {}) => {+ persons: (opts: { q?: string; kind?: string; limit?: number; tier?: PersonTier } = {}) => {const qs = new URLSearchParams();if (opts.q) qs.set("q", opts.q);if (opts.kind) qs.set("kind", opts.kind);+ if (opts.tier) qs.set("tier", opts.tier);qs.set("limit", String(opts.limit ?? 200));return http.get<{ persons: BrainPerson[] }>(`/api/brain/persons?${qs}`);},person: (id: string) => http.get<{ person: BrainPerson }>(`/api/brain/persons/${encodeURIComponent(id)}`),personMemories: (id: string) => http.get<{ memories: BrainMemory[] }>(`/api/brain/persons/${encodeURIComponent(id)}/memories?limit=60`),- updatePerson: (id: string, patch: { name?: string; relationship?: string | null; summary?: string | null; kind?: string; meta?: PersonMeta }) =>+ /** A one-to-one relation someone else holds fails with 409 ("Heer is already your wife."); `force` moves it. */+ updatePerson: (id: string, patch: { name?: string; relationship?: string | null; summary?: string | null; kind?: string; meta?: PersonMeta; force?: boolean }) =>http.patch<{ person?: BrainPerson; removed?: boolean }>(`/api/brain/persons/${encodeURIComponent(id)}`, patch),mergePerson: (id: string, into: string) => http.post<{ person: BrainPerson | null }>(`/api/brain/persons/${encodeURIComponent(id)}/merge`, { into }),notAPerson: (id: string) => http.patch<{ removed?: boolean }>(`/api/brain/persons/${encodeURIComponent(id)}`, { kind: "not_person" }),@@ -102,5 +116,6 @@ export const brain = {runCheck: () => http.post<{ checked: number; status: CheckStatus }>("/api/brain/persons/checks/run"),queueExisting: () => http.post<{ queued: number; status: CheckStatus | null }>("/api/brain/persons/checks/queue-existing"),- graph: (memories = 300) => http.get<BrainGraphData>(`/api/brain/graph/v2?memories=${memories}`),+ graph: (memories = 300, shadows = false) => http.get<BrainGraphData>(`/api/brain/graph/v2?memories=${memories}${shadows ? "&shadows=1" : ""}`),+ relations: () => http.get<{ relations: Array<{ label: string; cardinality: "one" | "many" }>; knownCap: number }>("/api/brain/relations"),};diff --git a/apps/desktop/src/views/brain/BrainGraph.test.ts b/apps/desktop/src/views/brain/BrainGraph.test.tsnew file mode 100644index 00000000..b0db7f77--- /dev/null+++ b/apps/desktop/src/views/brain/BrainGraph.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import type { BrainGraphData } from "~/api/brain";+import { toGraph } from "./BrainGraph";++const data: BrainGraphData = {+ available: true,+ persons: [+ { id: "heer", name: "Heer", kind: "person", relationship: "wife", memoryCount: 5, tier: "known", score: 99 },+ { id: "zaid", name: "Zaid", kind: "person", relationship: "friend", memoryCount: 4, tier: "known", score: 99 },+ { id: "castor", name: "Castor", kind: "unverified", relationship: null, memoryCount: 4, tier: "shadow", score: 56 },+ ],+ memories: [+ { id: "m1", summary: "Heer loves tea", type: "preference", importance: 0.5, updatedAt: 1 },+ { id: "m2", summary: "Ship Mercury Desktop", type: "project", importance: 0.8, updatedAt: 1 },+ { id: "m3", summary: "Castor promo video", type: "project", importance: 0.4, updatedAt: 1 },+ ],+ memoryPersons: [{ memoryId: "m1", personId: "heer", role: "mention" }],+ relationships: [{ source: "zaid", target: "heer", type: "knows", strength: 0.6 }],+};++const ids = (g: ReturnType<typeof toGraph>) => g.nodes.map((n) => n.id);+const link = (g: ReturnType<typeof toGraph>, kind: string) => g.links.filter((l) => l.kind === kind).map((l) => `${String(l.source)}>${String(l.target)}${l.label ? `:${l.label}` : ""}`);++describe("brain graph shape", () => {+ it("clusters memories on people, and the rest by topic instead of one star on you", () => {+ const g = toGraph(data, "all");+ expect(link(g, "about")).toEqual(["m1>heer"]);+ expect(link(g, "topic").sort()).toEqual(["m2>hub:project", "m3>hub:project"]);+ expect(link(g, "hub")).toEqual(["you>hub:project"]);+ expect(g.links.some((l) => l.kind === "you" && String(l.target).startsWith("m"))).toBe(false);+ expect(g.nodes.find((n) => n.id === "hub:project")?.label).toBe("Projects · 2");+ });++ it("names relationships on the lines", () => {+ const g = toGraph(data, "all");+ expect(link(g, "you")).toContain("you>heer:wife");+ expect(link(g, "relation")).toEqual(["zaid>heer:knows"]);+ });++ it("marks shadows and keeps label priority: you, topics, people, memories", () => {+ const g = toGraph(data, "all");+ expect(g.nodes.find((n) => n.id === "castor")?.shadow).toBe(true);+ expect(ids(g)).toEqual(["you", "hub:project", "heer", "zaid", "castor", "m1", "m2", "m3"]);+ });++ it("filters: people only, or memories only", () => {+ expect(ids(toGraph(data, "people"))).toEqual(["you", "heer", "zaid", "castor"]);+ const mem = toGraph(data, "memories");+ expect(mem.nodes.some((n) => n.kind === "person")).toBe(false);+ expect(link(mem, "topic").length).toBe(3);+ });+});diff --git a/apps/desktop/src/views/brain/BrainGraph.tsx b/apps/desktop/src/views/brain/BrainGraph.tsxindex 53239a33..ffdddb01 100644--- a/apps/desktop/src/views/brain/BrainGraph.tsx+++ b/apps/desktop/src/views/brain/BrainGraph.tsx@@ -1,120 +1,173 @@-import { Maximize2, RefreshCw } from "lucide-react";+import { Maximize2, Minus, Plus, RefreshCw, RotateCcw, Search } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type ForceGraph from "force-graph";import type { LinkObject, NodeObject } from "force-graph";+import { forceCollide, forceX, forceY } from "d3-force";import { brain, type BrainGraphData } from "~/api/brain";import { Button } from "~/components/ui/Button";import { Segmented, Spinner } from "~/components/ui/bits";+import { Switch } from "~/components/ui/Switch";+import { Tooltip } from "~/components/ui/Tooltip";import { useTheme } from "~/app/theme";import { cx } from "~/lib/cx";/**- * The brain as a living graph (Obsidian-style): you at the centre, the people- * in your life, and what Mercury knows, joined only by real links (who- * appears in which memory, who relates to whom). d3-force physics: drag a- * node and its neighbours follow with springy, fluid motion; let go and it- * settles. Canvas rendering; the library and the data load only when the- * graph is opened; animation pauses while it is hidden; positions are kept- * for the session so reopening doesn't re-settle from scratch.+ * The brain as a living graph, Obsidian-style.+ *+ * Library: force-graph (d3-force on canvas). Chosen after comparing sigma,+ * cosmos, Cytoscape, vis-network, G6 and a custom Pixi renderer: it is the+ * only one with d3's drag-reheat built in (the simulation warms while you+ * drag, so neighbours follow like liquid) and it is light and WebKit-safe.+ *+ * Layout: you at the centre; people around you; memories cluster on the+ * people they are about, and the rest gather by topic (Projects, Goals…)+ * instead of one big star. Every open starts from a random scatter that+ * flows into place. A node you drag stays where you left it (pinned) until+ * "Reset layout". Labels never overlap; relationships are named on the+ * lines. Nothing loads until the graph is opened; it pauses when hidden.*/+type Kind = "you" | "hub" | "person" | "pet" | "memory";+export type SelectableKind = "you" | "person" | "pet" | "memory";+export interface GraphNode extends NodeObject {id: string;- kind: "you" | "person" | "pet" | "memory";+ kind: Kind;label: string;type?: string;weight: number;+ shadow?: boolean;relationship?: string | null;}interface GraphLink extends LinkObject<GraphNode> {- kind: "about" | "relation" | "you";+ kind: "you" | "relation" | "about" | "topic" | "hub";+ label?: string;}-const POSITIONS_KEY = "mercury.brain.graph.positions.v1";+const PINS_KEY = "mercury.brain.graph.pins.v2";const TYPE_COLORS: Record<string, string> = {- fact: "#7E8FA3", preference: "#C9A227", trait: "#9B7BD8", situation: "#5AA9C8", relationship: "#E07BA8",+ fact: "#7E8FA3", preference: "#D4A72C", trait: "#9B7BD8", situation: "#4FA6C8", relationship: "#E07BA8",goal: "#3FB37F", project: "#8B7CF6", episode: "#6C8EF0", identity: "#2BB5C9", habit: "#E8894A", decision: "#4C8FD6", constraint: "#E06B6B", reflection: "#3BA99C",};+const HUB_LABEL: Record<string, string> = {+ fact: "Facts", preference: "Preferences", trait: "Traits", situation: "Situations", relationship: "Relationships", goal: "Goals", project: "Projects",+ episode: "Moments", identity: "Identity", habit: "Habits", decision: "Decisions", constraint: "Constraints", reflection: "Reflections",+};-export function BrainGraph({ visible, onSelect, selectedId }: { visible: boolean; onSelect: (node: { id: string; kind: GraphNode["kind"] } | null) => void; selectedId: string | null }) {+type Show = "all" | "people" | "memories";++export function BrainGraph({ visible, onSelect, selectedId }: { visible: boolean; onSelect: (node: { id: string; kind: SelectableKind } | null) => void; selectedId: string | null }) {const host = useRef<HTMLDivElement>(null);const graph = useRef<ForceGraph<GraphNode, GraphLink> | null>(null);const [data, setData] = useState<BrainGraphData | null>(null);const [limit, setLimit] = useState(300);- const [show, setShow] = useState<"all" | "people" | "memories">("all");+ const [show, setShow] = useState<Show>("all");+ const [shadows, setShadows] = useState(false);const [error, setError] = useState<string | null>(null);const [loading, setLoading] = useState(false);+ const [zoomPct, setZoomPct] = useState(100);+ const [find, setFind] = useState("");+ const [matchCount, setMatchCount] = useState(0);const hover = useRef<GraphNode | null>(null);- const neighbours = useRef<Set<string>>(new Set());+ const adjacency = useRef<Map<string, Set<string>>>(new Map());+ const labelsDrawn = useRef<Array<[number, number, number, number]>>([]);+ const matches = useRef<Set<string>>(new Set());const resolved = useTheme((s) => s.resolved);+ const dark = useRef(resolved === "dark");+ dark.current = resolved === "dark";const selectedRef = useRef<string | null>(selectedId);selectedRef.current = selectedId;+ const onSelectRef = useRef(onSelect);+ onSelectRef.current = onSelect;- const load = useCallback(async (n: number) => {+ const load = useCallback(async (n: number, withShadows: boolean) => {setLoading(true);setError(null);- try { setData(await brain.graph(n)); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }+ try { setData(await brain.graph(n, withShadows)); } catch (e) { setError(e instanceof Error ? e.message : String(e)); }setLoading(false);}, []);// Lazy: nothing is fetched until the graph is first shown.- useEffect(() => { if (visible && !data && !loading) void load(limit); }, [visible, data, loading, limit, load]);+ const requested = useRef(false);+ useEffect(() => {+ if (visible && !requested.current) { requested.current = true; void load(limit, shadows); }+ }, [visible, limit, shadows, load]);const graphData = useMemo(() => (data ? toGraph(data, show) : null), [data, show]);+ const lastData = useRef<typeof graphData>(null);- // Create the engine once, lazily (dynamic import keeps it out of the main bundle).+ function setGraph(g: ForceGraph<GraphNode, GraphLink>, next: NonNullable<typeof graphData>) {+ lastData.current = next;+ adjacency.current = buildAdjacency(next.links);+ g.graphData(place(next, g.graphData().nodes));+ }++ // Build the engine once (dynamic import keeps it out of the main bundle).useEffect(() => {if (!visible || !graphData || graph.current || !host.current) return;let disposed = false;void import("force-graph").then(({ default: ForceGraphCtor }) => {- if (disposed || !host.current) return;+ if (disposed || !host.current || graph.current) return;const el = host.current;const g = new ForceGraphCtor<GraphNode, GraphLink>(el).width(el.clientWidth).height(el.clientHeight).backgroundColor("rgba(0,0,0,0)").nodeId("id")- .nodeRelSize(4)- .d3VelocityDecay(0.28) // low friction: fluid, springy motion- .d3AlphaDecay(0.018)- .cooldownTime(12_000)- .warmupTicks(30)- .linkColor((l) => linkColor(l, hover.current))- .linkWidth((l) => (hover.current && (endId(l.source) === hover.current.id || endId(l.target) === hover.current.id) ? 1.6 : 0.6))- .nodeCanvasObject((node, ctx, scale) => drawNode(node, ctx, scale, hover.current, neighbours.current, selectedRef.current))- .nodePointerAreaPaint((node, color, ctx) => { ctx.fillStyle = color; ctx.beginPath(); ctx.arc(node.x ?? 0, node.y ?? 0, radius(node) + 3, 0, 2 * Math.PI); ctx.fill(); })+ .minZoom(0.15)+ .maxZoom(10)+ // Fluid: low friction, slow cooling, and a random start that flows into place.+ .d3VelocityDecay(0.3)+ .d3AlphaDecay(0.0228)+ .warmupTicks(0)+ .cooldownTicks(600)+ .linkColor((l) => linkColor(l))+ .linkWidth((l) => (isLit(l) ? 1.8 : l.kind === "relation" || l.kind === "you" ? 1.1 : 0.6))+ .linkCanvasObjectMode(() => "after")+ .linkCanvasObject((l, ctx, scale) => drawLinkLabel(l, ctx, scale))+ .nodeCanvasObject((node, ctx, scale) => drawNode(node, ctx, scale))+ .nodePointerAreaPaint((node, color, ctx) => { ctx.fillStyle = color; ctx.beginPath(); ctx.arc(node.x ?? 0, node.y ?? 0, radius(node) + 4, 0, 2 * Math.PI); ctx.fill(); })+ .onRenderFramePre(() => { labelsDrawn.current = []; })+ .onZoom(({ k }) => setZoomPct(Math.round(k * 100))).onNodeHover((node) => {hover.current = node ?? null;- neighbours.current = node ? neighbourIds(g.graphData(), node.id) : new Set();el.style.cursor = node ? "pointer" : "grab";}).onNodeClick((node) => {- onSelect({ id: node.id, kind: node.kind });+ if (node.kind === "hub") { g.centerAt(node.x, node.y, 500); g.zoom(Math.max(g.zoom(), 1.6), 500); return; }+ onSelectRef.current({ id: node.id, kind: node.kind });g.centerAt(node.x, node.y, 500);})- .onBackgroundClick(() => onSelect(null))+ .onBackgroundClick(() => onSelectRef.current(null))+ // Pinned where you leave it; d3 already warms the simulation while you drag..onNodeDragEnd((node) => {- // Release it back into the flow (fluid) rather than pinning it.- node.fx = undefined;- node.fy = undefined;- savePositions(g.graphData().nodes);- })- .onEngineStop(() => savePositions(g.graphData().nodes));- const charge = g.d3Force("charge");- charge?.strength?.((n: GraphNode) => (n.kind === "memory" ? -18 : n.kind === "you" ? -400 : -120));- const link = g.d3Force("link");- link?.distance?.((l: GraphLink) => (l.kind === "you" ? 90 : l.kind === "relation" ? 60 : 34));+ node.fx = node.x;+ node.fy = node.y;+ savePin(node);+ });++ g.d3Force("charge")?.strength?.((n: GraphNode) => CHARGE[n.kind]).distanceMax?.(520);+ g.d3Force("link")+ ?.distance?.((l: GraphLink) => LINK_DISTANCE[l.kind])+ .strength?.((l: GraphLink) => LINK_STRENGTH[l.kind]);+ g.d3Force("collide", forceCollide<GraphNode>((n) => radius(n) + (n.kind === "memory" ? 2 : 6)).strength(0.8).iterations(1));+ g.d3Force("x", forceX<GraphNode>(0).strength(0.035));+ g.d3Force("y", forceY<GraphNode>(0).strength(0.035));+graph.current = g;- g.graphData(withPositions(graphData));- setTimeout(() => g.zoomToFit(600, 60), 900);+ setGraph(g, graphData);+ setTimeout(() => { if (graph.current === g) g.zoomToFit(700, 80); }, 1600);}).catch((e) => setError(e instanceof Error ? e.message : String(e)));return () => { disposed = true; };- }, [visible, graphData, onSelect]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [visible, graphData]);- // New data or filter: swap the data in, keeping positions.+ // New data or filter: swap it in, keeping where everything already is.useEffect(() => {- if (graph.current && graphData) graph.current.graphData(withPositions(graphData, graph.current.graphData().nodes));+ const g = graph.current;+ if (!g || !graphData || lastData.current === graphData) return;+ setGraph(g, graphData);}, [graphData]);// Pause when hidden: no frames, no CPU.@@ -128,30 +181,101 @@ export function BrainGraph({ visible, onSelect, selectedId }: { visible: booleanuseEffect(() => {const el = host.current;if (!el) return;- const ro = new ResizeObserver(() => { graph.current?.width(el.clientWidth).height(el.clientHeight); });+ const ro = new ResizeObserver(() => { if (el.clientWidth && el.clientHeight) graph.current?.width(el.clientWidth).height(el.clientHeight); });ro.observe(el);return () => ro.disconnect();}, []);useEffect(() => () => { graph.current?._destructor(); graph.current = null; }, []);- useEffect(() => { graph.current?.nodeCanvasObject(graph.current.nodeCanvasObject()); }, [resolved, selectedId]);++ // Theme or selection changed: one redraw (the canvas only repaints on change).+ useEffect(() => { const g = graph.current; if (g) g.nodeCanvasObject(g.nodeCanvasObject()); }, [resolved, selectedId]);++ // Find: highlight matches; Enter flies to the first one.+ useEffect(() => {+ const q = find.trim().toLowerCase();+ const g = graph.current;+ matches.current = new Set(q.length < 2 || !g ? [] : g.graphData().nodes.filter((n) => n.label.toLowerCase().includes(q)).map((n) => n.id));+ setMatchCount(matches.current.size);+ if (g) g.nodeCanvasObject(g.nodeCanvasObject());+ }, [find]);+ function flyToMatch() {+ const g = graph.current;+ if (!g) return;+ const n = g.graphData().nodes.find((x) => matches.current.has(x.id));+ if (!n) return;+ g.centerAt(n.x, n.y, 600);+ g.zoom(Math.max(2.2, g.zoom()), 600);+ if (n.kind !== "hub") onSelectRef.current({ id: n.id, kind: n.kind });+ }++ function zoomBy(f: number) {+ const g = graph.current;+ if (g) g.zoom(Math.min(10, Math.max(0.15, g.zoom() * f)), 250);+ }++ function resetLayout() {+ const g = graph.current;+ if (!g) return;+ clearPins();+ scatter(g.graphData().nodes, true);+ g.d3ReheatSimulation();+ setTimeout(() => g.zoomToFit(700, 80), 1600);+ }++ // Keyboard: + / - / 0 zoom while the graph is on screen.+ useEffect(() => {+ if (!visible) return;+ const onKey = (e: KeyboardEvent) => {+ const t = e.target as HTMLElement | null;+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) return;+ if (e.metaKey || e.ctrlKey || e.altKey) return;+ if (e.key === "+" || e.key === "=") zoomBy(1.4);+ else if (e.key === "-") zoomBy(1 / 1.4);+ else if (e.key === "0") graph.current?.zoomToFit(500, 80);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [visible]);const counts = data ? { people: data.persons.length, memories: data.memories.length, links: data.memoryPersons.length + data.relationships.length } : null;+ const ctl = "flex h-8 w-8 items-center justify-center rounded-lg text-ink2 hover:bg-ink/[0.07] hover:text-ink";return (<div className="relative h-full w-full overflow-hidden"><div ref={host} className="absolute inset-0" style={{ cursor: "grab" }} />- <div className="pointer-events-none absolute left-4 top-3 flex items-center gap-2">++ <div className="pointer-events-none absolute left-4 right-4 top-3 flex flex-wrap items-center gap-2"><div className="pointer-events-auto"><Segmented value={show} onChange={setShow} options={[{ value: "all", label: "Everything" }, { value: "people", label: "People" }, { value: "memories", label: "Memories" }]} /></div>+ <div className="pointer-events-auto flex h-8 items-center rounded-md bg-surface/85 px-2.5 text-xs text-ink2 backdrop-blur">+ <Switch checked={shadows} onCheckedChange={(v) => { setShadows(v); void load(limit, v); }} label="Shadows" />+ </div>+ <div className="pointer-events-auto flex h-8 items-center gap-1.5 rounded-md border border-line bg-surface/85 px-2 backdrop-blur">+ <Search size={13} className="text-ink4" />+ <input value={find} onChange={(e) => setFind(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") flyToMatch(); if (e.key === "Escape") setFind(""); }}+ placeholder="Find in graph" className="w-[150px] bg-transparent text-xs text-ink placeholder:text-ink4" aria-label="Find in graph" />+ {find.trim().length > 1 && <span className="text-2xs text-ink4">{matchCount}</span>}+ </div>{counts && <span className="rounded-md bg-surface/80 px-2 py-1 text-xs text-ink3 backdrop-blur">{counts.people} people · {counts.memories} memories · {counts.links} links</span>}- </div>- <div className="absolute right-4 top-3 flex items-center gap-1.5">+ <span className="flex-1" />{data && data.memories.length >= limit && limit < 2000 && (- <Button size="sm" variant="outline" onClick={() => { const next = Math.min(2000, limit * 2); setLimit(next); void load(next); }}>Load more</Button>+ <Button className="pointer-events-auto" size="sm" variant="outline" onClick={() => { const next = Math.min(2000, limit * 2); setLimit(next); void load(next, shadows); }}>Load more</Button>)}- <Button size="sm" variant="ghost" icon onClick={() => graph.current?.zoomToFit(500, 60)} aria-label="Fit to view"><Maximize2 size={14} /></Button>- <Button size="sm" variant="ghost" icon onClick={() => void load(limit)} loading={loading} aria-label="Reload"><RefreshCw size={14} /></Button>+ <Tooltip label="Reload" side="bottom">+ <Button className="pointer-events-auto" size="sm" variant="ghost" icon onClick={() => void load(limit, shadows)} loading={loading} aria-label="Reload"><RefreshCw size={14} /></Button>+ </Tooltip>+ </div>++ {/* Zoom controls, bottom right like a map. */}+ <div className="absolute bottom-3 right-4 flex flex-col items-center gap-1 rounded-xl border border-line bg-surface/90 p-1 shadow-sm backdrop-blur">+ <Tooltip label="Zoom in" shortcut="+" side="left"><button onClick={() => zoomBy(1.4)} className={ctl} aria-label="Zoom in"><Plus size={15} /></button></Tooltip>+ <span className="font-mono text-2xs text-ink4">{zoomPct}%</span>+ <Tooltip label="Zoom out" shortcut="−" side="left"><button onClick={() => zoomBy(1 / 1.4)} className={ctl} aria-label="Zoom out"><Minus size={15} /></button></Tooltip>+ <div className="my-0.5 h-px w-6 bg-line" />+ <Tooltip label="Fit to screen" shortcut="0" side="left"><button onClick={() => graph.current?.zoomToFit(500, 80)} className={ctl} aria-label="Fit to screen"><Maximize2 size={14} /></button></Tooltip>+ <Tooltip label="Reset layout (unpin everything)" side="left"><button onClick={resetLayout} className={ctl} aria-label="Reset layout"><RotateCcw size={14} /></button></Tooltip></div>+{!data && !error && <div className="absolute inset-0 flex items-center justify-center text-ink3"><Spinner size={20} /></div>}{error && <div className="absolute inset-0 flex items-center justify-center p-8 text-center text-sm text-ink3">Couldn't load the brain: {error}</div>}{data && data.memories.length === 0 && data.persons.length === 0 && <div className="absolute inset-0 flex items-center justify-center text-sm text-ink3">Nothing in the brain yet.</div>}@@ -159,119 +283,264 @@ export function BrainGraph({ visible, onSelect, selectedId }: { visible: boolean</div>);- function linkColor(l: GraphLink, h: GraphNode | null): string {- const dark = resolved === "dark";- const lit = h && (endId(l.source) === h.id || endId(l.target) === h.id);- if (lit) return dark ? "rgba(52,225,161,0.85)" : "rgba(26,158,110,0.85)";- if (l.kind === "relation") return dark ? "rgba(224,123,168,0.5)" : "rgba(200,90,140,0.45)";- return dark ? "rgba(230,234,237,0.12)" : "rgba(22,24,26,0.12)";+ // ── drawing ──────────────────────────────────────────────────────────────++ function near(id: string): boolean {+ const h = hover.current;+ return !!h && (h.id === id || !!adjacency.current.get(h.id)?.has(id));+ }++ function isLit(l: GraphLink): boolean {+ const h = hover.current;+ return !!h && (endId(l.source) === h.id || endId(l.target) === h.id);+ }++ function linkColor(l: GraphLink): string {+ const d = dark.current;+ if (isLit(l)) return d ? "rgba(52,225,161,0.9)" : "rgba(26,158,110,0.9)";+ const f = hover.current ? 0.35 : 1;+ if (l.kind === "relation") return d ? `rgba(240,140,185,${0.7 * f})` : `rgba(200,80,140,${0.6 * f})`;+ if (l.kind === "you") return d ? `rgba(127,216,232,${0.45 * f})` : `rgba(14,124,140,${0.4 * f})`;+ if (l.kind === "hub") return d ? `rgba(230,234,237,${0.18 * f})` : `rgba(22,24,26,${0.16 * f})`;+ return d ? `rgba(230,234,237,${0.1 * f})` : `rgba(22,24,26,${0.1 * f})`;+ }++ function drawLinkLabel(l: GraphLink, ctx: CanvasRenderingContext2D, scale: number) {+ if (!l.label) return;+ if (scale < 1.1 && !isLit(l)) return;+ const s = l.source as GraphNode;+ const t = l.target as GraphNode;+ if (s.x === undefined || t.x === undefined) return;+ const x = (s.x + t.x) / 2;+ const y = ((s.y ?? 0) + (t.y ?? 0)) / 2;+ const size = 10 / scale;+ ctx.font = `500 ${size}px "Geist Variable", system-ui, sans-serif`;+ const w = ctx.measureText(l.label).width;+ if (!claim(x - w / 2, y - size / 2, w, size)) return;+ ctx.fillStyle = dark.current ? "rgba(17,19,21,0.85)" : "rgba(255,255,255,0.88)";+ ctx.fillRect(x - w / 2 - 2 / scale, y - size / 2 - 1 / scale, w + 4 / scale, size + 2 / scale);+ ctx.fillStyle = l.kind === "relation" ? (dark.current ? "#F08CB9" : "#B8437E") : (dark.current ? "#7FD8E8" : "#0E7C8C");+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";+ ctx.fillText(l.label, x, y);+ }++ /** Reserve a label box for this frame; false when it would overlap one already drawn. */+ function claim(x: number, y: number, w: number, h: number): boolean {+ for (const [ax, ay, aw, ah] of labelsDrawn.current) {+ if (x < ax + aw && x + w > ax && y < ay + ah && y + h > ay) return false;+ }+ labelsDrawn.current.push([x, y, w, h]);+ return true;}- function drawNode(n: GraphNode, ctx: CanvasRenderingContext2D, scale: number, h: GraphNode | null, near: Set<string>, selected: string | null) {- const dark = resolved === "dark";+ function drawNode(n: GraphNode, ctx: CanvasRenderingContext2D, scale: number) {+ const d = dark.current;const r = radius(n);- const dim = h && h.id !== n.id && !near.has(n.id);- ctx.globalAlpha = dim ? 0.25 : 1;+ const x = n.x ?? 0;+ const y = n.y ?? 0;+ const h = hover.current;+ const finding = matches.current.size > 0;+ const dim = (h && !near(n.id)) || (finding && !matches.current.has(n.id));+ ctx.globalAlpha = dim ? 0.18 : n.shadow ? 0.55 : 1;++ const fill = colorOf(n, d);ctx.beginPath();- ctx.arc(n.x ?? 0, n.y ?? 0, r, 0, 2 * Math.PI);- ctx.fillStyle = n.kind === "you" ? (dark ? "#34E1A1" : "#1A9E6E") : n.kind === "person" ? (dark ? "#7FD8E8" : "#0E7C8C") : n.kind === "pet" ? "#F5C451" : TYPE_COLORS[n.type ?? ""] ?? "#8A97A3";- ctx.fill();- if (selected === n.id) {+ ctx.arc(x, y, r, 0, 2 * Math.PI);+ if (n.kind === "hub") {+ ctx.fillStyle = d ? "rgba(17,19,21,0.9)" : "rgba(255,255,255,0.95)";+ ctx.fill();+ ctx.lineWidth = 2 / scale;+ ctx.strokeStyle = fill;+ ctx.stroke();+ } else if (n.shadow) {+ ctx.setLineDash([2 / scale, 2 / scale]);+ ctx.lineWidth = 1.4 / scale;+ ctx.strokeStyle = fill;+ ctx.stroke();+ ctx.setLineDash([]);+ } else {+ ctx.fillStyle = fill;+ ctx.fill();+ }+ if (selectedRef.current === n.id || matches.current.has(n.id)) {+ ctx.beginPath();+ ctx.arc(x, y, r + 3 / scale, 0, 2 * Math.PI);ctx.lineWidth = 2 / scale;- ctx.strokeStyle = dark ? "#fff" : "#000";+ ctx.strokeStyle = d ? "#fff" : "#111";ctx.stroke();}- // Names for people always; memory labels only when zoomed in or hovered.- const showLabel = n.kind !== "memory" || scale > 2.2 || h?.id === n.id;- if (showLabel) {- const size = Math.max(10 / scale, n.kind === "memory" ? 3 : 4);+ // A small dot marks a node you pinned by dragging.+ if (n.fx !== undefined && n.kind !== "you") {+ ctx.beginPath();+ ctx.arc(x + r * 0.75, y - r * 0.75, Math.max(1.2 / scale, 2 / scale), 0, 2 * Math.PI);+ ctx.fillStyle = d ? "#F5C451" : "#A0620A";+ ctx.fill();+ }++ // Labels: you and topics always; people once readable; memories when zoomed in or near the pointer.+ const lit = h?.id === n.id || near(n.id) || selectedRef.current === n.id || matches.current.has(n.id);+ const want = n.kind === "you" || n.kind === "hub" || ((n.kind === "person" || n.kind === "pet") && scale > 0.45) || (n.kind === "memory" && (scale > 2.2 || lit));+ if (want && !dim) {+ const px = n.kind === "memory" ? 10.5 : n.kind === "hub" || n.kind === "you" ? 12.5 : 12;+ const size = px / scale;ctx.font = `${n.kind === "memory" ? 400 : 600} ${size}px "Geist Variable", system-ui, sans-serif`;- ctx.textAlign = "center";- ctx.textBaseline = "top";- ctx.fillStyle = dark ? "rgba(230,234,237,0.92)" : "rgba(22,24,26,0.9)";- const text = n.kind === "memory" ? truncate(n.label, 48) : n.label;- ctx.fillText(text, n.x ?? 0, (n.y ?? 0) + r + 1.5);+ const text = n.kind === "memory" ? truncate(n.label, 54) : n.label;+ const w = ctx.measureText(text).width;+ const ty = y + r + 2 / scale;+ const free = lit || n.kind === "you" ? (labelsDrawn.current.push([x - w / 2, ty, w, size]), true) : claim(x - w / 2, ty, w, size);+ if (free) {+ ctx.textAlign = "center";+ ctx.textBaseline = "top";+ ctx.lineWidth = 3 / scale;+ ctx.strokeStyle = d ? "rgba(17,19,21,0.85)" : "rgba(255,255,255,0.9)";+ ctx.strokeText(text, x, ty);+ ctx.fillStyle = d ? "rgba(236,239,241,0.95)" : "rgba(22,24,26,0.92)";+ ctx.fillText(text, x, ty);+ }}ctx.globalAlpha = 1;}}-function toGraph(d: BrainGraphData, show: "all" | "people" | "memories"): { nodes: GraphNode[]; links: GraphLink[] } {+// ── data → graph ───────────────────────────────────────────────────────────++const CHARGE: Record<Kind, number> = { you: -700, hub: -320, person: -240, pet: -240, memory: -34 };+const LINK_DISTANCE: Record<GraphLink["kind"], number> = { you: 120, hub: 170, relation: 80, about: 42, topic: 46 };+const LINK_STRENGTH: Record<GraphLink["kind"], number> = { you: 0.35, hub: 0.5, relation: 0.45, about: 0.75, topic: 0.7 };++export function toGraph(d: BrainGraphData, show: Show): { nodes: GraphNode[]; links: GraphLink[] } {const nodes: GraphNode[] = [{ id: "you", kind: "you", label: "You", weight: 10 }];const links: GraphLink[] = [];- const people = show !== "memories";- const mems = show !== "people";- if (people) {+ const withPeople = show !== "memories";+ const withMemories = show !== "people";+ const people: GraphNode[] = [];+ const hubs = new Map<string, GraphNode>();+ const mems: GraphNode[] = [];++ if (withPeople) {for (const p of d.persons) {- nodes.push({ id: p.id, kind: p.kind === "pet" ? "pet" : "person", label: p.name, weight: p.memoryCount, relationship: p.relationship });- if (p.relationship && p.relationship !== "known") links.push({ source: "you", target: p.id, kind: "you" });+ const rel = p.relationship && p.relationship !== "known" ? p.relationship : null;+ people.push({ id: p.id, kind: p.kind === "pet" ? "pet" : "person", label: p.name, weight: p.memoryCount, relationship: rel, shadow: p.tier === "shadow" });+ links.push({ source: "you", target: p.id, kind: "you", label: rel ?? undefined });}- for (const r of d.relationships) links.push({ source: r.source, target: r.target, kind: "relation" });+ for (const r of d.relationships) links.push({ source: r.source, target: r.target, kind: "relation", label: r.type });}- if (mems) {- for (const m of d.memories) nodes.push({ id: m.id, kind: "memory", label: m.summary, type: m.type, weight: m.importance });- if (people) for (const l of d.memoryPersons) links.push({ source: l.memoryId, target: l.personId, kind: "about" });- // Memories with no person are about you.- const linked = new Set(people ? d.memoryPersons.map((l) => l.memoryId) : []);- for (const m of d.memories) if (!linked.has(m.id)) links.push({ source: "you", target: m.id, kind: "you" });+ if (withMemories) {+ const shownPeople = new Set(people.map((p) => p.id));+ const about = withPeople ? d.memoryPersons.filter((l) => shownPeople.has(l.personId)) : [];+ const linked = new Set(about.map((l) => l.memoryId));+ for (const m of d.memories) {+ mems.push({ id: m.id, kind: "memory", label: m.summary, type: m.type, weight: m.importance });+ if (linked.has(m.id)) continue;+ // Not about anyone shown: gather by topic, so the brain reads as clusters, not one star.+ const hubId = `hub:${m.type}`;+ let hub = hubs.get(hubId);+ if (!hub) {+ hub = { id: hubId, kind: "hub", label: HUB_LABEL[m.type] ?? m.type, type: m.type, weight: 0 };+ hubs.set(hubId, hub);+ links.push({ source: "you", target: hubId, kind: "hub" });+ }+ hub.weight += 1;+ links.push({ source: m.id, target: hubId, kind: "topic" });+ }+ for (const l of about) links.push({ source: l.memoryId, target: l.personId, kind: "about" });}+ for (const h of hubs.values()) h.label = `${h.label} · ${h.weight}`;+ // Draw order is label priority: you, topics, people, then memories.+ nodes.push(...hubs.values(), ...people, ...mems);return { nodes, links };}function radius(n: GraphNode): number {- if (n.kind === "you") return 9;- if (n.kind === "memory") return 2.2 + Math.min(2.5, n.weight * 2.5);- return 3.5 + Math.min(6, Math.sqrt(n.weight) * 1.1);+ if (n.kind === "you") return 11;+ if (n.kind === "hub") return 6 + Math.min(8, Math.sqrt(n.weight) * 1.2);+ if (n.kind === "memory") return 2.4 + Math.min(2.6, n.weight * 2.6);+ return 4.5 + Math.min(7, Math.sqrt(n.weight) * 1.3);+}++function colorOf(n: GraphNode, dark: boolean): string {+ if (n.kind === "you") return dark ? "#34E1A1" : "#1A9E6E";+ if (n.kind === "person") return dark ? "#7FD8E8" : "#0E7C8C";+ if (n.kind === "pet") return dark ? "#F5C451" : "#B7791F";+ return TYPE_COLORS[n.type ?? ""] ?? "#8A97A3";}function endId(e: string | number | GraphNode | undefined): string {return typeof e === "object" && e ? String(e.id) : String(e ?? "");}-function neighbourIds(data: { links: GraphLink[] }, id: string): Set<string> {- const out = new Set<string>();- for (const l of data.links) {- const s = endId(l.source);- const t = endId(l.target);- if (s === id) out.add(t);- if (t === id) out.add(s);- }- return out;+function buildAdjacency(links: GraphLink[]): Map<string, Set<string>> {+ const m = new Map<string, Set<string>>();+ const add = (a: string, b: string) => { let s = m.get(a); if (!s) { s = new Set(); m.set(a, s); } s.add(b); };+ for (const l of links) { const s = endId(l.source); const t = endId(l.target); add(s, t); add(t, s); }+ return m;}function truncate(s: string, n: number): string {return s.length > n ? `${s.slice(0, n - 1)}…` : s;}-function savePositions(nodes: GraphNode[]): void {+// ── placement: random start, pins kept for the session ─────────────────────++function readPins(): Record<string, [number, number]> {+ try { return JSON.parse(sessionStorage.getItem(PINS_KEY) ?? "{}") as Record<string, [number, number]>; } catch { return {}; }+}++function savePin(n: GraphNode) {try {- const out: Record<string, [number, number]> = {};- for (const n of nodes) if (n.x !== undefined && n.y !== undefined) out[n.id] = [Math.round(n.x), Math.round(n.y)];- sessionStorage.setItem(POSITIONS_KEY, JSON.stringify(out));- } catch { /* storage full or blocked: positions are a convenience */ }+ const pins = readPins();+ pins[n.id] = [Math.round(n.x ?? 0), Math.round(n.y ?? 0)];+ sessionStorage.setItem(PINS_KEY, JSON.stringify(pins));+ } catch { /* storage blocked: the pin still holds until reload */ }+}++function clearPins() {+ try { sessionStorage.removeItem(PINS_KEY); } catch { /* ignore */ }+}++/** Random scatter around the centre, so every fresh layout flows in from a new start. */+function scatter(nodes: GraphNode[], unpin: boolean) {+ const rnd = (a: number, b: number) => a + Math.random() * (b - a);+ for (const n of nodes) {+ if (n.kind === "you") { n.x = 0; n.y = 0; n.fx = 0; n.fy = 0; n.vx = 0; n.vy = 0; continue; }+ if (unpin) { n.fx = undefined; n.fy = undefined; }+ const angle = rnd(0, Math.PI * 2);+ const dist = n.kind === "hub" ? rnd(160, 260) : n.kind === "memory" ? rnd(120, 420) : rnd(70, 220);+ n.x = Math.cos(angle) * dist;+ n.y = Math.sin(angle) * dist;+ n.vx = 0;+ n.vy = 0;+ }}-function withPositions(g: { nodes: GraphNode[]; links: GraphLink[] }, live?: GraphNode[]): { nodes: GraphNode[]; links: GraphLink[] } {- let saved: Record<string, [number, number]> = {};- try { saved = JSON.parse(sessionStorage.getItem(POSITIONS_KEY) ?? "{}"); } catch { saved = {}; }- const current = new Map((live ?? []).map((n) => [n.id, n]));- return {- nodes: g.nodes.map((n) => {- const c = current.get(n.id);- if (c?.x !== undefined) return { ...n, x: c.x, y: c.y };- const p = saved[n.id];- return p ? { ...n, x: p[0], y: p[1] } : n;- }),- links: g.links.map((l) => ({ ...l, source: endId(l.source), target: endId(l.target) })),- };+/** Keep live positions, apply pins, scatter the rest at random. "You" sits fixed at the centre. */+function place(g: { nodes: GraphNode[]; links: GraphLink[] }, live: GraphNode[]): { nodes: GraphNode[]; links: GraphLink[] } {+ const pins = readPins();+ const current = new Map(live.map((n) => [n.id, n]));+ const fresh: GraphNode[] = [];+ const nodes = g.nodes.map((n) => {+ const c = current.get(n.id);+ const pin = pins[n.id];+ if (n.kind === "you") return { ...n, x: 0, y: 0, fx: 0, fy: 0 };+ if (pin) return { ...n, x: pin[0], y: pin[1], fx: pin[0], fy: pin[1] };+ if (c?.x !== undefined) return { ...n, x: c.x, y: c.y, vx: c.vx, vy: c.vy, fx: c.fx, fy: c.fy };+ const copy = { ...n };+ fresh.push(copy);+ return copy;+ });+ scatter(fresh, false);+ return { nodes, links: g.links.map((l) => ({ ...l, source: endId(l.source), target: endId(l.target) })) };}function Legend() {- const items: Array<[string, string]> = [["You", "bg-accent"], ["Person", "bg-cyan"], ["Pet", "bg-amber"], ["Memory", "bg-ink3"]];+ const items: Array<[string, string]> = [["You", "bg-accent"], ["Person", "bg-cyan"], ["Pet", "bg-amber"]];return (- <div className="pointer-events-none absolute bottom-3 left-4 flex items-center gap-3 rounded-md bg-surface/80 px-2.5 py-1.5 text-xs text-ink3 backdrop-blur">+ <div className="pointer-events-none absolute bottom-3 left-4 flex flex-wrap items-center gap-3 rounded-md bg-surface/85 px-2.5 py-1.5 text-xs text-ink3 backdrop-blur">{items.map(([label, cls]) => <span key={label} className="flex items-center gap-1.5"><span className={cx("block h-2.5 w-2.5 rounded-full", cls)} />{label}</span>)}- <span className="text-ink4">· drag to move · scroll to zoom · click for details</span>+ <span className="flex items-center gap-1.5"><span className="block h-2.5 w-2.5 rounded-full border border-dashed border-cyan" />Shadow</span>+ <span className="flex items-center gap-1.5"><span className="block h-2.5 w-2.5 rounded-full border-2 border-ink3" />Topic</span>+ <span className="text-ink4">· drag to pin · scroll or +/− to zoom · click for details</span></div>);}diff --git a/apps/desktop/src/views/brain/BrainView.tsx b/apps/desktop/src/views/brain/BrainView.tsxindex f75eeb5e..65d7c4c9 100644--- a/apps/desktop/src/views/brain/BrainView.tsx+++ b/apps/desktop/src/views/brain/BrainView.tsx@@ -4,7 +4,7 @@ import { useUi } from "~/app/store";import { ErrorBoundary } from "~/components/ErrorBoundary";import { Badge, Segmented, Spinner } from "~/components/ui/bits";import { PageHeader } from "~/components/ui/kit";-import { BrainGraph, type GraphNode } from "./BrainGraph";+import { BrainGraph, type SelectableKind } from "./BrainGraph";import { Memories } from "./Memories";import { People } from "./People";import { PersonCard } from "./PersonCard";@@ -21,7 +21,7 @@ export function BrainView() {const view = useUi((s) => s.view);const [tab, setTab] = useState<Tab>(() => { try { return (sessionStorage.getItem(TAB_KEY) as Tab) || "graph"; } catch { return "graph"; } });const [opened, setOpened] = useState<Record<Tab, boolean>>({ graph: false, memories: false, people: false });- const [selected, setSelected] = useState<{ id: string; kind: GraphNode["kind"] } | null>(null);+ const [selected, setSelected] = useState<{ id: string; kind: SelectableKind } | null>(null);const [people, setPeople] = useState<BrainPerson[]>([]);const visible = view === "brain";diff --git a/apps/desktop/src/views/brain/People.tsx b/apps/desktop/src/views/brain/People.tsxindex 232db755..c7c3498d 100644--- a/apps/desktop/src/views/brain/People.tsx+++ b/apps/desktop/src/views/brain/People.tsx@@ -7,17 +7,19 @@ import { SearchField } from "~/components/ui/kit";import { cx } from "~/lib/cx";import { Initials, PersonCard, VerifiedBadge } from "./PersonCard";-type Filter = "people" | "pets" | "unreviewed" | "all";+type Filter = "known" | "shadow" | "pets" | "all";/**- * People: contact cards for everyone in the brain, search, filters, and the- * card on the right. "Unreviewed" are names Mercury found but nobody has- * confirmed; the checks panel shows the slow, capped model check.+ * People: contact cards, search, filters, and the card on the right.+ * Known are people with recurring mentions and a real tie (a relationship+ * to you or to someone else); Shadows are names Mercury is not sure about+ * yet: kept, out of the way, and promoted by evidence or by you. The+ * checks panel (under Shadows) shows the slow, capped model check.*/export function People({ initialId }: { initialId?: string | null }) {const [people, setPeople] = useState<BrainPerson[] | null>(null);const [q, setQ] = useState("");- const [filter, setFilter] = useState<Filter>("people");+ const [filter, setFilter] = useState<Filter>("known");const [selected, setSelected] = useState<string | null>(initialId ?? null);const [error, setError] = useState<string | null>(null);@@ -31,14 +33,14 @@ export function People({ initialId }: { initialId?: string | null }) {const shown = useMemo(() => {const query = q.trim().toLowerCase();return (people ?? [])- .filter((p) => filter === "all" || (filter === "pets" ? p.kind === "pet" : filter === "unreviewed" ? p.kind === "unverified" : p.kind === "person" || (p.kind === "unverified" && !!p.relationship && p.relationship !== "known")))+ .filter((p) => filter === "all" || (filter === "pets" ? p.kind === "pet" : tierOf(p) === filter)).filter((p) => !query || p.name.toLowerCase().includes(query) || (p.relationship ?? "").toLowerCase().includes(query) || JSON.stringify(p.meta ?? {}).toLowerCase().includes(query));}, [people, q, filter]);const counts = useMemo(() => ({- people: (people ?? []).filter((p) => p.kind === "person" || (p.kind === "unverified" && !!p.relationship && p.relationship !== "known")).length,+ known: (people ?? []).filter((p) => tierOf(p) === "known").length,+ shadow: (people ?? []).filter((p) => tierOf(p) === "shadow").length,pets: (people ?? []).filter((p) => p.kind === "pet").length,- unreviewed: (people ?? []).filter((p) => p.kind === "unverified").length,}), [people]);if (error) return <Empty title="Couldn't load people" body={error} />;@@ -49,25 +51,28 @@ export function People({ initialId }: { initialId?: string | null }) {<div className="flex min-w-0 flex-1 flex-col"><div className="flex shrink-0 flex-wrap items-center gap-3 px-6 pb-3 pt-4"><Segmented size="md" value={filter} onChange={setFilter} options={[- { value: "people", label: `People · ${counts.people}` },+ { value: "known", label: `Known · ${counts.known}` },+ { value: "shadow", label: `Shadows · ${counts.shadow}` },{ value: "pets", label: `Pets · ${counts.pets}` },- { value: "unreviewed", label: `Unreviewed · ${counts.unreviewed}` },{ value: "all", label: "All" },]} /><SearchField value={q} onChange={setQ} placeholder="Search names, relationships, details" className="ml-auto w-[300px]" /></div>- {filter === "unreviewed" && <ChecksPanel onChanged={load} />}+ {filter === "shadow" && (+ <p className="mx-6 mb-2 text-sm text-ink3">Names Mercury isn't sure about yet. They join Known once they recur and have a relationship, or when you confirm them.</p>+ )}+ {filter === "shadow" && <ChecksPanel onChanged={load} />}<div className="min-h-0 flex-1 overflow-y-auto px-6 pb-6">- {shown.length === 0 ? <Empty title={q ? "No one matches" : filter === "unreviewed" ? "Nothing to review" : "No one here yet"} /> : (+ {shown.length === 0 ? <Empty title={q ? "No one matches" : filter === "shadow" ? "No shadows" : "No one here yet"} /> : (<div className="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-3">{shown.map((p) => (<button key={p.id} onClick={() => setSelected(p.id)}- className={cx("flex items-center gap-3 rounded-xl border bg-surface p-3 text-left transition-colors hover:border-line-strong", selected === p.id ? "border-accent/60" : "border-line")}>+ className={cx("flex items-center gap-3 rounded-xl border bg-surface p-3 text-left transition-colors hover:border-line-strong", selected === p.id ? "border-accent/60" : "border-line", tierOf(p) !== "known" && "opacity-75")}><Initials name={p.name} kind={p.kind} size={40} /><span className="min-w-0 flex-1"><span className="block truncate text-base font-medium text-ink">{p.name}</span><span className="block truncate text-xs capitalize text-ink3">{p.relationship && p.relationship !== "known" ? p.relationship : `${p.memoryCount} memor${p.memoryCount === 1 ? "y" : "ies"}`}</span>- <span className="mt-1 block"><VerifiedBadge p={p} /></span>+ <span className="mt-1 flex items-center gap-1.5"><VerifiedBadge p={p} />{p.standing && <span className="font-mono text-2xs text-ink4" title={p.standing.reasons.join(" · ")}>{p.standing.score}</span>}</span></span></button>))}@@ -84,6 +89,10 @@ export function People({ initialId }: { initialId?: string | null }) {);}+function tierOf(p: BrainPerson): "known" | "shadow" | "faint" {+ return p.standing?.tier ?? "shadow";+}+/** Dev-visible: what the "is it a person?" check is doing, with manual controls. */function ChecksPanel({ onChanged }: { onChanged: () => void }) {const [s, setS] = useState<CheckStatus | null>(null);diff --git a/apps/desktop/src/views/brain/PersonCard.tsx b/apps/desktop/src/views/brain/PersonCard.tsxindex 9b9aa226..d67da9fa 100644--- a/apps/desktop/src/views/brain/PersonCard.tsx+++ b/apps/desktop/src/views/brain/PersonCard.tsx@@ -1,6 +1,7 @@import { Cake, Check, Mail, MapPin, PawPrint, Phone, ShieldCheck, Sparkles, Briefcase, Link2, X } from "lucide-react";import { useEffect, useMemo, useState } from "react";import { brain, type BrainMemory, type BrainPerson, type PersonMeta } from "~/api/brain";+import { ApiError } from "~/api/client";import { Button } from "~/components/ui/Button";import { Field, Input } from "~/components/ui/Input";import { Badge, Segmented, Spinner } from "~/components/ui/bits";@@ -49,6 +50,8 @@ export function PersonCard({ id, onClose, onChanged, allPeople }: { id: string;{onClose && <button onClick={onClose} className="rounded-md p-1 text-ink4 hover:text-ink" aria-label="Close"><X size={16} /></button>}</div>+ {!editing && person.standing && <StandingPanel person={person} />}+{editing? <EditForm person={person} onCancel={() => setEditing(false)} onSaved={(p) => { setPerson(p); setEditing(false); onChanged(); }} />: <ContactDetails person={person} />}@@ -113,13 +116,19 @@ function EditForm({ person, onCancel, onSaved }: { person: BrainPerson; onCancelconst [links, setLinks] = useState((person.meta.links ?? []).join("\n"));const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ const [conflict, setConflict] = useState<string | null>(null);+ const [relations, setRelations] = useState<Array<{ label: string; cardinality: "one" | "many" }>>([]);+ useEffect(() => { void brain.relations().then((r) => setRelations(r.relations)).catch(() => {}); }, []);+ const spec = relations.find((r) => r.label === relationship.trim().toLowerCase());const set = (k: keyof PersonMeta) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setMeta((m) => ({ ...m, [k]: e.target.value }));- async function save() {+ async function save(force = false) {setBusy(true);setError(null);+ setConflict(null);try {const r = await brain.updatePerson(person.id, {+ ...(force ? { force: true } : {}),name: name.trim() || person.name,kind,relationship: relationship.trim() || null,@@ -128,7 +137,9 @@ function EditForm({ person, onCancel, onSaved }: { person: BrainPerson; onCancel});if (r.person) onSaved(r.person);} catch (e) {- setError(e instanceof Error ? e.message : String(e));+ // A one-to-one relation someone else holds: say who, offer to move it.+ if (e instanceof ApiError && e.status === 409) setConflict(e.message);+ else setError(e instanceof Error ? e.message : String(e));} finally {setBusy(false);}@@ -140,7 +151,17 @@ function EditForm({ person, onCancel, onSaved }: { person: BrainPerson; onCancel<Field label="Name" htmlFor="pc-name"><Input id="pc-name" value={name} onChange={(e) => setName(e.target.value)} /></Field><Segmented<"person" | "pet"> value={kind} onChange={setKind} options={[{ value: "person", label: "Person" }, { value: "pet", label: "Pet" }]} /></div>- <Field label="Relationship to you" htmlFor="pc-rel"><Input id="pc-rel" value={relationship} onChange={(e) => setRelationship(e.target.value)} placeholder="wife, son, friend, colleague…" /></Field>+ <Field label="Relationship to you" htmlFor="pc-rel">+ <Input id="pc-rel" list="pc-rel-options" value={relationship} onChange={(e) => { setRelationship(e.target.value); setConflict(null); }} placeholder="wife, son, friend, colleague…" />+ <datalist id="pc-rel-options">{relations.map((r) => <option key={r.label} value={r.label}>{r.cardinality === "one" ? "only one person" : ""}</option>)}</datalist>+ {spec && <span className="mt-1 block text-xs text-ink4">{spec.cardinality === "one" ? `Only one person can be your ${spec.label}.` : `You can have any number of ${spec.label}s.`}</span>}+ </Field>+ {conflict && (+ <div className="flex flex-wrap items-center gap-2 rounded-lg border border-amber/40 bg-amber/10 px-3 py-2 text-sm text-ink">+ <span className="flex-1">{conflict}</span>+ <Button type="button" size="sm" variant="outline" onClick={() => void save(true)}>Move it to {name.trim() || person.name}</Button>+ </div>+ )}<Field label="About" htmlFor="pc-sum"><textarea id="pc-sum" value={summary} onChange={(e) => setSummary(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-accent/60" /></Field><div className="grid grid-cols-2 gap-3"><Field label="Phone" htmlFor="pc-phone"><Input id="pc-phone" value={meta.phone ?? ""} onChange={set("phone")} /></Field>@@ -188,6 +209,25 @@ function MergeInto({ person, people, onMerged }: { person: BrainPerson; people:);}+/** Why Mercury counts (or doesn't yet count) this as someone in your life. */+function StandingPanel({ person }: { person: BrainPerson }) {+ const s = person.standing!;+ const tone = s.tier === "known" ? "bg-accent" : s.tier === "shadow" ? "bg-amber" : "bg-ink4";+ const label = s.tier === "known" ? "Known" : s.tier === "shadow" ? "Shadow" : "Faint";+ return (+ <div className="rounded-xl border border-line bg-surface p-3">+ <div className="flex items-center gap-2 text-sm">+ <span className="font-medium text-ink">{label}</span>+ <span className="font-mono text-xs text-ink3">{s.score}/100</span>+ {person.cardinality === "one" && <span className="text-xs text-ink4">· one-to-one relationship</span>}+ </div>+ <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-ink/[0.08]"><div className={cx("h-full rounded-full", tone)} style={{ width: `${s.score}%` }} /></div>+ {s.reasons.length > 0 && <div className="mt-2 text-xs text-ink3">{s.reasons.join(" · ")}</div>}+ {s.tier !== "known" && <div className="mt-1 text-xs text-ink4">Confirm them below, or they join Known once they recur with a relationship.</div>}+ </div>+ );+}+export function VerifiedBadge({ p }: { p: Pick<BrainPerson, "kind" | "verifiedBy"> }) {if (p.verifiedBy === "owner") return <Badge tone="accent"><ShieldCheck size={11} className="mr-1" />{p.kind === "pet" ? "pet · you" : "confirmed by you"}</Badge>;if (p.verifiedBy === "model") return <Badge tone="cyan"><Sparkles size={11} className="mr-1" />{p.kind === "pet" ? "pet · checked" : "checked"}</Badge>;