Skip to content

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

perf(wiki): stop the wiki stalling on every view and keystroke

Ruben Lütkece8bf1948310
diff --git a/jarvis/memory/wiki/consolidator.py b/jarvis/memory/wiki/consolidator.py
index a86ea25730..e1b8f4f0f5 100644
--- a/jarvis/memory/wiki/consolidator.py
+++ b/jarvis/memory/wiki/consolidator.py
@@ -216,6 +216,13 @@ class Consolidator:
# In-memory by design: bounds the burn within one process life while
# a restart (usually carrying a fix) retries parked-adjacent rows.
self._judge_rejections: dict[int, tuple[int, float]] = {}
+ # Page bodies read during ONE run, keyed by vault-relative target.
+ # Validation re-reads the same residence/profile pages once per
+ # decision item AND once per provider attempt; a cycle-scoped memo
+ # turns that repeated disk traffic into one read per page. Cleared
+ # at the start of every judge/execute cycle so no cached body can
+ # outlive a write. ``None`` records "unreadable/absent".
+ self._page_body_cache: dict[str, str | None] = {}
# ------------------------------------------------------------------
# public API
@@ -223,7 +230,12 @@ class Consolidator:
async def run_once(self, *, review_keys: Sequence[str] | None = None) -> str:
"""Drain one batch, optionally scoped to exact capture reviews."""
- rows = self._journal.pending(
+ # Every blocking step of a run (SQLite, vault reads, FTS) is pushed
+ # to a worker thread. A run is triggered from the app's event loop,
+ # which also serves the Desktop UI, the WebSocket stream, and the
+ # voice path — a synchronous batch there stalls all of them (AP-9).
+ rows = await asyncio.to_thread(
+ self._journal.pending,
limit=self._batch_limit,
review_keys=review_keys,
)
@@ -249,7 +261,7 @@ class Consolidator:
row for row in rows if row.review_key and not row.evidence_excerpt
]
if ungrounded:
- self._journal.mark(
+ await self._mark(
[row.id for row in ungrounded],
status="rejected",
)
@@ -289,7 +301,15 @@ class Consolidator:
"""Judge rows, bisecting capacity failures without losing candidates."""
if not rows:
return _BatchOutcome()
- neighbours = self._collect_neighbours(rows)
+ # Fresh page reads per judge/execute cycle. Every read in a cycle
+ # happens before that cycle's writes, so the memo can never serve a
+ # body this run already replaced — and the bisection recursion starts
+ # each half with a clean slate.
+ self._page_body_cache.clear()
+ # Retrieval is FTS5 plus up to ``k_nearest * len(rows)`` full page
+ # reads — hundreds of milliseconds of disk work that must never run
+ # on the event loop.
+ neighbours = await asyncio.to_thread(self._collect_neighbours, rows)
decisions = await self._judge(rows, neighbours)
if decisions is None:
# Provider timeout/unavailability is not a content verdict. Keep
@@ -302,7 +322,7 @@ class Consolidator:
# data loss. Retryable is still bounded: repeat rejections
# back off, then park the row (see _note_judge_rejection).
if decisions == "rejected":
- self._note_judge_rejection(rows[0])
+ await self._note_judge_rejection(rows[0])
return _BatchOutcome(rejected=1)
return _BatchOutcome(truncated=True)
midpoint = len(rows) // 2
@@ -324,6 +344,28 @@ class Consolidator:
transient=transient,
)
+ async def _mark(
+ self,
+ ids: Sequence[int],
+ *,
+ status: str,
+ decision: str | None = None,
+ target_path: str | None = None,
+ ) -> None:
+ """Close journal rows off the event loop.
+
+ Each ``mark`` is a SQLite write transaction, and a batch closes up to
+ ``batch_limit`` rows one call at a time. On the loop that is a visible
+ stall in the UI and the voice path for every run.
+ """
+ await asyncio.to_thread(
+ self._journal.mark,
+ list(ids),
+ status=status, # type: ignore[arg-type]
+ decision=decision, # type: ignore[arg-type]
+ target_path=target_path,
+ )
+
def _in_rejection_backoff(self, row_id: int) -> bool:
"""True while a judge-rejected row waits out its escalating backoff."""
history = self._judge_rejections.get(row_id)
@@ -332,7 +374,7 @@ class Consolidator:
rounds, last_ts = history
return (time.monotonic() - last_ts) < self._JUDGE_REJECTION_BACKOFF_S * rounds
- def _note_judge_rejection(self, row: JournalRow) -> None:
+ async def _note_judge_rejection(self, row: JournalRow) -> None:
"""Record one all-provider judge rejection; park the row at the cap.
``skipped`` (not ``rejected``) because the JUDGE never produced a
@@ -342,7 +384,7 @@ class Consolidator:
rounds = self._judge_rejections.get(row.id, (0, 0.0))[0] + 1
if rounds >= self._MAX_JUDGE_REJECTION_ROUNDS:
self._judge_rejections.pop(row.id, None)
- self._journal.mark([row.id], status="skipped")
+ await self._mark([row.id], status="skipped")
telemetry.inc("wiki_consolidator_parked_judge_wedge")
log.warning(
"Consolidator: parking candidate %d as skipped after %d "
@@ -810,36 +852,36 @@ class Consolidator:
if cid in deferred_ids:
continue
if cid in duplicate_target_ids:
- self._journal.mark([cid], status="skipped")
+ await self._mark([cid], status="skipped")
log.warning(
"Consolidator: candidate %d proposed the same target twice; skipped",
cid,
)
continue
if cid in noop_ids:
- self._journal.mark([cid], status="consolidated", decision="noop")
+ await self._mark([cid], status="consolidated", decision="noop")
telemetry.inc("wiki_consolidator_noop")
continue
plan = write_plan.get(cid)
if plan is None:
# Judge returned nothing usable for this candidate.
- self._journal.mark([cid], status="skipped")
+ await self._mark([cid], status="skipped")
log.debug("Consolidator: candidate %d unjudged — skipped", cid)
continue
decision, target = plan
if decision is None or target is None:
- self._journal.mark([cid], status="skipped")
+ await self._mark([cid], status="skipped")
continue
required = required_targets.get(cid, {target})
if required and required.issubset(applied_rel):
- self._journal.mark(
+ await self._mark(
[cid], status="consolidated",
- decision=decision, # type: ignore[arg-type]
+ decision=decision,
target_path=target,
)
telemetry.inc(f"wiki_consolidator_{decision}")
elif required & rejected_rel:
- self._journal.mark([cid], status="rejected", target_path=target)
+ await self._mark([cid], status="rejected", target_path=target)
log.warning(
"Consolidator: write for candidate %d rejected "
"(secret guard / validation) — %s", cid, target,
@@ -971,16 +1013,33 @@ class Consolidator:
(graph_target, user_slug),
(profile_target, topic_slug),
):
- path = self._vault_root / target
- try:
- body = path.read_text(encoding="utf-8")
- except OSError:
+ body = self._read_page(target)
+ if body is None:
required.add(target)
continue
if not self._body_links_to_slug(body, linked_slug):
required.add(target)
return required
+ def _read_page(self, target: str) -> str | None:
+ """Read a vault-relative page once per run; ``None`` when unreadable.
+
+ ``_validate_decisions`` runs once per provider attempt and again in
+ ``_execute``, and probes the same residence/profile pages for every
+ decision item — without the memo one batch re-read the same handful
+ of files a dozen times.
+ """
+ if target in self._page_body_cache:
+ return self._page_body_cache[target]
+ try:
+ body: str | None = (self._vault_root / target).read_text(
+ encoding="utf-8"
+ )
+ except OSError:
+ body = None
+ self._page_body_cache[target] = body
+ return body
+
def _is_required_place_secondary_update(
self,
row: JournalRow,
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.render.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.render.test.tsx
new file mode 100644
index 0000000000..33921ba2a6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.render.test.tsx
@@ -0,0 +1,221 @@
+/**
+ * Render-loop and camera guards for the Memory-Map.
+ *
+ * `WikiGraph.test.tsx` mocks `react-force-graph-2d` with a prop recorder and
+ * no imperative handle, which is enough for data/click behaviour but blind to
+ * everything the component does THROUGH the library instance. These tests
+ * install a handle so the expensive paths are observable:
+ *
+ * 1. d3 forces are configured once per data generation, not per engine tick
+ * (the tick handler used to re-initialise every force on every frame).
+ * 2. a settled engine does not yank the camera back after the user panned.
+ * 3. the component's own fit animation is not mistaken for a user pan.
+ * 4. the render loop is parked once nothing needs frames any more.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { PropsWithChildren } from "react";
+
+import { WikiGraph } from "@/components/wiki/WikiGraph";
+
+const { forceGraphProps, handle } = vi.hoisted(() => {
+ const chargeForce = { strength: vi.fn(), distanceMax: vi.fn() };
+ const linkForce = { distance: vi.fn(), strength: vi.fn() };
+ const centerForce = { strength: vi.fn() };
+ return {
+ forceGraphProps: [] as Array<Record<string, unknown>>,
+ handle: {
+ chargeForce,
+ linkForce,
+ centerForce,
+ d3Force: vi.fn((name: string) => {
+ if (name === "charge") return chargeForce;
+ if (name === "link") return linkForce;
+ if (name === "center") return centerForce;
+ return undefined;
+ }),
+ zoomToFit: vi.fn(),
+ centerAt: vi.fn(),
+ zoom: vi.fn(() => 1),
+ getGraphBbox: vi.fn(() => ({ x: [-100, 100], y: [-100, 100] })),
+ screen2GraphCoords: vi.fn(() => ({ x: 0, y: 0 })),
+ pauseAnimation: vi.fn(),
+ resumeAnimation: vi.fn(),
+ },
+ };
+});
+
+vi.mock("react-force-graph-2d", async () => {
+ const { forwardRef, useImperativeHandle } = await import("react");
+ return {
+ default: forwardRef(function ForceGraphMock(
+ props: Record<string, unknown>,
+ ref,
+ ) {
+ forceGraphProps.push(props);
+ useImperativeHandle(ref, () => handle, []);
+ return null;
+ }),
+ };
+});
+
+const PAYLOAD = {
+ ok: true,
+ nodes: [
+ { id: "ruben", kind: "entity", title: "Ruben" },
+ { id: "harald", kind: "entity", title: "Harald" },
+ { id: "golf", kind: "concept", title: "Golf" },
+ ],
+ edges: [{ source: "ruben", target: "harald", context: "knows" }],
+ broken: [],
+};
+
+function makeClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+}
+
+function Wrapper({ children, client }: PropsWithChildren<{ client: QueryClient }>) {
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
+
+/** Latest props the component handed to the library. */
+function latest(): Record<string, unknown> {
+ return forceGraphProps[forceGraphProps.length - 1];
+}
+
+async function renderGraph() {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ new Response(JSON.stringify(PAYLOAD), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ ),
+ );
+ const client = makeClient();
+ render(
+ <Wrapper client={client}>
+ <WikiGraph onNodeClick={() => {}} />
+ </Wrapper>,
+ );
+ await waitFor(() => {
+ expect(forceGraphProps.length).toBeGreaterThan(0);
+ });
+ // Let the pending auto-fit / resize-fit timers settle so each test starts
+ // from a quiet camera.
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ });
+ vi.clearAllMocks();
+}
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ forceGraphProps.length = 0;
+});
+
+describe("WikiGraph render loop", () => {
+ it("configures the d3 forces once, not on every engine tick", async () => {
+ await renderGraph();
+ const onEngineTick = latest().onEngineTick as () => void;
+
+ await act(async () => {
+ for (let i = 0; i < 12; i += 1) onEngineTick();
+ });
+
+ // Each of these setters walks every node (charge) or every link (link
+ // distance) inside d3, so calling them per frame is an O(n) tax on the
+ // whole simulation.
+ expect(handle.chargeForce.strength).toHaveBeenCalledTimes(1);
+ expect(handle.linkForce.distance).toHaveBeenCalledTimes(1);
+ expect(handle.centerForce.strength).toHaveBeenCalledTimes(1);
+ });
+
+ it("re-fits the camera when the engine settles and the user has not panned", async () => {
+ await renderGraph();
+ const props = latest();
+
+ await act(async () => {
+ (props.onEngineStop as () => void)();
+ });
+
+ expect(handle.zoomToFit).toHaveBeenCalled();
+ });
+
+ it("does not yank the camera back after the user panned", async () => {
+ await renderGraph();
+ const props = latest();
+
+ await act(async () => {
+ (props.onZoom as () => void)(); // user drags the canvas
+ (props.onEngineStop as () => void)(); // a reheat settles afterwards
+ });
+
+ expect(handle.zoomToFit).not.toHaveBeenCalled();
+ });
+
+ it("does not treat its own fit animation as a user pan", async () => {
+ await renderGraph();
+ const props = latest();
+
+ await act(async () => {
+ (props.onEngineStop as () => void)();
+ });
+ expect(handle.zoomToFit).toHaveBeenCalledTimes(1);
+
+ // zoomToFit eases over its duration and emits a zoom event per frame.
+ // Those are ours; a later settle must still be allowed to re-fit.
+ await act(async () => {
+ (props.onZoom as () => void)();
+ (props.onEngineStop as () => void)();
+ });
+
+ expect(handle.zoomToFit).toHaveBeenCalledTimes(2);
+ });
+
+ it("parks the render loop once the layout has settled", async () => {
+ await renderGraph();
+ const props = latest();
+
+ await act(async () => {
+ (props.onEngineStop as () => void)();
+ });
+ // The fit animation still needs frames — pausing is deferred, not skipped.
+ expect(handle.pauseAnimation).not.toHaveBeenCalled();
+
+ await act(async () => {
+ vi.advanceTimersByTime(1500);
+ });
+
+ expect(handle.pauseAnimation).toHaveBeenCalled();
+ });
+
+ it("wakes the render loop back up when the pointer returns", async () => {
+ await renderGraph();
+ const props = latest();
+
+ await act(async () => {
+ (props.onEngineStop as () => void)();
+ vi.advanceTimersByTime(1500);
+ });
+ expect(handle.pauseAnimation).toHaveBeenCalled();
+
+ const wrap = document.querySelector('[data-testid="wiki-graph-wrap"]');
+ expect(wrap).not.toBeNull();
+ await act(async () => {
+ wrap?.dispatchEvent(new Event("pointerenter"));
+ });
+
+ expect(handle.resumeAnimation).toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
index cbccd63ba4..ff5519a146 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
@@ -7,7 +7,7 @@
//
// Visual contract: docs/plans/b3/00-OVERVIEW.md §3. Node colours live in
// `lib/wikiGraph.ts:NODE_COLOUR` — never hardcoded here.
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import ForceGraph2D from "react-force-graph-2d";
import type { ForceGraphMethods, NodeObject } from "react-force-graph-2d";
@@ -23,10 +23,16 @@ import {
type WikiGraphPayload,
} from "@/lib/wikiGraph";
import { useEventStore } from "@/store/events";
-import { useT } from "@/i18n";
+import { useT, useUiLanguage } from "@/i18n";
const GRAPH_QUERY_KEY = ["wiki", "graph"] as const;
+/** Extra render-loop controls the library exposes but the typings omit. */
+interface RenderControls {
+ pauseAnimation?: () => void;
+ resumeAnimation?: () => void;
+}
+
async function fetchGraph(): Promise<WikiGraphPayload> {
const res = await fetch("/api/wiki/graph");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
@@ -77,6 +83,15 @@ function edgeDetails(
return `${source} → ${target}${relationship ? ` · ${relationship}` : ""}`;
}
+/** Node radius in graph units — shared by the hit area and the label offset. */
+function nodeSizeScore(node: RenderNode, isActive: boolean): number {
+ const backlinks = node.backlinkCount ?? 0;
+ // Range 1.0 ... 2.6 → with nodeRelSize=2 that's a node radius of roughly
+ // 2.8 px (leaf) ... 4.6 px (hub).
+ const sizeScore = 1.0 + Math.min(backlinks, 8) * 0.2;
+ return isActive ? sizeScore * 1.5 : sizeScore;
+}
+
export interface WikiGraphProps {
onNodeClick: (slug: string) => void;
/** When set, render that node enlarged with a glow. */
@@ -85,12 +100,35 @@ export interface WikiGraphProps {
/**
* Memory-Map force-graph. Mounts the canvas lazily when the Wiki tab renders
- * (parent owns mounting) and freezes the simulation after a short warm-up so
- * an idle Wiki tab stops repainting the canvas.
+ * (parent owns mounting) and parks the render loop once the layout has
+ * settled and the pointer is elsewhere, so an idle Wiki tab stops burning a
+ * frame budget it cannot use.
*/
export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.Element {
const assistantName = useEventStore((s) => s.assistantName);
+ const uiLanguage = useUiLanguage();
const t = useT();
+ // `useT()` returns a FRESH closure on every render, so using it directly in
+ // a dependency array silently defeats every memo below — and this component
+ // re-renders on each canvas measurement. Keep a stable callable whose
+ // identity only changes when the language or the assistant name changes.
+ const tRef = useRef(t);
+ tRef.current = t;
+ const tStable = useCallback(
+ (key: string) => tRef.current(key),
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- identity is
+ // deliberately pinned to what actually changes the translation output.
+ [uiLanguage, assistantName],
+ );
+
+ // Same reasoning for the click handler: the parent re-creates it on every
+ // one of ITS renders, which would invalidate the node-list memo each time.
+ const onNodeClickRef = useRef(onNodeClick);
+ onNodeClickRef.current = onNodeClick;
+ const selectNode = useCallback((slug: string) => {
+ if (slug) onNodeClickRef.current(slug);
+ }, []);
+
const { data, isLoading, isError } = useQuery({
queryKey: GRAPH_QUERY_KEY,
queryFn: fetchGraph,
@@ -127,6 +165,13 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
const graphRef = useRef<ForceGraphMethods<RenderNode, RenderEdge> | undefined>(undefined);
const wrapRef = useRef<HTMLDivElement | null>(null);
+ // The canvas draw callbacks read the highlight through a ref so a selection
+ // change does not have to swap the prop functions on the library (which
+ // makes it re-ingest every accessor); the next painted frame just reads the
+ // new value.
+ const highlightRef = useRef(highlightSlug);
+ highlightRef.current = highlightSlug;
+
// Canvas dimensions match the wrap container EXACTLY so the graph's
// (0,0) origin lands at the centre of the visible area.
//
@@ -182,21 +227,6 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
};
}, []);
- // Freeze the simulation after 8s so the canvas stops repainting on idle.
- // The library re-energises it automatically on node drag.
- useEffect(() => {
- if (graphData.nodes.length === 0) return;
- const handle = window.setTimeout(() => {
- const sim = graphRef.current?.d3Force("simulation") as unknown as
- | { alphaTarget?: (a: number) => { restart: () => void } }
- | undefined;
- if (sim && typeof sim.alphaTarget === "function") {
- sim.alphaTarget(0).restart();
- }
- }, 8000);
- return () => window.clearTimeout(handle);
- }, [graphData.nodes.length]);
-
// Auto-fit ONCE, ~2.5 s after the graph data lands. We deliberately
// do NOT keep firing zoomToFit on a schedule — that destroyed the
// user's pan: as soon as they dragged the canvas, a pending fit
@@ -210,15 +240,79 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
// centerAt re-emits zoom events, which would otherwise re-fire the boundary
// clamp in a feedback loop.
const correctingRef = useRef(false);
+ // Wall-clock deadline while OUR OWN camera animation is running. zoomToFit
+ // eases over its whole duration and emits a zoom event per frame; without
+ // this the very first auto-fit marked the view as "the user panned" and
+ // suppressed every later auto-fit (including the one after a resize).
+ const programmaticUntilRef = useRef(0);
+ // Render-loop bookkeeping. `renderingRef` mirrors the library's animation
+ // state; the others decide when parking it is safe.
+ const renderingRef = useRef(true);
+ const engineRunningRef = useRef(true);
+ const pointerInsideRef = useRef(false);
+ const pointerDownRef = useRef(false);
+ const pauseTimerRef = useRef<number | null>(null);
+ // Forces are applied once per data generation, never per tick (see below).
+ const forcesConfiguredRef = useRef(false);
+
+ const renderControls = (): RenderControls | undefined =>
+ graphRef.current as RenderControls | undefined;
+
+ const resumeRender = useCallback((): void => {
+ if (pauseTimerRef.current !== null) {
+ window.clearTimeout(pauseTimerRef.current);
+ pauseTimerRef.current = null;
+ }
+ if (renderingRef.current) return;
+ renderingRef.current = true;
+ renderControls()?.resumeAnimation?.();
+ }, []);
+
+ /**
+ * Park the render loop — but only when nothing on screen still needs
+ * frames. Pausing mid-simulation would freeze a half-settled layout, and
+ * pausing during a camera tween would strand it mid-flight, so both defer
+ * instead of cancelling.
+ */
+ const pauseRenderIfIdle = useCallback(function pauseIfIdle(): void {
+ if (pauseTimerRef.current !== null) {
+ window.clearTimeout(pauseTimerRef.current);
+ pauseTimerRef.current = null;
+ }
+ if (!renderingRef.current) return;
+ if (engineRunningRef.current) return;
+ if (pointerInsideRef.current || pointerDownRef.current) return;
+ const pending = programmaticUntilRef.current - Date.now();
+ if (pending > 0) {
+ pauseTimerRef.current = window.setTimeout(pauseIfIdle, pending + 30);
+ return;
+ }
+ renderingRef.current = false;
+ renderControls()?.pauseAnimation?.();
+ }, []);
+
+ /** Fit the graph into view, flagged as OUR camera move, not the user's. */
+ const fitToView = useCallback(
+ (duration: number, padding: number): void => {
+ const ref = graphRef.current;
+ if (!ref) return;
+ programmaticUntilRef.current = Date.now() + duration + 120;
+ // A tween needs frames; make sure the loop is not parked.
+ resumeRender();
+ ref.zoomToFit(duration, padding);
+ },
+ [resumeRender],
+ );
+
useEffect(() => {
if (graphData.nodes.length === 0) return;
const timer = window.setTimeout(() => {
if (!panInteractedRef.current) {
- graphRef.current?.zoomToFit(400, 120);
+ fitToView(400, 120);
}
}, 2500);
return () => window.clearTimeout(timer);
- }, [graphData.nodes.length]);
+ }, [graphData.nodes.length, fitToView]);
// Re-frame after a resize. Now that the canvas resizes in place (no remount),
// the settled graph keeps its positions but can sit off-centre in the new
@@ -230,47 +324,76 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
if (graphData.nodes.length === 0) return;
const timer = window.setTimeout(() => {
panInteractedRef.current = false;
- graphRef.current?.zoomToFit(400, 80);
+ fitToView(400, 80);
}, 220);
return () => window.clearTimeout(timer);
- }, [winSize.w, winSize.h, graphData.nodes.length]);
+ }, [winSize.w, winSize.h, graphData.nodes.length, fitToView]);
- if (isLoading) {
- return (
- <div
- data-testid="wiki-graph-loading"
- className="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
- {t("wiki_graph.loading")}
- </div>
- );
- }
+ // New data reheats the simulation, so the loop must be running to show it —
+ // and the forces have to be re-applied to the new node/link set.
+ useEffect(() => {
+ if (graphData.nodes.length === 0) return;
+ forcesConfiguredRef.current = false;
+ engineRunningRef.current = true;
+ resumeRender();
+ }, [graphData, resumeRender]);
- if (isError || !data?.ok) {
- return (
- <div
- data-testid="wiki-graph-error"
- className="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
- {t("wiki_graph.load_error")}
- </div>
- );
- }
+ // A selection change only needs a repaint, not a reheat: run a few frames,
+ // then go back to idle.
+ useEffect(() => {
+ if (graphData.nodes.length === 0) return;
+ resumeRender();
+ const timer = window.setTimeout(() => pauseRenderIfIdle(), 400);
+ return () => window.clearTimeout(timer);
+ }, [highlightSlug, graphData.nodes.length, resumeRender, pauseRenderIfIdle]);
- if (graphData.nodes.length === 0) {
- return (
- <div
- data-testid="wiki-graph-empty"
- className="flex h-full items-center justify-center px-8 text-center text-sm text-muted-foreground"
- >
- {t("wiki_graph.empty_prefix")}
- {assistantName}
- {t("wiki_graph.empty_suffix")}
- </div>
- );
- }
+ // Pointer presence drives the idle parking: while the cursor is over the
+ // canvas the user can hover, drag and wheel-zoom, all of which need frames.
+ //
+ // `hasGraph` is a real dependency, not decoration: the first render of this
+ // component is always the loading placeholder, so the wrapper does not exist
+ // yet and an attach-on-mount effect would bind to nothing and never retry.
+ const hasGraph = graphData.nodes.length > 0;
+ useEffect(() => {
+ const el = wrapRef.current;
+ if (!el || !hasGraph) return;
+ const onEnter = () => {
+ pointerInsideRef.current = true;
+ resumeRender();
+ };
+ const onLeave = () => {
+ pointerInsideRef.current = false;
+ pauseRenderIfIdle();
+ };
+ const onDown = () => {
+ pointerDownRef.current = true;
+ resumeRender();
+ };
+ const onUp = () => {
+ pointerDownRef.current = false;
+ };
+ el.addEventListener("pointerenter", onEnter);
+ el.addEventListener("pointerleave", onLeave);
+ el.addEventListener("pointerdown", onDown);
+ window.addEventListener("pointerup", onUp);
+ el.addEventListener("wheel", resumeRender, { passive: true });
+ return () => {
+ el.removeEventListener("pointerenter", onEnter);
+ el.removeEventListener("pointerleave", onLeave);
+ el.removeEventListener("pointerdown", onDown);
+ window.removeEventListener("pointerup", onUp);
+ el.removeEventListener("wheel", resumeRender);
+ };
+ }, [hasGraph, resumeRender, pauseRenderIfIdle]);
- const handleResetView = (): void => {
+ useEffect(
+ () => () => {
+ if (pauseTimerRef.current !== null) window.clearTimeout(pauseTimerRef.current);
+ },
+ [],
+ );
+
+ const handleResetView = useCallback((): void => {
const ref = graphRef.current;
if (!ref) return;
// User explicitly asked for centring → clear the pan-touched flag
@@ -299,13 +422,16 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
n.vx = 0;
n.vy = 0;
});
+ // The reheat needs frames, and it will run the engine again.
+ engineRunningRef.current = true;
+ resumeRender();
const sim = anyRef.d3Force?.("simulation");
if (sim?.alpha && sim?.restart) {
sim.alpha(1).restart();
}
// Give the sim ~1.5 s to spread, then fit.
- window.setTimeout(() => ref.zoomToFit(600, 100), 1500);
- };
+ window.setTimeout(() => fitToView(600, 100), 1500);
+ }, [graphData.nodes, fitToView, resumeRender]);
// Keep the graph from being panned/zoomed entirely out of view.
//
@@ -323,7 +449,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
// throttles once the simulation freezes, so an eased correction stalls
// mid-flight (verified live). A synchronous set holds. The guard absorbs the
// nested zoom event that translateTo re-emits, so this can't loop.
- const clampViewToBounds = (): void => {
+ const clampViewToBounds = useCallback((): void => {
if (correctingRef.current) return;
const ref = graphRef.current;
if (!ref) return;
@@ -339,7 +465,282 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
ref.centerAt(target.x, target.y, 0);
correctingRef.current = false;
}
- };
+ }, [winSize.w, winSize.h]);
+
+ const handleZoom = useCallback((): void => {
+ // Our own fit animation emits zoom events too — those are not a user pan,
+ // and the fit is in-bounds by construction, so leave both flags alone.
+ if (Date.now() < programmaticUntilRef.current) return;
+ // Any user-driven zoom/pan cancels future auto-fits. Without
+ // this, the 2.5 s pending fit would yank the canvas back to
+ // centre right after the user finished dragging.
+ panInteractedRef.current = true;
+ // Live wall — keep the graph reachable WHILE the user drags, so it
+ // sticks at the edge instead of sliding off and vanishing.
+ clampViewToBounds();
+ }, [clampViewToBounds]);
+
+ const handleZoomEnd = useCallback((): void => {
+ // Safety net for any pan/zoom that slipped past the live clamp
+ // (e.g. a wheel-zoom that shifts the centre).
+ if (Date.now() < programmaticUntilRef.current) return;
+ clampViewToBounds();
+ }, [clampViewToBounds]);
+
+ const handleNodeDrag = useCallback((): void => {
+ panInteractedRef.current = true;
+ }, []);
+
+ const handleBackgroundClick = useCallback(
+ (event: MouseEvent): void => {
+ // Double-click on empty canvas re-centres the view.
+ // Cheaper than reaching for the Zentrieren button.
+ if (event.detail >= 2) {
+ panInteractedRef.current = false;
+ handleResetView();
+ }
+ },
+ [handleResetView],
+ );
+
+ // Force-sim tuning for dense graphs (~10+ edges per node), applied ONCE per
+ // data generation.
+ //
+ // This used to run on EVERY engine tick. d3's setters are not free: each
+ // `charge.strength()` re-initialises the force over all nodes and each
+ // `link.distance()` recomputes the distance of every link — so a 60 fps
+ // simulation paid an extra O(nodes + links) pass per frame purely to
+ // re-assign constants that never changed. On a dense vault that is exactly
+ // the stutter users felt while the graph settled and while dragging.
+ const configureForces = useCallback((): void => {
+ engineRunningRef.current = true;
+ if (forcesConfiguredRef.current) return;
+ const ref = graphRef.current;
+ if (!ref) return;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const anyRef = ref as any;
+ // Repulsion: each pair pushes each other away with strength
+ // -180 if closer than 220 px, then falls off. Settled
+ // envelope is ~300x300 px.
+ const chargeForce = anyRef.d3Force?.("charge");
+ if (chargeForce && typeof chargeForce.strength === "function") {
+ chargeForce.strength(-180);
+ if (typeof chargeForce.distanceMax === "function") {
+ chargeForce.distanceMax(220);
+ }
+ }
+ // Links stay short so labels stay close enough to read.
+ const linkForce = anyRef.d3Force?.("link");
+ if (linkForce && typeof linkForce.distance === "function") {
+ linkForce.distance(55);
+ if (typeof linkForce.strength === "function") {
+ linkForce.strength(0.85);
+ }
+ }
+ // Soft centering: every node feels a gentle pull towards (0,0) — this
+ // replaces the hard bounding box. Strength 0.08 keeps the cluster from
+ // drifting infinitely, but is gentle enough that the user can drag a node
+ // far away and it stays where they dropped it. Higher values (0.3-0.5)
+ // caused dragged nodes to spring back to the centre, which felt broken
+ // when the user wanted to lay the graph out manually.
+ const centerForce = anyRef.d3Force?.("center");
+ if (centerForce && typeof centerForce.strength === "function") {
+ centerForce.strength(0.08);
+ }
+ forcesConfiguredRef.current = true;
+ }, []);
+
+ const handleEngineStop = useCallback((): void => {
+ engineRunningRef.current = false;
+ // First chance the simulation finished spreading — fit the bounding box
+ // of the settled nodes into the viewport. 80px padding leaves room for
+ // labels at all four edges. Skipped once the user has taken over the
+ // camera: a reheat (node drag, reset) ends here too, and yanking the view
+ // back every time a drag settles was its own reported bug.
+ if (!panInteractedRef.current) {
+ fitToView(500, 80);
+ }
+ // Nothing left to animate — park the loop until the user comes back.
+ pauseRenderIfIdle();
+ }, [fitToView, pauseRenderIfIdle]);
+
+ const nodeLabel = useCallback(
+ (node: NodeObject<RenderNode>) =>
+ escapeTooltipText(nodeDetails(node as RenderNode, tStable)),
+ [tStable],
+ );
+
+ const linkLabel = useCallback(
+ (link: RenderEdge) => escapeTooltipText(edgeDetails(link as RenderEdge, nodeTitles)),
+ [nodeTitles],
+ );
+
+ const nodeVal = useCallback(
+ (node: NodeObject<RenderNode>) =>
+ nodeSizeScore(node as RenderNode, node.id === highlightRef.current),
+ [],
+ );
+
+ const nodeColor = useCallback(
+ (node: NodeObject<RenderNode>) => node.colour ?? NODE_COLOUR.entity ?? "#8b95a7",
+ [],
+ );
+
+ const nodeCanvasObjectMode = useCallback(() => "after" as const, []);
+
+ const nodeCanvasObject = useCallback(
+ (
+ node: NodeObject<RenderNode>,
+ ctx: CanvasRenderingContext2D,
+ globalScale: number,
+ ): void => {
+ const x = node.x ?? 0;
+ const y = node.y ?? 0;
+ const isActive = node.id === highlightRef.current;
+ // Match the nodeVal calculation so label distance stays consistent with
+ // the dot edge across all node sizes.
+ const radius = nodeSizeScore(node as RenderNode, isActive) * 2;
+ if (isActive) {
+ ctx.save();
+ ctx.beginPath();
+ ctx.arc(x, y, radius + 4, 0, 2 * Math.PI, false);
+ ctx.fillStyle = "rgba(106, 169, 255, 0.18)";
+ ctx.fill();
+ ctx.restore();
+ }
+ // Always-visible labels in screen-space (divide font size by
+ // globalScale so labels look ~10 px regardless of zoom).
+ const label = (node as RenderNode).title ?? (node.id as string | undefined) ?? "";
+ if (label) {
+ ctx.save();
+ const fontSize = 10 / globalScale;
+ ctx.font = `${fontSize}px ui-sans-serif, system-ui, sans-serif`;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "top";
+ ctx.fillStyle = isActive ? "#e6ecf5" : "#a8b0c0";
+ ctx.shadowColor = "rgba(0,0,0,0.85)";
+ ctx.shadowBlur = 3 / globalScale;
+ ctx.fillText(label, x, y + radius + 3 / globalScale);
+ ctx.restore();
+ }
+ },
+ [],
+ );
+
+ const linkColor = useCallback(
+ (link: RenderEdge) =>
+ (link as RenderEdge).broken ? BROKEN_EDGE_COLOUR : "rgba(106, 169, 255, 0.45)",
+ [],
+ );
+
+ const linkLineDash = useCallback(
+ (link: RenderEdge) => ((link as RenderEdge).broken ? [4, 4] : null),
+ [],
+ );
+
+ const linkArrowColor = useCallback(
+ (link: RenderEdge) =>
+ (link as RenderEdge).broken ? BROKEN_EDGE_COLOUR : "rgba(106, 169, 255, 0.75)",
+ [],
+ );
+
+ const handleNodeClick = useCallback(
+ (node: NodeObject<RenderNode>): void => {
+ selectNode((node.id as string | undefined) ?? "");
+ },
+ [selectNode],
+ );
+
+ // Hidden DOM mirror — keeps the canvas-based graph testable without a full
+ // canvas mock. The visible canvas remains the source of truth for users;
+ // this list is purely a behaviour anchor for RTL + a11y readers.
+ //
+ // Memoised because it is the single largest render cost in this component:
+ // one <li> plus a formatted label per node AND per edge. Rebuilding all of
+ // that on every canvas measurement (the ResizeObserver fires a burst per
+ // window drag) is what made resizing the window feel like the graph froze.
+ const nodeListItems = useMemo(
+ () =>
+ graphData.nodes.map((node) => {
+ const isActive = node.id === highlightSlug;
+ const renderRadius = isActive ? node.radius * 1.5 : node.radius;
+ return (
+ <li
+ key={node.id}
+ data-testid="wiki-graph-node"
+ data-node-id={node.id}
+ data-node-kind={node.kind}
+ data-node-radius={renderRadius}
+ data-node-active={isActive ? "true" : "false"}
+ >
+ <button
+ type="button"
+ onClick={() => selectNode(node.id)}
+ aria-label={nodeDetails(node, tStable)}
+ >
+ {node.title}
+ </button>
+ </li>
+ );
+ }),
+ [graphData.nodes, highlightSlug, selectNode, tStable],
+ );
+
+ const edgeListItems = useMemo(
+ () =>
+ graphData.links.map((edge, index) => {
+ const source = endpointId(edge.source);
+ const target = endpointId(edge.target);
+ return (
+ <li
+ key={`${source}:${target}:${index}`}
+ data-testid="wiki-graph-edge"
+ data-edge-source={source}
+ data-edge-target={target}
+ data-edge-broken={edge.broken ? "true" : "false"}
+ >
+ {edgeDetails(edge, nodeTitles)}
+ {edge.broken ? ` · ${tStable("wiki_graph.unresolved")}` : ""}
+ </li>
+ );
+ }),
+ [graphData.links, nodeTitles, tStable],
+ );
+
+ if (isLoading) {
+ return (
+ <div
+ data-testid="wiki-graph-loading"
+ className="flex h-full items-center justify-center text-sm text-muted-foreground"
+ >
+ {t("wiki_graph.loading")}
+ </div>
+ );
+ }
+
+ if (isError || !data?.ok) {
+ return (
+ <div
+ data-testid="wiki-graph-error"
+ className="flex h-full items-center justify-center text-sm text-muted-foreground"
+ >
+ {t("wiki_graph.load_error")}
+ </div>
+ );
+ }
+
+ if (graphData.nodes.length === 0) {
+ return (
+ <div
+ data-testid="wiki-graph-empty"
+ className="flex h-full items-center justify-center px-8 text-center text-sm text-muted-foreground"
+ >
+ {t("wiki_graph.empty_prefix")}
+ {assistantName}
+ {t("wiki_graph.empty_suffix")}
+ </div>
+ );
+ }
return (
<div
@@ -358,50 +759,11 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
>
{t("wiki_graph.center")}
</button>
- {/* Hidden DOM mirror — keeps the canvas-based graph testable without a
- full canvas mock. The visible canvas remains the source of truth for
- users; this list is purely a behaviour anchor for RTL + a11y readers. */}
<ul data-testid="wiki-graph-node-list" className="sr-only">
- {graphData.nodes.map((node) => {
- const isActive = node.id === highlightSlug;
- const renderRadius = isActive ? node.radius * 1.5 : node.radius;
- return (
- <li
- key={node.id}
- data-testid="wiki-graph-node"
- data-node-id={node.id}
- data-node-kind={node.kind}
- data-node-radius={renderRadius}
- data-node-active={isActive ? "true" : "false"}
- >
- <button
- type="button"
- onClick={() => onNodeClick(node.id)}
- aria-label={nodeDetails(node, t)}
- >
- {node.title}
- </button>
- </li>
- );
- })}
+ {nodeListItems}
</ul>
<ul data-testid="wiki-graph-edge-list" className="sr-only">
- {graphData.links.map((edge, index) => {
- const source = endpointId(edge.source);
- const target = endpointId(edge.target);
- return (
- <li
- key={`${source}:${target}:${index}`}
- data-testid="wiki-graph-edge"
- data-edge-source={source}
- data-edge-target={target}
- data-edge-broken={edge.broken ? "true" : "false"}
- >
- {edgeDetails(edge, nodeTitles)}
- {edge.broken ? ` · ${t("wiki_graph.unresolved")}` : ""}
- </li>
- );
- })}
+ {edgeListItems}
</ul>
<ForceGraph2D<RenderNode, RenderEdge>
@@ -414,13 +776,17 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
// DPI rounding, scrollbar flicker) made the network flail and fly off
// screen. The settled layout is preserved now; a debounced zoomToFit
// (see the winSize effect above) just re-frames it after a real resize.
+ //
+ // Every accessor below is a STABLE callback. Passing fresh closures
+ // made the library re-ingest its whole accessor set on each of this
+ // component's renders, for values that never changed.
ref={graphRef}
graphData={graphData}
width={winSize.w}
height={winSize.h}
backgroundColor="rgba(0,0,0,0)"
nodeId="id"
- nodeLabel={(node) => escapeTooltipText(nodeDetails(node as RenderNode, t))}
+ nodeLabel={nodeLabel}
// Pan + zoom + drag — all interactions enabled so the user
// can move freely. NO bounding box — the previous bounding
// box implementation created an "invisible wall" the user
@@ -430,156 +796,35 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
enableNodeDrag={true}
minZoom={0.1}
maxZoom={8}
- onZoom={() => {
- // Any user-driven zoom/pan cancels future auto-fits. Without
- // this, the 2.5 s pending fit would yank the canvas back to
- // centre right after the user finished dragging.
- panInteractedRef.current = true;
- // Live wall — keep the graph reachable WHILE the user drags, so it
- // sticks at the edge instead of sliding off and vanishing.
- clampViewToBounds();
- }}
- onZoomEnd={() => {
- // Safety net for any pan/zoom that slipped past the live clamp
- // (e.g. a wheel-zoom that shifts the centre).
- clampViewToBounds();
- }}
- onNodeDrag={() => {
- panInteractedRef.current = true;
- }}
- onBackgroundClick={(event) => {
- // Double-click on empty canvas re-centres the view.
- // Cheaper than reaching for the Zentrieren button.
- if ((event as MouseEvent).detail >= 2) {
- panInteractedRef.current = false;
- handleResetView();
- }
- }}
+ onZoom={handleZoom}
+ onZoomEnd={handleZoomEnd}
+ onNodeDrag={handleNodeDrag}
+ onBackgroundClick={handleBackgroundClick}
// Compact, Obsidian-like node size.
nodeRelSize={2}
- nodeVal={(node: NodeObject<RenderNode>) => {
- const isActive = node.id === highlightSlug;
- const backlinks = (node as RenderNode).backlinkCount ?? 0;
- // Range 1.0 ... 2.6 → with nodeRelSize=2 that's a node radius
- // of roughly 2.8 px (leaf) ... 4.6 px (hub).
- const sizeScore = 1.0 + Math.min(backlinks, 8) * 0.2;
- return isActive ? sizeScore * 1.5 : sizeScore;
- }}
- nodeColor={(node: NodeObject<RenderNode>) =>
- node.colour ?? NODE_COLOUR.entity ?? "#8b95a7"
- }
- nodeCanvasObjectMode={() => "after"}
- nodeCanvasObject={(node, ctx, globalScale) => {
- const x = node.x ?? 0;
- const y = node.y ?? 0;
- const isActive = node.id === highlightSlug;
- // Match the nodeVal calculation so label distance stays
- // consistent with the dot edge across all node sizes.
- const backlinks = (node as RenderNode).backlinkCount ?? 0;
- const sizeScore = 1.0 + Math.min(backlinks, 8) * 0.2;
- const radius = (isActive ? sizeScore * 1.5 : sizeScore) * 2;
- if (isActive) {
- ctx.save();
- ctx.beginPath();
- ctx.arc(x, y, radius + 4, 0, 2 * Math.PI, false);
- ctx.fillStyle = "rgba(106, 169, 255, 0.18)";
- ctx.fill();
- ctx.restore();
- }
- // Always-visible labels in screen-space (divide font size by
- // globalScale so labels look ~10 px regardless of zoom).
- const label = (node as RenderNode).title ?? (node.id as string | undefined) ?? "";
- if (label) {
- ctx.save();
- const fontSize = 10 / globalScale;
- ctx.font = `${fontSize}px ui-sans-serif, system-ui, sans-serif`;
- ctx.textAlign = "center";
- ctx.textBaseline = "top";
- ctx.fillStyle = isActive ? "#e6ecf5" : "#a8b0c0";
- ctx.shadowColor = "rgba(0,0,0,0.85)";
- ctx.shadowBlur = 3 / globalScale;
- ctx.fillText(label, x, y + radius + 3 / globalScale);
- ctx.restore();
- }
- }}
- linkLabel={(link) =>
- escapeTooltipText(edgeDetails(link as RenderEdge, nodeTitles))
- }
- linkColor={(link) => ((link as RenderEdge).broken ? BROKEN_EDGE_COLOUR : "rgba(106, 169, 255, 0.45)")}
- linkWidth={(link) => ((link as RenderEdge).broken ? 1.0 : 1.0)}
- linkLineDash={(link) => ((link as RenderEdge).broken ? [4, 4] : null)}
+ nodeVal={nodeVal}
+ nodeColor={nodeColor}
+ nodeCanvasObjectMode={nodeCanvasObjectMode}
+ nodeCanvasObject={nodeCanvasObject}
+ linkLabel={linkLabel}
+ linkColor={linkColor}
+ linkWidth={1.0}
+ linkLineDash={linkLineDash}
linkDirectionalArrowLength={4}
linkDirectionalArrowRelPos={0.82}
- linkDirectionalArrowColor={(link) =>
- (link as RenderEdge).broken
- ? BROKEN_EDGE_COLOUR
- : "rgba(106, 169, 255, 0.75)"
- }
- // Force-sim tuning for dense graphs (~10+ edges per node).
- // Calibrated for a vault with ~14 backlinks per node:
- // - charge -500: strong repulsion so dense clusters spread out
- // - linkDistance 110: long edges for label whitespace
- // - velocityDecay 0.5: damp oscillation in dense graphs
- // - alphaDecay 0.02: settle time ~4s
- // - cooldownTicks 400: matches alphaDecay
- // - warmupTicks 60: enough pre-paint settling that the first
+ linkDirectionalArrowColor={linkArrowColor}
+ // - velocityDecay 0.6: damp oscillation in dense graphs
+ // - alphaDecay 0.04: settle time ~4s
+ // - cooldownTicks 200: matches alphaDecay
+ // - warmupTicks 40: enough pre-paint settling that the first
// visible frame is already mostly in shape
cooldownTicks={200}
d3VelocityDecay={0.6}
d3AlphaDecay={0.04}
warmupTicks={40}
- onEngineTick={() => {
- // Force-sim tuning. NO hard bounding box — the user can
- // drag any node anywhere. The forces are calibrated so the
- // graph naturally settles into a compact cluster without a
- // wall.
- const ref = graphRef.current;
- if (!ref) return;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const anyRef = ref as any;
- // Repulsion: each pair pushes each other away with strength
- // -180 if closer than 220 px, then falls off. Settled
- // envelope is ~300x300 px.
- const chargeForce = anyRef.d3Force?.("charge");
- if (chargeForce && typeof chargeForce.strength === "function") {
- chargeForce.strength(-180);
- if (typeof chargeForce.distanceMax === "function") {
- chargeForce.distanceMax(220);
- }
- }
- // Links stay short so labels stay close enough to read.
- const linkForce = anyRef.d3Force?.("link");
- if (linkForce && typeof linkForce.distance === "function") {
- linkForce.distance(55);
- if (typeof linkForce.strength === "function") {
- linkForce.strength(0.85);
- }
- }
- // Very soft centering — strength 0.08 keeps the cluster
- // from drifting infinitely, but is gentle enough that the
- // user can drag a node far away and it stays where they
- // dropped it. Higher values (0.3-0.5) caused dragged nodes
- // to spring back to the centre, which felt broken when the
- // user wanted to lay the graph out manually.
- // Soft centering: every node feels a gentle pull towards
- // (0,0) — this replaces the hard bounding box. Strength 0.5
- // is firm enough that even after dragging, releasing a node
- // brings it back home.
- const centerForce = anyRef.d3Force?.("center");
- if (centerForce && typeof centerForce.strength === "function") {
- centerForce.strength(0.08);
- }
- }}
- onEngineStop={() => {
- // First chance the simulation finished spreading — fit the
- // bounding box of the settled nodes into the viewport. 80px
- // padding leaves room for labels at all four edges.
- graphRef.current?.zoomToFit(500, 80);
- }}
- onNodeClick={(node) => {
- const slug = (node.id as string | undefined) ?? "";
- if (slug) onNodeClick(slug);
- }}
+ onEngineTick={configureForces}
+ onEngineStop={handleEngineStop}
+ onNodeClick={handleNodeClick}
/>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx
index d76fd2b5b6..eb8a237253 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx
@@ -163,6 +163,112 @@ describe("WikiSearch", () => {
expect(items[1].getAttribute("data-slug")).toBe("harald");
});
+ it("renders every server hit, even when the slug does not match the query", async () => {
+ // Regression: the palette let cmdk re-filter the results a second time,
+ // scoring the query against the item value (`hit:<slug>`) instead of the
+ // page text the backend actually matched. A multi-word search therefore
+ // returned hits over the API and showed an empty list to the user.
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ new Response(
+ JSON.stringify({
+ ok: true,
+ query: "birthday party",
+ hits: [
+ {
+ slug: "harald",
+ title: "Harald",
+ path: "entities/harald.md",
+ snippet: "Plans the birthday party every year.",
+ score: 1,
+ },
+ ],
+ }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ ),
+ );
+
+ const client = makeClient();
+ seedTreeCache(client);
+ render(
+ <Wrapper client={client}>
+ <WikiSearch onResultClick={() => {}} />
+ </Wrapper>,
+ );
+ await act(async () => {
+ fireEvent.keyDown(window, { key: "k", ctrlKey: true });
+ });
+ const input = await screen.findByTestId("wiki-search-input");
+ await act(async () => {
+ fireEvent.change(input, { target: { value: "birthday party" } });
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(250);
+ });
+
+ await waitFor(() => {
+ const hits = screen.getAllByTestId("wiki-search-hit");
+ expect(hits).toHaveLength(1);
+ expect(hits[0].getAttribute("data-slug")).toBe("harald");
+ });
+ });
+
+ it("marks every occurrence of the query term in a snippet", async () => {
+ // Regression: highlighting used `pattern.test(part)` with a /g regex,
+ // whose `lastIndex` carried over between calls — so it alternated
+ // true/false and marked plain words while leaving real matches plain.
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ new Response(
+ JSON.stringify({
+ ok: true,
+ query: "pizza",
+ hits: [
+ {
+ slug: "pizza",
+ title: "Pizza",
+ path: "concepts/pizza.md",
+ snippet: "pizza on Friday and pizza on Sunday",
+ score: 1,
+ },
+ ],
+ }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ ),
+ );
+
+ const client = makeClient();
+ seedTreeCache(client);
+ const { container } = render(
+ <Wrapper client={client}>
+ <WikiSearch onResultClick={() => {}} />
+ </Wrapper>,
+ );
+ await act(async () => {
+ fireEvent.keyDown(window, { key: "k", ctrlKey: true });
+ });
+ const input = await screen.findByTestId("wiki-search-input");
+ await act(async () => {
+ fireEvent.change(input, { target: { value: "pizza" } });
+ });
+ await act(async () => {
+ vi.advanceTimersByTime(250);
+ });
+
+ await waitFor(() => {
+ expect(screen.getAllByTestId("wiki-search-hit")).toHaveLength(1);
+ });
+ // cmdk renders the palette in a portal, so query the document body.
+ const marks = Array.from(
+ (container.ownerDocument ?? document).querySelectorAll("mark"),
+ );
+ expect(marks.map((m) => m.textContent)).toEqual(["pizza", "pizza"]);
+ });
+
it("clicking a result calls onResultClick(slug)", async () => {
const client = makeClient();
seedTreeCache(client);
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
index 7aef5d1901..972b8d3dba 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
@@ -14,7 +14,7 @@
// * Enter or click → `onResultClick(slug)` and closes the dialog.
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { Command } from "cmdk";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { colourForKind } from "@/lib/wikiGraph";
import { useT } from "@/i18n";
@@ -96,23 +96,40 @@ function selectRecentPages(tree: TreeResponse | undefined): RecentEntry[] {
}
/**
- * Render a snippet with `<mark>` highlight wrapping for the matched terms.
- * Best-effort: case-insensitive word match, escapes HTML.
+ * Build the highlight matcher for one query. Returns `null` when there is
+ * nothing to highlight. Built once per query in the component rather than
+ * once per snippet per render.
*/
-function highlightSnippet(snippet: string, query: string): JSX.Element {
+function buildHighlightPattern(query: string): RegExp | null {
const trimmed = query.trim();
- if (!trimmed || !snippet) return <>{snippet}</>;
+ if (!trimmed) return null;
const terms = trimmed
.split(/\s+/)
.filter(Boolean)
.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
- if (terms.length === 0) return <>{snippet}</>;
- const pattern = new RegExp(`(${terms.join("|")})`, "ig");
+ if (terms.length === 0) return null;
+ return new RegExp(`(${terms.join("|")})`, "ig");
+}
+
+/**
+ * Render a snippet with `<mark>` highlight wrapping for the matched terms.
+ * Best-effort: case-insensitive word match; React escapes the text for us.
+ */
+function highlightSnippet(snippet: string, pattern: RegExp | null): JSX.Element {
+ if (!pattern || !snippet) return <>{snippet}</>;
+ // `String.split` with exactly ONE capture group puts every captured
+ // delimiter — i.e. every match — at an ODD index. Deriving the highlight
+ // from the index is exact and free.
+ //
+ // It replaces a `pattern.test(part)` check that was quietly wrong: `test()`
+ // on a /g regex advances `lastIndex` and resumes from there on the next
+ // call, so consecutive calls alternated true/false. Real matches were left
+ // unhighlighted and plain words got marked instead.
const parts = snippet.split(pattern);
return (
<>
{parts.map((part, idx) =>
- pattern.test(part) ? (
+ idx % 2 === 1 ? (
<mark key={idx} className="bg-amber-400/30 text-foreground">
{part}
</mark>
@@ -177,13 +194,32 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
queryFn: () => fetchSearch(debouncedQuery),
enabled,
staleTime: 10_000,
+ // Keep the previous query's hits on screen while the next one is in
+ // flight. Without this every keystroke tore the list down to a
+ // "Searching…" placeholder and rebuilt it, which read as typing lag even
+ // though the request itself was fast.
+ placeholderData: keepPreviousData,
});
- const queryClient = useQueryClient();
- const recent = useMemo(() => {
- const tree = queryClient.getQueryData<TreeResponse>(["wiki", "tree"]);
- return selectRecentPages(tree);
- }, [queryClient, open]);
+ const highlightPattern = useMemo(
+ () => buildHighlightPattern(debouncedQuery),
+ [debouncedQuery],
+ );
+
+ // Read the tree through the query cache rather than `getQueryData` so the
+ // palette re-renders when the tree lands. `enabled: false` means this
+ // component never triggers the (expensive) vault walk itself — it only
+ // shows the recents once some other view has fetched the tree.
+ const { data: tree } = useQuery<TreeResponse>({
+ queryKey: ["wiki", "tree"],
+ queryFn: async () => {
+ const res = await fetch("/api/wiki/tree");
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+ },
+ enabled: false,
+ });
+ const recent = useMemo(() => selectRecentPages(tree), [tree]);
const handlePick = useCallback(
(slug: string) => {
@@ -200,6 +236,13 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
open={open}
onOpenChange={setOpen}
label={t("wiki_search.dialog_label")}
+ // The backend already ranked these hits (FTS5/BM25 over full page
+ // bodies). cmdk's built-in filter would score them a SECOND time
+ // against the item `value` — which is `hit:<slug>`, not the page text —
+ // and hide every hit whose slug does not contain the query as a
+ // subsequence. That is why a multi-word search looked broken: the API
+ // returned results and the palette showed an empty list.
+ shouldFilter={false}
data-testid="wiki-search-dialog"
contentClassName="fixed left-1/2 top-[20vh] z-50 w-[min(640px,90vw)] -translate-x-1/2 rounded-xl border border-border bg-background shadow-2xl"
overlayClassName="fixed inset-0 z-40 bg-black/40 backdrop-blur-sm"
@@ -256,7 +299,9 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
))
)}
</Command.Group>
- ) : isFetching ? (
+ ) : isFetching && !data ? (
+ // Only the very first search shows a placeholder. Later keystrokes
+ // keep the previous hits visible until the new ones arrive.
<div className="px-2 py-3 text-muted-foreground" data-testid="wiki-search-loading">
{t("wiki_search.searching")}
</div>
@@ -294,7 +339,7 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function
<span className="text-muted-foreground">— {hit.path}</span>
</span>
<span className="line-clamp-2 text-xs text-muted-foreground">
- {highlightSnippet(hit.snippet, debouncedQuery)}
+ {highlightSnippet(hit.snippet, highlightPattern)}
</span>
</Command.Item>
))}
diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.py
index f5bf614101..0b3218cc5c 100644
--- a/jarvis/ui/web/wiki_routes.py
+++ b/jarvis/ui/web/wiki_routes.py
@@ -33,6 +33,7 @@ from __future__ import annotations
import asyncio
import logging
import os
+import threading
import time
from dataclasses import dataclass
from datetime import UTC
@@ -217,61 +218,170 @@ def _visible_path_sort_key(relative_path: Path) -> tuple[int, str]:
return rank, relative_path.as_posix().casefold()
-def _scan_visible_pages_sync(vault_root: Path) -> list[_VisiblePage]:
- """Parse every user-visible Markdown page below ``vault_root``.
+# Parsed-page cache, keyed by vault root and then by vault-relative path.
+#
+# ``/tree``, ``/graph`` and ``/backlinks/{slug}`` all project the same vault
+# walk, and each one used to READ AND PARSE every Markdown file in the vault
+# on every single request. Opening the Wiki tab fires all three at once and
+# every page click fires two more, so a vault with a few hundred pages spent
+# whole seconds of disk + parse work per navigation — the user-visible "the
+# wiki feels laggy" symptom.
+#
+# An entry is reused only when the file's ``(mtime_ns, size)`` is unchanged,
+# which the walk has to stat for the response payload anyway. So a warm scan
+# of an untouched vault costs one stat per file and zero reads/parses, while
+# any external edit (Obsidian, the curator, a git pull) invalidates exactly
+# the files it touched. Entries not seen in a scan are dropped, which bounds
+# the cache by the vault itself; only the few most recent roots are kept.
+_PARSE_CACHE_LOCK = threading.Lock()
+_PARSE_CACHE: dict[str, dict[str, tuple[int, int, _VisiblePage]]] = {}
+_PARSE_CACHE_MAX_ROOTS = 4
+
+
+def invalidate_visible_page_cache(vault_root: Path | None = None) -> None:
+ """Drop cached page parses for one vault root, or for all of them.
+
+ The ``(mtime_ns, size)`` check already covers every real edit; this exists
+ for tests and for callers that rewrite a vault in place fast enough to
+ land inside a filesystem's timestamp granularity.
+ """
+ with _PARSE_CACHE_LOCK:
+ if vault_root is None:
+ _PARSE_CACHE.clear()
+ else:
+ _PARSE_CACHE.pop(str(vault_root.resolve()), None)
+
+
+def _walk_page_files(root: Path) -> list[tuple[Path, Path, os.stat_result]]:
+ """Yield ``(path, vault-relative path, stat)`` for every visible page.
+
+ Built on ``os.scandir`` rather than ``os.walk``: the directory entry
+ already carries the file type and, on Windows, the full stat block, so the
+ type check and the ``(mtime, size)`` the cache validates against come for
+ free instead of costing a syscall each.
Hidden trees, frozen archive history, and attachment stores are pruned
- before files are opened. Symlinked files that resolve outside the vault
- are also ignored so a crafted vault cannot expose unrelated host files.
+ before files are opened. Symlinked files that resolve outside the vault are
+ ignored so a crafted vault cannot expose unrelated host files — and only a
+ symlink can point outside, so the expensive ``resolve()`` is paid for links
+ alone instead of for every page.
"""
- root = vault_root.resolve()
- paths: list[tuple[Path, Path]] = []
- for current, dirnames, filenames in os.walk(root, followlinks=False):
- dirnames[:] = sorted(
- (
- name
- for name in dirnames
- if not name.startswith(".")
- and name.casefold() not in _EXCLUDED_PAGE_DIRS
- ),
- key=str.casefold,
- )
- current_path = Path(current)
- for filename in sorted(filenames, key=str.casefold):
- if filename.startswith(".") or Path(filename).suffix.casefold() != ".md":
+ out: list[tuple[Path, Path, os.stat_result]] = []
+ stack: list[str] = [str(root)]
+ while stack:
+ current = stack.pop()
+ try:
+ with os.scandir(current) as entries:
+ listing = list(entries)
+ except OSError as exc:
+ log.warning("wiki_route_walk_failed: %s - %s", current, exc)
+ continue
+ for entry in listing:
+ name = entry.name
+ if name.startswith("."):
continue
- path = current_path / filename
try:
- resolved = path.resolve()
- resolved.relative_to(root)
- relative = path.relative_to(root)
+ # A symlinked directory reports False here, which is exactly
+ # the old ``os.walk(followlinks=False)`` behaviour: listed,
+ # never descended into.
+ if entry.is_dir(follow_symlinks=False):
+ if name.casefold() not in _EXCLUDED_PAGE_DIRS:
+ stack.append(entry.path)
+ continue
+ if not name.casefold().endswith(".md"):
+ continue
+ path = Path(entry.path)
+ if entry.is_symlink():
+ resolved = path.resolve()
+ resolved.relative_to(root)
+ if not resolved.is_file():
+ continue
+ elif not entry.is_file(follow_symlinks=False):
+ continue
+ stat = entry.stat()
except (OSError, ValueError):
continue
- paths.append((path, relative))
+ out.append((path, path.relative_to(root), stat))
+ return out
+
+
+def _scan_visible_pages_sync(vault_root: Path) -> list[_VisiblePage]:
+ """Parse every user-visible Markdown page below ``vault_root``.
+
+ Unchanged files are served from the parse cache above; the walk itself is
+ described in :func:`_walk_page_files`.
+ """
+ root = vault_root.resolve()
+ cache_key = str(root)
+ found = _walk_page_files(root)
+ # One total-order sort at the end — the intermediate per-directory sorts
+ # the old walk did could not change this result.
+ found.sort(key=lambda item: _visible_path_sort_key(item[1]))
+
+ with _PARSE_CACHE_LOCK:
+ cached = _PARSE_CACHE.get(cache_key, {})
- paths.sort(key=lambda item: _visible_path_sort_key(item[1]))
+ fresh: dict[str, tuple[int, int, _VisiblePage]] = {}
visible: list[_VisiblePage] = []
- for path, relative in paths:
- try:
- raw = path.read_text(encoding="utf-8", errors="replace")
- stat = path.stat()
- except OSError as exc:
- log.warning("wiki_route_walk_failed: %s - %s", path, exc)
- continue
- visible.append(
- _VisiblePage(
+ for path, relative, stat in found:
+ rel_key = relative.as_posix()
+ signature = (stat.st_mtime_ns, stat.st_size)
+ hit = cached.get(rel_key)
+ if hit is not None and (hit[0], hit[1]) == signature:
+ entry = hit[2]
+ else:
+ try:
+ raw = path.read_text(encoding="utf-8", errors="replace")
+ except OSError as exc:
+ log.warning("wiki_route_walk_failed: %s - %s", path, exc)
+ continue
+ entry = _VisiblePage(
page=parse_markdown(raw, path),
relative_path=relative,
mtime=stat.st_mtime,
size=stat.st_size,
)
- )
+ fresh[rel_key] = (*signature, entry)
+ visible.append(entry)
+
+ with _PARSE_CACHE_LOCK:
+ # Re-insert so this root counts as the most recently used one.
+ _PARSE_CACHE.pop(cache_key, None)
+ _PARSE_CACHE[cache_key] = fresh
+ while len(_PARSE_CACHE) > _PARSE_CACHE_MAX_ROOTS:
+ del _PARSE_CACHE[next(iter(_PARSE_CACHE))]
+
return visible
+# One shared scan per vault root while it is running. Mounting the Wiki tab
+# fires /tree, /graph and /backlinks simultaneously; without this they queued
+# three identical walks against the same thread pool, so the slowest response
+# waited for all three. Now the first request does the work and the others
+# await its result.
+_SCAN_INFLIGHT: dict[str, asyncio.Task[list[_VisiblePage]]] = {}
+
+
+def _release_inflight(key: str, task: asyncio.Task[list[_VisiblePage]]) -> None:
+ """Drop a finished scan task unless a newer one already replaced it."""
+ if _SCAN_INFLIGHT.get(key) is task:
+ _SCAN_INFLIGHT.pop(key, None)
+
+
async def _scan_visible_pages(vault_root: Path) -> list[_VisiblePage]:
- """Build a fresh, non-blocking projection of the active Obsidian vault."""
- return await asyncio.to_thread(_scan_visible_pages_sync, vault_root)
+ """Build a non-blocking projection of the active Obsidian vault."""
+ key = str(vault_root)
+ loop = asyncio.get_running_loop()
+ task = _SCAN_INFLIGHT.get(key)
+ if task is None or task.done() or task.get_loop() is not loop:
+ task = loop.create_task(
+ asyncio.to_thread(_scan_visible_pages_sync, vault_root)
+ )
+ _SCAN_INFLIGHT[key] = task
+ task.add_done_callback(lambda done, k=key: _release_inflight(k, done))
+ # Shielded: a client that disconnects mid-scan must not cancel the walk
+ # the other waiters are riding on.
+ return await asyncio.shield(task)
def _folder_name(relative_path: Path) -> str:
diff --git a/tests/unit/memory/wiki/test_consolidator_off_loop.py b/tests/unit/memory/wiki/test_consolidator_off_loop.py
new file mode 100644
index 0000000000..7978969312
--- /dev/null
+++ b/tests/unit/memory/wiki/test_consolidator_off_loop.py
@@ -0,0 +1,165 @@
+"""The Stage-2 consolidator must never do blocking work on the event loop.
+
+A run is awaited from the app's event loop — the same loop that serves the
+Desktop UI, the WebSocket stream and the voice path. Its blocking steps
+(SQLite reads/writes, FTS5 queries, whole-page vault reads) therefore have to
+land on a worker thread; doing them inline stalls everything else for as long
+as a batch takes, which is exactly the "the whole app freezes while the wiki
+thinks" symptom (AP-9).
+
+These tests assert the thread, not the wall clock, so they stay deterministic.
+"""
+from __future__ import annotations
+
+import threading
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.config import (
+ BrainConfig,
+ BrainProviderConfig,
+ JarvisConfig,
+ MemoryConfig,
+ WikiMemoryConfig,
+)
+from jarvis.memory.wiki.consolidator import Consolidator
+from jarvis.memory.wiki.journal import CandidateFact, CandidateJournal
+
+
+def _config() -> JarvisConfig:
+ return JarvisConfig(
+ brain=BrainConfig(
+ primary="gemini",
+ providers={"gemini": BrainProviderConfig(model="gemini-3.1-pro-preview")},
+ ),
+ memory=MemoryConfig(wiki=WikiMemoryConfig()),
+ )
+
+
+class _ThreadRecordingJournal:
+ """Pass-through journal that records which thread each call ran on."""
+
+ def __init__(self, inner: CandidateJournal) -> None:
+ self._inner = inner
+ self.threads: dict[str, list[int]] = {}
+
+ def _record(self, method: str) -> None:
+ self.threads.setdefault(method, []).append(threading.get_ident())
+
+ def pending(self, *args: Any, **kwargs: Any) -> Any:
+ self._record("pending")
+ return self._inner.pending(*args, **kwargs)
+
+ def mark(self, *args: Any, **kwargs: Any) -> None:
+ self._record("mark")
+ self._inner.mark(*args, **kwargs)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._inner, name)
+
+
+def stack(tmp_path: Path):
+ vault_root = tmp_path / "vault"
+ for sub in ("entities", "concepts", "projects"):
+ (vault_root / sub).mkdir(parents=True)
+ journal = CandidateJournal(tmp_path / "jarvis.db")
+ recording = _ThreadRecordingJournal(journal)
+ consolidator = Consolidator(
+ config=_config(),
+ journal=recording, # type: ignore[arg-type]
+ curator=object(), # never reached in these tests
+ search=None,
+ vault_root=vault_root,
+ )
+ yield consolidator, recording, journal
+ journal.close()
+
+
+async def test_journal_read_runs_off_the_event_loop(stack) -> None:
+ consolidator, recording, _journal = stack
+
+ assert await consolidator.run_once() == "journal-empty"
+
+ assert recording.threads["pending"], "the journal was never read"
+ assert threading.get_ident() not in recording.threads["pending"]
+
+
+async def test_journal_write_runs_off_the_event_loop(stack) -> None:
+ consolidator, recording, journal = stack
+ journal.append(
+ [CandidateFact(fact="Lena moved to Hamburg.", kind="person", subjects=("lena",))],
+ source_label="voice-fact:1",
+ turn_hash="h1",
+ )
+ row_id = journal.pending()[0].id
+
+ await consolidator._mark([row_id], status="skipped")
+
+ assert recording.threads["mark"]
+ assert threading.get_ident() not in recording.threads["mark"]
+ assert journal.pending() == []
+
+
+async def test_neighbour_retrieval_runs_off_the_event_loop(
+ stack, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Retrieval reads up to ``k_nearest * batch`` full pages plus FTS5."""
+ consolidator, _recording, journal = stack
+ journal.append(
+ [CandidateFact(fact="Lena moved to Hamburg.", kind="person", subjects=("lena",))],
+ source_label="voice-fact:1",
+ turn_hash="h1",
+ )
+ rows = journal.pending()
+
+ seen: list[int] = []
+ real = consolidator._collect_neighbours
+
+ def recording_collect(batch): # type: ignore[no-untyped-def]
+ seen.append(threading.get_ident())
+ return real(batch)
+
+ monkeypatch.setattr(consolidator, "_collect_neighbours", recording_collect)
+
+ # No provider needed: an unreachable judge ends the batch right after
+ # retrieval, which is the step under test.
+ async def no_provider(*_args: Any, **_kwargs: Any) -> None:
+ return None
+
+ monkeypatch.setattr(consolidator, "_judge", no_provider)
+
+ outcome = await consolidator._process_rows(rows)
+
+ assert outcome.unavailable is True
+ assert seen and threading.get_ident() not in seen
+
+
+def test_page_reads_are_memoised_within_one_cycle(stack) -> None:
+ """Validation probes the same pages repeatedly; disk must see one read."""
+ consolidator, _recording, _journal = stack
+ target = "entities/lena.md"
+ (consolidator._vault_root / "entities" / "lena.md").write_text(
+ "# Lena\n\nLives in Hamburg.\n", encoding="utf-8"
+ )
+
+ first = consolidator._read_page(target)
+ (consolidator._vault_root / "entities" / "lena.md").write_text(
+ "# Lena\n\nRewritten mid-cycle.\n", encoding="utf-8"
+ )
+ second = consolidator._read_page(target)
+
+ assert first == second, "the memo must serve the same body within a cycle"
+
+ # A new judge/execute cycle always starts from disk again, so a body this
+ # run has written can never be served stale.
+ consolidator._page_body_cache.clear()
+ assert "Rewritten mid-cycle." in (consolidator._read_page(target) or "")
+
+
+def test_missing_page_is_memoised_as_absent(stack) -> None:
+ consolidator, _recording, _journal = stack
+ assert consolidator._read_page("entities/nobody.md") is None
+ assert consolidator._page_body_cache["entities/nobody.md"] is None
diff --git a/tests/unit/ui/web/test_wiki_scan_cache.py b/tests/unit/ui/web/test_wiki_scan_cache.py
new file mode 100644
index 0000000000..01432f143d
--- /dev/null
+++ b/tests/unit/ui/web/test_wiki_scan_cache.py
@@ -0,0 +1,251 @@
+"""Guards for the vault-scan hot path behind /tree, /graph and /backlinks.
+
+All three routes project the SAME walk of the Obsidian vault, and every one
+of them used to re-read and re-parse every Markdown file on every request.
+Opening the Wiki tab fires all three at once and each page click fires more,
+so the walk is what the user actually feels as "the wiki is laggy".
+
+Two properties are pinned here:
+
+* an unchanged file is never read or parsed twice, while a changed one is
+ picked up immediately (correctness of the cache, not just its speed), and
+* concurrent requests share ONE walk instead of queueing identical ones.
+
+Real files in ``tmp_path`` — the filesystem is never mocked.
+"""
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from jarvis.ui.web import wiki_routes
+from jarvis.ui.web.wiki_routes import (
+ _scan_visible_pages,
+ _scan_visible_pages_sync,
+ invalidate_visible_page_cache,
+)
+
+
[email protected](autouse=True)
+def _clear_scan_cache() -> None:
+ """The parse cache is process-wide; keep it from leaking across tests."""
+ invalidate_visible_page_cache()
+ yield
+ invalidate_visible_page_cache()
+
+
+def _write_page(vault_root: Path, subdir: str, slug: str, body: str) -> Path:
+ directory = vault_root / subdir
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / f"{slug}.md"
+ path.write_text(
+ f"---\ntype: entity\nslug: {slug}\n---\n\n# {slug.title()}\n\n{body}\n",
+ encoding="utf-8",
+ )
+ return path
+
+
+def vault(tmp_path: Path) -> Path:
+ root = tmp_path / "vault"
+ _write_page(root, "entities", "lena", "Lives in Hamburg.")
+ _write_page(root, "concepts", "golf", "A sport the user practices.")
+ return root
+
+
+class _ParseCounter:
+ """Count how often the tolerant Markdown parser actually runs."""
+
+ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ self.calls: list[str] = []
+ real = wiki_routes.parse_markdown
+
+ def counting(raw: str, path: Path): # type: ignore[no-untyped-def]
+ self.calls.append(Path(path).name)
+ return real(raw, path)
+
+ monkeypatch.setattr(wiki_routes, "parse_markdown", counting)
+
+
+def test_unchanged_vault_is_not_reparsed(
+ vault: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ counter = _ParseCounter(monkeypatch)
+
+ first = _scan_visible_pages_sync(vault)
+ assert len(first) == 2
+ assert sorted(counter.calls) == ["golf.md", "lena.md"]
+
+ counter.calls.clear()
+ second = _scan_visible_pages_sync(vault)
+
+ # Same projection, zero re-parses: a warm scan costs one stat per file.
+ assert [p.relative_path for p in second] == [p.relative_path for p in first]
+ assert counter.calls == []
+
+
+def test_edited_page_is_reparsed_and_others_are_not(
+ vault: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _scan_visible_pages_sync(vault)
+ counter = _ParseCounter(monkeypatch)
+
+ edited = vault / "entities" / "lena.md"
+ edited.write_text(
+ "---\ntype: entity\nslug: lena\n---\n\n# Lena\n\nMoved to Berlin.\n",
+ encoding="utf-8",
+ )
+ # Make the change unmistakable even on a coarse-grained clock.
+ future = time.time() + 5
+ os.utime(edited, (future, future))
+
+ pages = _scan_visible_pages_sync(vault)
+
+ assert counter.calls == ["lena.md"]
+ lena = next(p for p in pages if p.relative_path.name == "lena.md")
+ assert "Moved to Berlin." in lena.page.body
+
+
+def test_new_and_deleted_pages_are_picked_up(
+ vault: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _scan_visible_pages_sync(vault)
+ counter = _ParseCounter(monkeypatch)
+
+ _write_page(vault, "projects", "cabin", "Weekend build.")
+ (vault / "concepts" / "golf.md").unlink()
+
+ names = {p.relative_path.name for p in _scan_visible_pages_sync(vault)}
+
+ assert names == {"lena.md", "cabin.md"}
+ assert counter.calls == ["cabin.md"]
+
+
+def test_explicit_invalidation_forces_a_full_reparse(
+ vault: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _scan_visible_pages_sync(vault)
+ counter = _ParseCounter(monkeypatch)
+
+ invalidate_visible_page_cache(vault)
+ _scan_visible_pages_sync(vault)
+
+ assert sorted(counter.calls) == ["golf.md", "lena.md"]
+
+
+def test_cache_does_not_grow_without_bound(tmp_path: Path) -> None:
+ """Only the few most recent vault roots stay resident."""
+ roots = []
+ for index in range(wiki_routes._PARSE_CACHE_MAX_ROOTS + 3):
+ root = tmp_path / f"vault{index}"
+ _write_page(root, "entities", f"page{index}", "body")
+ roots.append(root)
+ _scan_visible_pages_sync(root)
+
+ assert len(wiki_routes._PARSE_CACHE) == wiki_routes._PARSE_CACHE_MAX_ROOTS
+
+
+def _symlinks_supported(tmp_path: Path) -> bool:
+ """Windows needs developer mode or elevation to create symlinks."""
+ probe = tmp_path / "probe"
+ target = tmp_path / "probe-target"
+ target.write_text("x", encoding="utf-8")
+ try:
+ os.symlink(target, probe)
+ except (OSError, NotImplementedError, AttributeError):
+ return False
+ probe.unlink()
+ return True
+
+
+def test_symlink_escaping_the_vault_is_not_exposed(vault: Path, tmp_path: Path) -> None:
+ """The walk resolves links only — but it must still resolve them."""
+ if not _symlinks_supported(tmp_path):
+ pytest.skip("symlink creation unavailable on this host")
+
+ outside = tmp_path / "outside" / "secret.md"
+ outside.parent.mkdir(parents=True, exist_ok=True)
+ outside.write_text("# Secret\n\nNot part of the vault.\n", encoding="utf-8")
+ os.symlink(outside, vault / "entities" / "secret.md")
+
+ names = {p.relative_path.name for p in _scan_visible_pages_sync(vault)}
+
+ assert "secret.md" not in names
+ assert names == {"lena.md", "golf.md"}
+
+
+def test_symlink_inside_the_vault_is_still_listed(vault: Path, tmp_path: Path) -> None:
+ if not _symlinks_supported(tmp_path):
+ pytest.skip("symlink creation unavailable on this host")
+
+ os.symlink(vault / "entities" / "lena.md", vault / "concepts" / "lena-alias.md")
+
+ names = {p.relative_path.name for p in _scan_visible_pages_sync(vault)}
+
+ assert names == {"lena.md", "golf.md", "lena-alias.md"}
+
+
+def test_symlinked_directory_is_not_descended(vault: Path, tmp_path: Path) -> None:
+ """Matches the old ``os.walk(followlinks=False)`` contract."""
+ if not _symlinks_supported(tmp_path):
+ pytest.skip("symlink creation unavailable on this host")
+
+ outside_dir = tmp_path / "elsewhere"
+ outside_dir.mkdir()
+ (outside_dir / "leaked.md").write_text("# Leaked\n", encoding="utf-8")
+ os.symlink(outside_dir, vault / "linked", target_is_directory=True)
+
+ names = {p.relative_path.name for p in _scan_visible_pages_sync(vault)}
+
+ assert "leaked.md" not in names
+
+
+async def test_concurrent_requests_share_one_walk(
+ vault: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Mounting the Wiki tab fires /tree, /graph and /backlinks together."""
+ started: list[Path] = []
+ real = wiki_routes._scan_visible_pages_sync
+
+ def slow(root: Path): # type: ignore[no-untyped-def]
+ started.append(root)
+ time.sleep(0.05)
+ return real(root)
+
+ monkeypatch.setattr(wiki_routes, "_scan_visible_pages_sync", slow)
+
+ results = await asyncio.gather(
+ _scan_visible_pages(vault),
+ _scan_visible_pages(vault),
+ _scan_visible_pages(vault),
+ )
+
+ assert len(started) == 1
+ assert all(len(pages) == 2 for pages in results)
+ # All three requests got the same projection object graph.
+ assert results[0] is results[1] is results[2]
+
+
+async def test_a_cancelled_request_does_not_abort_the_shared_walk(
+ vault: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A client that disconnects mid-scan must not take the others down."""
+ real = wiki_routes._scan_visible_pages_sync
+
+ def slow(root: Path): # type: ignore[no-untyped-def]
+ time.sleep(0.1)
+ return real(root)
+
+ monkeypatch.setattr(wiki_routes, "_scan_visible_pages_sync", slow)
+
+ leaving = asyncio.ensure_future(_scan_visible_pages(vault))
+ staying = asyncio.ensure_future(_scan_visible_pages(vault))
+ await asyncio.sleep(0)
+ leaving.cancel()
+
+ pages = await staying
+ assert len(pages) == 2