Skip to content

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

feat(ultrawiki): add the Explore tab - topics, moments and their graph

Ruben Lütke67919c438912
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.test.tsx
new file mode 100644
index 0000000000..a39eea0f02
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.test.tsx
@@ -0,0 +1,169 @@
+/**
+ * EntityGraph tests — the map of which topics appear together.
+ *
+ * The canvas library is stubbed (jsdom has no <canvas>), so what is pinned
+ * here is the contract around it: the mention floor reaches the backend, the
+ * encoding hands the renderer sized and tinted nodes, a click reports the
+ * topic, and a floor that hides everything says so instead of showing an
+ * empty rectangle the user would read as "nothing is known".
+ */
+import { afterEach, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { EntityGraph } from "@/components/ultrawiki/EntityGraph";
+
+// jsdom ships no ResizeObserver; the graph observes its container to size the
+// canvas. Same stand-in the AgenticGrid tests use.
+class ResizeObserverPolyfill {
+ constructor(_callback: ResizeObserverCallback) {}
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+}
+if (typeof globalThis.ResizeObserver === "undefined") {
+ globalThis.ResizeObserver =
+ ResizeObserverPolyfill as unknown as typeof ResizeObserver;
+}
+
+const { forceGraphProps } = vi.hoisted(() => ({
+ forceGraphProps: [] as Array<Record<string, unknown>>,
+}));
+
+vi.mock("react-force-graph-2d", async () => {
+ const { forwardRef } = await import("react");
+ return {
+ default: forwardRef(function ForceGraphMock(
+ props: Record<string, unknown>,
+ _ref,
+ ) {
+ forceGraphProps.push(props);
+ return null;
+ }),
+ };
+});
+
+const PAYLOAD = {
+ ok: true,
+ nodes: [
+ {
+ key: "bora bora",
+ label: "Bora Bora",
+ mentions: 20,
+ first_seen: "2026-06-30T10:00:00Z",
+ last_seen: "2026-07-08T10:00:00Z",
+ },
+ {
+ key: "tahiti",
+ label: "Tahiti",
+ mentions: 4,
+ first_seen: "2026-07-01T10:00:00Z",
+ last_seen: "2026-07-13T10:00:00Z",
+ },
+ ],
+ edges: [{ source: "bora bora", target: "tahiti", weight: 10 }],
+ min_mentions: 2,
+ total_entities: 947,
+ corpus: { sources: 1, items: 40, distilled: 30 },
+ reason: "ok",
+};
+
+function installFetch(body: unknown = PAYLOAD) {
+ const fetchMock = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => body,
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function renderGraph(props: Partial<Parameters<typeof EntityGraph>[0]> = {}) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },
+ });
+ return render(
+ <QueryClientProvider client={client}>
+ <EntityGraph
+ minMentions={2}
+ onMinMentionsChange={() => {}}
+ selectedKey={null}
+ onSelect={() => {}}
+ {...props}
+ />
+ </QueryClientProvider>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ forceGraphProps.length = 0;
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+it("asks the backend for the current mention floor", async () => {
+ const fetchMock = installFetch();
+ renderGraph({ minMentions: 3 });
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalled());
+ expect(fetchMock.mock.calls.map(String).join("|")).toContain("min_mentions=3");
+});
+
+it("sizes nodes by how often a topic comes up", async () => {
+ installFetch();
+ renderGraph();
+
+ await waitFor(() => expect(forceGraphProps.length).toBeGreaterThan(0));
+ const data = forceGraphProps.at(-1)?.graphData as {
+ nodes: Array<{ id: string; radius: number; colour: string }>;
+ };
+ const bora = data.nodes.find((node) => node.id === "bora bora");
+ const tahiti = data.nodes.find((node) => node.id === "tahiti");
+ expect(bora!.radius).toBeGreaterThan(tahiti!.radius);
+ expect(bora!.colour).toMatch(/^#[0-9a-f]{6}$/);
+});
+
+it("reports the topic behind a clicked node", async () => {
+ installFetch();
+ const onSelect = vi.fn();
+ renderGraph({ onSelect });
+
+ await waitFor(() => expect(forceGraphProps.length).toBeGreaterThan(0));
+ const handler = forceGraphProps.at(-1)?.onNodeClick as (node: unknown) => void;
+ handler({ id: "tahiti" });
+
+ expect(onSelect).toHaveBeenCalledWith("tahiti");
+});
+
+it("moves the floor when the slider moves", async () => {
+ installFetch();
+ const onMinMentionsChange = vi.fn();
+ renderGraph({ onMinMentionsChange });
+
+ // A range control emits `input` while it is dragged, which is the event
+ // React's onChange is bound to; `change` alone only fires on release.
+ fireEvent.input(await screen.findByTestId("explore-graph-floor"), {
+ target: { value: "0" },
+ });
+
+ expect(onMinMentionsChange).toHaveBeenCalledWith(1);
+});
+
+it("says the floor is hiding everything instead of drawing a blank box", async () => {
+ installFetch({ ...PAYLOAD, nodes: [], edges: [] });
+ renderGraph();
+
+ expect(await screen.findByTestId("explore-graph-empty")).toBeTruthy();
+});
+
+it("shows how much of the corpus is on screen", async () => {
+ installFetch();
+ renderGraph();
+
+ const caption = await screen.findByTestId("explore-graph-shown");
+ // The caption exists before the data does, so wait for the loaded numbers
+ // rather than for the element.
+ await waitFor(() => expect(caption.textContent).toContain("947"));
+ expect(caption.textContent).toContain("2");
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.tsx
new file mode 100644
index 0000000000..5ce09e4d41
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.tsx
@@ -0,0 +1,213 @@
+/**
+ * The map of which topics appear together.
+ *
+ * A node is a topic, an edge means "these two came up in the same moment",
+ * and the edge is thicker the more often that happened. Node size is mention
+ * count, node brightness is recency — both computed in lib/entityGraph.ts so
+ * the list and the map speak the same visual language.
+ *
+ * The mention floor is the whole reason this is readable. On a real corpus
+ * 977 topics collapse to 313 at two mentions and 77 at five; drawing every
+ * one-off at once is a hairball, not a map. The slider makes the trade
+ * explicit and reversible instead of hiding data silently.
+ */
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import ForceGraph2D from "react-force-graph-2d";
+import type {
+ ForceGraphMethods,
+ LinkObject,
+ NodeObject,
+} from "react-force-graph-2d";
+
+import { useT } from "@/i18n";
+import { sizeChanged } from "@/lib/wikiGraph";
+import { corpusSpan, nodeRadius, recencyTint } from "@/lib/entityGraph";
+import { fetchExploreGraph } from "@/lib/ultrawikiExploreApi";
+
+export interface EntityGraphProps {
+ minMentions: number;
+ onMinMentionsChange: (value: number) => void;
+ selectedKey: string | null;
+ onSelect: (key: string) => void;
+}
+
+interface RenderNode {
+ id: string;
+ label: string;
+ mentions: number;
+ radius: number;
+ colour: string;
+ x?: number;
+ y?: number;
+}
+
+interface RenderEdge {
+ source: string;
+ target: string;
+ weight: number;
+}
+
+/** Floors the slider offers — 1 is always reachable, so nothing is hidden for good. */
+const FLOORS = [1, 2, 3, 5, 8] as const;
+
+export function EntityGraph({
+ minMentions,
+ onMinMentionsChange,
+ selectedKey,
+ onSelect,
+}: EntityGraphProps): JSX.Element {
+ const t = useT();
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const graphRef = useRef<
+ | ForceGraphMethods<NodeObject<RenderNode>, LinkObject<RenderNode, RenderEdge>>
+ | undefined
+ >(undefined);
+ const [size, setSize] = useState({ w: 0, h: 0 });
+
+ const query = useQuery({
+ queryKey: ["ultrawiki", "explore", "graph", minMentions],
+ queryFn: () => fetchExploreGraph(minMentions),
+ staleTime: 30_000,
+ });
+
+ useEffect(() => {
+ const element = containerRef.current;
+ if (!element) return;
+ const observer = new ResizeObserver((entries) => {
+ const box = entries[0]?.contentRect;
+ if (!box) return;
+ const next = { w: Math.round(box.width), h: Math.round(box.height) };
+ // Sub-pixel churn would restart the force simulation and make the
+ // network flail; the shared threshold helper absorbs it.
+ setSize((prev) => (sizeChanged(prev, next) ? next : prev));
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
+ const graphData = useMemo(() => {
+ const nodes = query.data?.nodes ?? [];
+ const span = corpusSpan(nodes);
+ const max = nodes.reduce((peak, node) => Math.max(peak, node.mentions), 1);
+ return {
+ nodes: nodes.map<RenderNode>((node) => ({
+ id: node.key,
+ label: node.label,
+ mentions: node.mentions,
+ radius: nodeRadius(node.mentions, max),
+ colour: recencyTint(node.last_seen, span),
+ })),
+ links: (query.data?.edges ?? []).map((edge) => ({
+ source: edge.source,
+ target: edge.target,
+ weight: edge.weight,
+ })),
+ };
+ }, [query.data]);
+
+ const shown = graphData.nodes.length;
+ const total = query.data?.total_entities ?? 0;
+
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex items-center justify-between gap-3 border-b border-border px-4 py-1.5">
+ <p className="text-[11px] uppercase tracking-wide text-muted-foreground">
+ {t("ultrawiki.explore.graph_title")}
+ </p>
+ <div className="flex items-center gap-2">
+ <span
+ data-testid="explore-graph-shown"
+ className="text-[11px] tabular-nums text-muted-foreground"
+ >
+ {t("ultrawiki.explore.graph_shown")
+ .replace("{0}", String(shown))
+ .replace("{1}", String(total))}
+ </span>
+ <input
+ type="range"
+ data-testid="explore-graph-floor"
+ min={0}
+ max={FLOORS.length - 1}
+ step={1}
+ value={Math.max(FLOORS.indexOf(minMentions as (typeof FLOORS)[number]), 0)}
+ onChange={(event) =>
+ onMinMentionsChange(FLOORS[Number(event.target.value)] ?? 1)
+ }
+ aria-label={t("ultrawiki.explore.min_mentions").replace(
+ "{0}",
+ String(minMentions),
+ )}
+ title={t("ultrawiki.explore.min_mentions").replace(
+ "{0}",
+ String(minMentions),
+ )}
+ className="h-1 w-24 cursor-pointer appearance-none rounded-full bg-muted accent-primary"
+ />
+ </div>
+ </div>
+
+ <div ref={containerRef} className="relative min-h-0 flex-1">
+ {shown === 0 ? (
+ <p
+ data-testid="explore-graph-empty"
+ className="flex h-full items-center justify-center px-6 text-center text-xs text-muted-foreground"
+ >
+ {t("ultrawiki.explore.graph_empty")}
+ </p>
+ ) : (
+ <ForceGraph2D<RenderNode, RenderEdge>
+ ref={graphRef}
+ width={size.w || undefined}
+ height={size.h || undefined}
+ graphData={graphData}
+ backgroundColor="transparent"
+ cooldownTicks={80}
+ nodeRelSize={1}
+ nodeVal={(node: NodeObject<RenderNode>) => node.radius}
+ nodeLabel={(node: NodeObject<RenderNode>) => node.label}
+ linkColor={() => "rgba(125, 184, 255, 0.16)"}
+ linkWidth={(link) =>
+ Math.min(0.4 + (link.weight ?? 1) * 0.15, 2.4)
+ }
+ onNodeClick={(node) => {
+ if (node?.id !== undefined) onSelect(String(node.id));
+ }}
+ nodeCanvasObjectMode={() => "after"}
+ nodeCanvasObject={(node, ctx, scale) => {
+ if (node.x === undefined || node.y === undefined) return;
+ const selected = node.id === selectedKey;
+ ctx.beginPath();
+ ctx.arc(node.x, node.y, node.radius, 0, 2 * Math.PI);
+ ctx.fillStyle = node.colour;
+ ctx.fill();
+ if (selected) {
+ ctx.lineWidth = 1.5 / scale;
+ ctx.strokeStyle = "#ffffff";
+ ctx.stroke();
+ }
+ // Labels only once the user has zoomed in, and only for the
+ // nodes that carry weight — a wall of overlapping text is how
+ // graph views become unreadable.
+ if (scale > 1.4 || selected || node.radius > 8) {
+ ctx.font = `${Math.max(9 / scale, 2.4)}px ui-sans-serif, system-ui, sans-serif`;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "top";
+ ctx.fillStyle = selected
+ ? "rgba(255,255,255,0.95)"
+ : "rgba(255,255,255,0.55)";
+ ctx.fillText(node.label, node.x, node.y + node.radius + 1.5);
+ }
+ }}
+ />
+ )}
+ </div>
+
+ <p className="border-t border-border px-4 py-1 text-[10px] text-muted-foreground">
+ {t("ultrawiki.explore.graph_hint")}
+ </p>
+ </div>
+ );
+}
+
+export default EntityGraph;
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.test.tsx
new file mode 100644
index 0000000000..c3c1ecc6f8
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.test.tsx
@@ -0,0 +1,332 @@
+/**
+ * ExplorePanel tests — the readable view over the knowledge base.
+ *
+ * The load-bearing case is emptiness, not the happy path: a knowledge base
+ * that shows nothing has four different causes, the user cannot tell them
+ * apart, and one of them once went undiagnosed for days behind a blank
+ * screen. Each cause must produce its OWN message and its own way out.
+ *
+ * The graph is canvas-based, so it is stubbed here; its own encoding is
+ * covered by lib/entityGraph.test.ts.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { ExplorePanel } from "@/components/ultrawiki/ExplorePanel";
+
+vi.mock("@/components/ultrawiki/EntityGraph", () => ({
+ EntityGraph: () => <div data-testid="entity-graph-stub" />,
+}));
+
+const ENTITIES = [
+ {
+ key: "bora bora",
+ label: "Bora Bora",
+ mentions: 20,
+ first_seen: "2026-06-30T10:00:00Z",
+ last_seen: "2026-07-08T10:00:00Z",
+ neighbors: [{ key: "tahiti", label: "Tahiti", shared: 10 }],
+ },
+ {
+ key: "tahiti",
+ label: "Tahiti",
+ mentions: 18,
+ first_seen: "2026-07-01T10:00:00Z",
+ last_seen: "2026-07-13T10:00:00Z",
+ neighbors: [{ key: "bora bora", label: "Bora Bora", shared: 10 }],
+ },
+ {
+ key: "berlin",
+ label: "Berlin",
+ mentions: 3,
+ first_seen: "2026-06-24T10:00:00Z",
+ last_seen: "2026-07-25T10:00:00Z",
+ neighbors: [],
+ },
+];
+
+const MOMENTS = [
+ {
+ document_id: 1,
+ item_id: 11,
+ title: "How do I get to Bora Bora?",
+ summary: "Routes via Tahiti.",
+ resolution: "Fly via Tahiti.",
+ entity_keys: ["bora bora", "tahiti"],
+ timestamp_utc: "2026-07-08T10:00:00Z",
+ month: "2026-07",
+ source_id: "src1",
+ source_label: "Jarvis Conversations",
+ permalink: "app://a",
+ },
+];
+
+const FULL_CORPUS = { sources: 1, items: 40, distilled: 30 };
+
+function makeClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },
+ });
+}
+
+function renderPanel() {
+ return render(
+ <QueryClientProvider client={makeClient()}>
+ <ExplorePanel onOpenSources={() => {}} onOpenSettings={() => {}} />
+ </QueryClientProvider>,
+ );
+}
+
+function installRoutes(overrides: Record<string, unknown> = {}) {
+ const responses: Record<string, unknown> = {
+ "/api/ultrawiki/explore/entities": {
+ ok: true,
+ entities: ENTITIES,
+ total: ENTITIES.length,
+ corpus: FULL_CORPUS,
+ reason: "ok",
+ },
+ "/api/ultrawiki/explore/moments": {
+ ok: true,
+ moments: MOMENTS,
+ total: MOMENTS.length,
+ corpus: FULL_CORPUS,
+ reason: "ok",
+ },
+ ...overrides,
+ };
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ const key = Object.keys(responses)
+ .sort((a, b) => b.length - a.length)
+ .find((prefix) => url.startsWith(prefix));
+ if (!key) throw new Error(`unrouted fetch: ${url}`);
+ const body = responses[key];
+ if (body instanceof Error) throw body;
+ return {
+ ok: true,
+ status: 200,
+ json: async () => body,
+ } as unknown as Response;
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("browsing", () => {
+ it("lists topics with the most-mentioned first", async () => {
+ installRoutes();
+ renderPanel();
+
+ const rows = await screen.findAllByTestId(/^explore-entity-/);
+ expect(rows.map((row) => row.getAttribute("data-entity-key"))).toEqual([
+ "bora bora",
+ "tahiti",
+ "berlin",
+ ]);
+ });
+
+ it("shows how often a topic came up", async () => {
+ installRoutes();
+ renderPanel();
+
+ const row = await screen.findByTestId("explore-entity-bora bora");
+ expect(row.textContent).toContain("Bora Bora");
+ expect(row.textContent).toContain("20");
+ });
+
+ it("gives every topic a time bar positioned inside the corpus span", async () => {
+ installRoutes();
+ renderPanel();
+
+ const bar = await screen.findByTestId("explore-span-berlin");
+ // Berlin runs the whole corpus; Bora Bora is a short late burst.
+ const berlinWidth = Number(bar.getAttribute("data-width"));
+ const boraBar = screen.getByTestId("explore-span-bora bora");
+ expect(berlinWidth).toBeGreaterThan(Number(boraBar.getAttribute("data-width")));
+ });
+
+ it("filters the list as the user types, without refetching", async () => {
+ const fetchMock = installRoutes();
+ renderPanel();
+ await screen.findByTestId("explore-entity-berlin");
+ const callsBefore = fetchMock.mock.calls.length;
+
+ fireEvent.change(screen.getByTestId("explore-search"), {
+ target: { value: "bor" },
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByTestId("explore-entity-berlin")).toBeNull();
+ });
+ expect(screen.getByTestId("explore-entity-bora bora")).toBeTruthy();
+ expect(fetchMock.mock.calls.length).toBe(callsBefore);
+ });
+
+ it("says so when a search matches nothing", async () => {
+ installRoutes();
+ renderPanel();
+ await screen.findByTestId("explore-entity-berlin");
+
+ fireEvent.change(screen.getByTestId("explore-search"), {
+ target: { value: "zzz" },
+ });
+
+ expect(await screen.findByTestId("explore-no-search-hits")).toBeTruthy();
+ });
+});
+
+describe("topic detail", () => {
+ it("opens the moments of a topic when it is clicked", async () => {
+ installRoutes({
+ "/api/ultrawiki/explore/entities/tahiti": {
+ ok: true,
+ entity: ENTITIES[1],
+ moments: MOMENTS,
+ total: 1,
+ corpus: FULL_CORPUS,
+ },
+ });
+ renderPanel();
+
+ fireEvent.click(await screen.findByTestId("explore-entity-tahiti"));
+
+ expect(await screen.findByTestId("explore-detail")).toBeTruthy();
+ expect(screen.getByTestId("explore-detail").textContent).toContain(
+ "How do I get to Bora Bora?",
+ );
+ });
+
+ it("offers the neighbours as a way to keep exploring", async () => {
+ installRoutes({
+ "/api/ultrawiki/explore/entities/tahiti": {
+ ok: true,
+ entity: ENTITIES[1],
+ moments: MOMENTS,
+ total: 1,
+ corpus: FULL_CORPUS,
+ },
+ });
+ renderPanel();
+
+ fireEvent.click(await screen.findByTestId("explore-entity-tahiti"));
+
+ const neighbour = await screen.findByTestId("explore-neighbor-bora bora");
+ expect(neighbour.textContent).toContain("Bora Bora");
+ });
+
+ it("links every moment back to its evidence", async () => {
+ installRoutes();
+ renderPanel();
+
+ const link = await screen.findByTestId("explore-moment-link-1");
+ expect(link.getAttribute("href")).toBe("app://a");
+ });
+});
+
+describe("the four honest empty states", () => {
+ const empty = (reason: string, corpus: Record<string, number>) => ({
+ "/api/ultrawiki/explore/entities": {
+ ok: true,
+ entities: [],
+ total: 0,
+ corpus,
+ reason,
+ },
+ "/api/ultrawiki/explore/moments": {
+ ok: true,
+ moments: [],
+ total: 0,
+ corpus,
+ reason,
+ },
+ });
+
+ it("names a missing source and offers the way there", async () => {
+ installRoutes(empty("no_sources", { sources: 0, items: 0, distilled: 0 }));
+ const onOpenSources = vi.fn();
+ render(
+ <QueryClientProvider client={makeClient()}>
+ <ExplorePanel onOpenSources={onOpenSources} onOpenSettings={() => {}} />
+ </QueryClientProvider>,
+ );
+
+ const banner = await screen.findByTestId("explore-empty");
+ expect(banner.getAttribute("data-reason")).toBe("no_sources");
+ fireEvent.click(screen.getByTestId("explore-empty-action"));
+ expect(onOpenSources).toHaveBeenCalled();
+ });
+
+ it("distinguishes a source that never imported", async () => {
+ installRoutes(
+ empty("nothing_imported", { sources: 1, items: 0, distilled: 0 }),
+ );
+ renderPanel();
+
+ const banner = await screen.findByTestId("explore-empty");
+ expect(banner.getAttribute("data-reason")).toBe("nothing_imported");
+ });
+
+ it("sends an undistilled corpus to the settings, not to the sources", async () => {
+ installRoutes(
+ empty("nothing_distilled", { sources: 1, items: 40, distilled: 0 }),
+ );
+ const onOpenSettings = vi.fn();
+ render(
+ <QueryClientProvider client={makeClient()}>
+ <ExplorePanel onOpenSources={() => {}} onOpenSettings={onOpenSettings} />
+ </QueryClientProvider>,
+ );
+
+ const banner = await screen.findByTestId("explore-empty");
+ expect(banner.getAttribute("data-reason")).toBe("nothing_distilled");
+ fireEvent.click(screen.getByTestId("explore-empty-action"));
+ expect(onOpenSettings).toHaveBeenCalled();
+ });
+
+ it("keeps the moments readable when only the topic layer is empty", async () => {
+ installRoutes({
+ "/api/ultrawiki/explore/entities": {
+ ok: true,
+ entities: [],
+ total: 0,
+ corpus: FULL_CORPUS,
+ reason: "no_entities",
+ },
+ });
+ renderPanel();
+
+ expect((await screen.findByTestId("explore-empty")).getAttribute("data-reason")).toBe(
+ "no_entities",
+ );
+ // The moments still arrived — an empty topic list must not hide them.
+ expect(await screen.findByTestId("explore-moment-1")).toBeTruthy();
+ });
+});
+
+describe("failure", () => {
+ it("reports a dead knowledge base instead of rendering an empty shell", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new Error("network down");
+ }),
+ );
+ renderPanel();
+
+ expect(await screen.findByTestId("explore-error")).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.tsx
new file mode 100644
index 0000000000..3cf9b78cde
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.tsx
@@ -0,0 +1,427 @@
+/**
+ * Explore — the readable face of the knowledge base.
+ *
+ * Everything else in the Ultra panel is administrative: what is connected,
+ * what is importing, what is configured. This is the one view that answers
+ * the question the user actually has — "what does it know about my life?"
+ *
+ * Visual encoding (lib/entityGraph.ts, never inline):
+ * - how OFTEN a topic comes up → its count and its node size in the graph
+ * - WHEN it lived in your history → the time bar under each topic and the
+ * brightness of its node
+ * Both are derived from the data. There is no decorative colour in here.
+ *
+ * The time bar is the signature of this view: at a glance you see that
+ * "Berlin" runs the whole way through while "Bora Bora" was one bright week
+ * in July — a shape no list of counts can show.
+ */
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { ArrowLeft, ExternalLink, Search } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import {
+ corpusSpan,
+ recencyTint,
+ spanBar,
+ type CorpusSpan,
+} from "@/lib/entityGraph";
+import {
+ exploreReasonKey,
+ fetchExploreEntities,
+ fetchExploreEntity,
+ fetchExploreMoments,
+ type UltraWikiEntity,
+ type UltraWikiExploreReason,
+ type UltraWikiMoment,
+} from "@/lib/ultrawikiExploreApi";
+import { EntityGraph } from "@/components/ultrawiki/EntityGraph";
+
+export interface ExplorePanelProps {
+ onOpenSources: () => void;
+ onOpenSettings: () => void;
+}
+
+/** Which tab an empty state should send the user to, if any. */
+const EMPTY_ACTION: Record<UltraWikiExploreReason, "sources" | "settings" | null> =
+ {
+ ok: null,
+ no_sources: "sources",
+ nothing_imported: "sources",
+ nothing_distilled: "settings",
+ no_entities: null,
+ };
+
+export function ExplorePanel({
+ onOpenSources,
+ onOpenSettings,
+}: ExplorePanelProps): JSX.Element {
+ const t = useT();
+ const [search, setSearch] = useState("");
+ const [selected, setSelected] = useState<string | null>(null);
+ const [minMentions, setMinMentions] = useState(2);
+
+ const entitiesQuery = useQuery({
+ queryKey: ["ultrawiki", "explore", "entities"],
+ // The whole topic list is small (a real corpus measured under a thousand)
+ // and filtering happens locally, so typing stays instant instead of
+ // firing a request per keystroke.
+ queryFn: () => fetchExploreEntities({ limit: 2000 }),
+ staleTime: 30_000,
+ });
+
+ const momentsQuery = useQuery({
+ queryKey: ["ultrawiki", "explore", "moments"],
+ queryFn: () => fetchExploreMoments({ limit: 200 }),
+ staleTime: 30_000,
+ });
+
+ const detailQuery = useQuery({
+ queryKey: ["ultrawiki", "explore", "entity", selected],
+ queryFn: () => fetchExploreEntity(selected as string),
+ enabled: selected !== null,
+ staleTime: 30_000,
+ });
+
+ const entities = entitiesQuery.data?.entities ?? [];
+ const span = useMemo(() => corpusSpan(entities), [entities]);
+
+ const filtered = useMemo(() => {
+ const needle = search.trim().toLowerCase();
+ if (!needle) return entities;
+ return entities.filter(
+ (entity) =>
+ entity.key.includes(needle) ||
+ entity.label.toLowerCase().includes(needle),
+ );
+ }, [entities, search]);
+
+ if (entitiesQuery.isError && momentsQuery.isError) {
+ return (
+ <div className="flex flex-1 items-center justify-center p-6">
+ <p
+ role="alert"
+ data-testid="explore-error"
+ className="max-w-md rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive"
+ >
+ {t("ultrawiki.explore.error")}
+ </p>
+ </div>
+ );
+ }
+
+ if (entitiesQuery.isLoading) {
+ return (
+ <div
+ data-testid="explore-loading"
+ className="flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground"
+ >
+ {t("ultrawiki.explore.loading")}
+ </div>
+ );
+ }
+
+ const reason = entitiesQuery.data?.reason ?? "ok";
+ const corpus = entitiesQuery.data?.corpus ?? {
+ sources: 0,
+ items: 0,
+ distilled: 0,
+ };
+ const action = EMPTY_ACTION[reason];
+
+ return (
+ <div className="flex flex-1 min-h-0 flex-col" data-testid="explore-panel">
+ {reason !== "ok" && (
+ <div
+ data-testid="explore-empty"
+ data-reason={reason}
+ className="flex flex-wrap items-center gap-x-2 gap-y-1 border-b border-border bg-muted/30 px-4 py-2.5 text-xs text-muted-foreground"
+ >
+ <span>{t(exploreReasonKey(reason))}</span>
+ {action && (
+ <button
+ type="button"
+ data-testid="explore-empty-action"
+ onClick={action === "sources" ? onOpenSources : onOpenSettings}
+ className="underline underline-offset-2 hover:text-foreground"
+ >
+ {action === "sources"
+ ? t("ultrawiki.panel.tab_sources")
+ : t("ultrawiki.panel.tab_settings")}
+ </button>
+ )}
+ </div>
+ )}
+
+ <div className="flex min-h-0 flex-1 flex-col lg:flex-row">
+ <aside className="flex min-h-0 shrink-0 flex-col border-b border-border lg:w-72 lg:border-b-0 lg:border-r">
+ <div className="relative border-b border-border px-3 py-2">
+ <Search
+ className="pointer-events-none absolute left-5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
+ aria-hidden
+ />
+ <input
+ data-testid="explore-search"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ placeholder={t("ultrawiki.explore.search_placeholder")}
+ aria-label={t("ultrawiki.explore.search_placeholder")}
+ className="w-full rounded-md border border-border bg-background py-1.5 pl-7 pr-2 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-primary"
+ />
+ </div>
+
+ <p className="px-4 py-1.5 text-[11px] uppercase tracking-wide text-muted-foreground">
+ {t("ultrawiki.explore.entities_count").replace(
+ "{0}",
+ String(filtered.length),
+ )}
+ </p>
+
+ <div className="min-h-0 flex-1 overflow-y-auto pb-2 max-lg:max-h-64">
+ {filtered.length === 0 && search.trim() !== "" && (
+ <p
+ data-testid="explore-no-search-hits"
+ className="px-4 py-3 text-xs text-muted-foreground"
+ >
+ {t("ultrawiki.explore.no_search_hits").replace("{0}", search.trim())}
+ </p>
+ )}
+ {filtered.map((entity) => (
+ <EntityRow
+ key={entity.key}
+ entity={entity}
+ span={span}
+ active={entity.key === selected}
+ onSelect={() => setSelected(entity.key)}
+ />
+ ))}
+ </div>
+ </aside>
+
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="h-56 shrink-0 border-b border-border sm:h-64">
+ <EntityGraph
+ minMentions={minMentions}
+ onMinMentionsChange={setMinMentions}
+ selectedKey={selected}
+ onSelect={setSelected}
+ />
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {selected && detailQuery.data ? (
+ <EntityDetail
+ entity={detailQuery.data.entity}
+ moments={detailQuery.data.moments}
+ onBack={() => setSelected(null)}
+ onSelect={setSelected}
+ />
+ ) : (
+ <MomentList
+ title={t("ultrawiki.explore.moments_title")}
+ moments={momentsQuery.data?.moments ?? []}
+ count={momentsQuery.data?.total ?? 0}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+
+ <p className="sr-only" data-testid="explore-corpus">
+ {corpus.sources}/{corpus.items}/{corpus.distilled}
+ </p>
+ </div>
+ );
+}
+
+function EntityRow({
+ entity,
+ span,
+ active,
+ onSelect,
+}: {
+ entity: UltraWikiEntity;
+ span: CorpusSpan;
+ active: boolean;
+ onSelect: () => void;
+}): JSX.Element {
+ const bar = spanBar(entity, span);
+ const tint = recencyTint(entity.last_seen, span);
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ data-testid={`explore-entity-${entity.key}`}
+ data-entity-key={entity.key}
+ data-active={active ? "true" : "false"}
+ className={cn(
+ "group block w-full px-4 py-1.5 text-left transition-colors",
+ active ? "bg-primary/10" : "hover:bg-muted/50",
+ )}
+ >
+ <span className="flex items-baseline justify-between gap-2">
+ <span className="truncate text-xs text-foreground">{entity.label}</span>
+ <span className="shrink-0 text-[11px] tabular-nums text-muted-foreground">
+ {entity.mentions}
+ </span>
+ </span>
+ {/* The signature of this view: where in your history this topic lived.
+ Width is its lifetime, position is when, brightness is how recent. */}
+ <span
+ className="mt-1 block h-[3px] w-full rounded-full bg-muted"
+ aria-hidden
+ >
+ <span
+ data-testid={`explore-span-${entity.key}`}
+ data-width={bar.width.toFixed(4)}
+ data-offset={bar.offset.toFixed(4)}
+ className="block h-full rounded-full"
+ style={{
+ marginLeft: `${bar.offset * 100}%`,
+ width: `${bar.width * 100}%`,
+ backgroundColor: tint,
+ }}
+ />
+ </span>
+ </button>
+ );
+}
+
+function EntityDetail({
+ entity,
+ moments,
+ onBack,
+ onSelect,
+}: {
+ entity: UltraWikiEntity;
+ moments: UltraWikiMoment[];
+ onBack: () => void;
+ onSelect: (key: string) => void;
+}): JSX.Element {
+ const t = useT();
+ return (
+ <div className="p-4" data-testid="explore-detail">
+ <button
+ type="button"
+ onClick={onBack}
+ className="mb-3 flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
+ >
+ <ArrowLeft className="h-3 w-3" aria-hidden />
+ {t("ultrawiki.explore.back")}
+ </button>
+
+ <h3 className="text-sm text-foreground">{entity.label}</h3>
+ <p className="mt-0.5 text-[11px] tabular-nums text-muted-foreground">
+ {t("ultrawiki.explore.mentions_long").replace(
+ "{0}",
+ String(entity.mentions),
+ )}
+ {entity.first_seen && (
+ <>
+ {" · "}
+ {t("ultrawiki.explore.period")
+ .replace("{0}", entity.first_seen.slice(0, 10))
+ .replace("{1}", entity.last_seen.slice(0, 10))}
+ </>
+ )}
+ </p>
+
+ <div className="mt-3">
+ <p className="text-[11px] uppercase tracking-wide text-muted-foreground">
+ {t("ultrawiki.explore.neighbors")}
+ </p>
+ {entity.neighbors.length === 0 ? (
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("ultrawiki.explore.no_neighbors")}
+ </p>
+ ) : (
+ <div className="mt-1.5 flex flex-wrap gap-1.5">
+ {entity.neighbors.slice(0, 12).map((neighbor) => (
+ <button
+ key={neighbor.key}
+ type="button"
+ data-testid={`explore-neighbor-${neighbor.key}`}
+ onClick={() => onSelect(neighbor.key)}
+ title={t("ultrawiki.explore.shared").replace(
+ "{0}",
+ String(neighbor.shared),
+ )}
+ className="rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground hover:border-primary/50 hover:text-foreground"
+ >
+ {neighbor.label}
+ <span className="ml-1 tabular-nums opacity-60">
+ {neighbor.shared}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <MomentList
+ title={t("ultrawiki.explore.moments_of").replace("{0}", entity.label)}
+ moments={moments}
+ count={moments.length}
+ className="mt-4"
+ />
+ </div>
+ );
+}
+
+function MomentList({
+ title,
+ moments,
+ count,
+ className,
+}: {
+ title: string;
+ moments: UltraWikiMoment[];
+ count: number;
+ className?: string;
+}): JSX.Element {
+ const t = useT();
+ return (
+ <div className={cn("px-4 py-3", className)}>
+ <p className="flex items-baseline gap-2 text-[11px] uppercase tracking-wide text-muted-foreground">
+ {title}
+ <span className="tabular-nums normal-case opacity-70">
+ {t("ultrawiki.explore.moments_count").replace("{0}", String(count))}
+ </span>
+ </p>
+ <ol className="mt-2 space-y-2.5">
+ {moments.map((moment) => (
+ <li
+ key={moment.document_id}
+ data-testid={`explore-moment-${moment.document_id}`}
+ className="border-l-2 border-border pl-3"
+ >
+ <p className="text-xs leading-snug text-foreground">{moment.title}</p>
+ {moment.summary && (
+ <p className="mt-0.5 line-clamp-2 text-[11px] leading-snug text-muted-foreground">
+ {moment.summary}
+ </p>
+ )}
+ <p className="mt-1 flex items-center gap-1.5 text-[10px] tabular-nums text-muted-foreground">
+ <span>{moment.timestamp_utc.slice(0, 10)}</span>
+ <span aria-hidden>·</span>
+ <span className="truncate">{moment.source_label}</span>
+ {moment.permalink && (
+ <a
+ href={moment.permalink}
+ data-testid={`explore-moment-link-${moment.document_id}`}
+ className="inline-flex items-center gap-0.5 hover:text-foreground"
+ >
+ <ExternalLink className="h-2.5 w-2.5" aria-hidden />
+ {t("ultrawiki.explore.open_source")}
+ </a>
+ )}
+ </p>
+ </li>
+ ))}
+ </ol>
+ </div>
+ );
+}
+
+export default ExplorePanel;
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index f40052cc2f..063b9e8f46 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2710,6 +2710,38 @@
"result_error": "Discord nicht erreichbar, bitte später erneut versuchen."
},
"ultrawiki": {
+ "explore": {
+ "tab": "Entdecken",
+ "loading": "Wissensbestand wird gelesen …",
+ "error": "Der Wissensbestand konnte nicht gelesen werden.",
+ "entities_title": "Begriffe",
+ "entities_count": "{0} Begriffe",
+ "moments_title": "Momente",
+ "moments_count": "{0} Momente",
+ "graph_title": "Verbindungen",
+ "search_placeholder": "Begriff suchen …",
+ "no_search_hits": "Kein Begriff passt zu „{0}“.",
+ "mentions": "{0}×",
+ "mentions_long": "{0} Erwähnungen",
+ "period": "{0} bis {1}",
+ "neighbors": "Taucht auf mit",
+ "no_neighbors": "Kommt bisher immer allein vor.",
+ "shared": "{0} gemeinsame Momente",
+ "back": "Zurück zur Übersicht",
+ "open_source": "Beleg öffnen",
+ "source_prefix": "aus",
+ "min_mentions": "Ab {0} Erwähnungen",
+ "graph_shown": "{0} von {1} Begriffen",
+ "graph_hint": "Weniger häufige Begriffe sind ausgeblendet — Regler nach links für alle.",
+ "graph_empty": "Kein Begriff wird oft genug erwähnt. Stell den Regler auf 1.",
+ "moments_of": "Momente mit {0}",
+ "empty": {
+ "no_sources": "Es ist noch keine Quelle verbunden. Verbinde zuerst eine Quelle, dann kann Jarvis etwas wissen.",
+ "nothing_imported": "Eine Quelle ist verbunden, aber es wurde noch nichts geholt. Starte den Import bei den Quellen.",
+ "nothing_distilled": "Es liegen Einträge da, aber noch keiner wurde ausgewertet. Dafür braucht es ein eingerichtetes Sprachmodell in den Einstellungen.",
+ "no_entities": "Die Einträge wurden ausgewertet, aber es kamen keine Namen oder Orte darin vor. Die Momente unten kannst du trotzdem durchblättern."
+ }
+ },
"mode": {
"normal": "Normal",
"ultra": "Ultra",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 6c398bc7fc..ec4e0a0814 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2711,6 +2711,38 @@
"result_error": "Couldn't reach Discord, please try again later."
},
"ultrawiki": {
+ "explore": {
+ "tab": "Explore",
+ "loading": "Reading the knowledge base …",
+ "error": "The knowledge base could not be read.",
+ "entities_title": "Topics",
+ "entities_count": "{0} topics",
+ "moments_title": "Moments",
+ "moments_count": "{0} moments",
+ "graph_title": "Connections",
+ "search_placeholder": "Search a topic …",
+ "no_search_hits": "No topic matches “{0}”.",
+ "mentions": "{0}×",
+ "mentions_long": "{0} mentions",
+ "period": "{0} to {1}",
+ "neighbors": "Appears with",
+ "no_neighbors": "Has only ever appeared on its own.",
+ "shared": "{0} shared moments",
+ "back": "Back to the overview",
+ "open_source": "Open the evidence",
+ "source_prefix": "from",
+ "min_mentions": "From {0} mentions",
+ "graph_shown": "{0} of {1} topics",
+ "graph_hint": "Rarer topics are hidden — move the slider left to show all.",
+ "graph_empty": "No topic is mentioned often enough. Set the slider to 1.",
+ "moments_of": "Moments involving {0}",
+ "empty": {
+ "no_sources": "No source is connected yet. Connect one first, then Jarvis has something to know.",
+ "nothing_imported": "A source is connected but nothing has been fetched yet. Start the import under Sources.",
+ "nothing_distilled": "Entries are stored but none has been analysed yet. That needs a language model configured in the settings.",
+ "no_entities": "The entries were analysed but named no people or places. You can still browse the moments below."
+ }
+ },
"mode": {
"normal": "Normal",
"ultra": "Ultra",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 9c6e08f9db..6f3860527f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2710,6 +2710,38 @@
"result_error": "No se pudo llegar a Discord, inténtalo de nuevo más tarde."
},
"ultrawiki": {
+ "explore": {
+ "tab": "Explorar",
+ "loading": "Leyendo la base de conocimiento …",
+ "error": "No se pudo leer la base de conocimiento.",
+ "entities_title": "Temas",
+ "entities_count": "{0} temas",
+ "moments_title": "Momentos",
+ "moments_count": "{0} momentos",
+ "graph_title": "Conexiones",
+ "search_placeholder": "Buscar un tema …",
+ "no_search_hits": "Ningún tema coincide con «{0}».",
+ "mentions": "{0}×",
+ "mentions_long": "{0} menciones",
+ "period": "{0} a {1}",
+ "neighbors": "Aparece junto a",
+ "no_neighbors": "Hasta ahora siempre aparece solo.",
+ "shared": "{0} momentos compartidos",
+ "back": "Volver al resumen",
+ "open_source": "Abrir la evidencia",
+ "source_prefix": "de",
+ "min_mentions": "Desde {0} menciones",
+ "graph_shown": "{0} de {1} temas",
+ "graph_hint": "Los temas menos frecuentes están ocultos: mueve el control a la izquierda para verlos todos.",
+ "graph_empty": "Ningún tema se menciona lo suficiente. Pon el control en 1.",
+ "moments_of": "Momentos con {0}",
+ "empty": {
+ "no_sources": "Todavía no hay ninguna fuente conectada. Conecta una primero y Jarvis tendrá algo que saber.",
+ "nothing_imported": "Hay una fuente conectada pero aún no se ha traído nada. Inicia la importación en Fuentes.",
+ "nothing_distilled": "Hay entradas guardadas pero ninguna se ha analizado todavía. Para eso hace falta un modelo de lenguaje configurado en los ajustes.",
+ "no_entities": "Las entradas se analizaron pero no mencionaron personas ni lugares. Aun así puedes hojear los momentos de abajo."
+ }
+ },
"mode": {
"normal": "Normal",
"ultra": "Ultra",
diff --git a/jarvis/ui/web/frontend/src/lib/entityGraph.test.ts b/jarvis/ui/web/frontend/src/lib/entityGraph.test.ts
new file mode 100644
index 0000000000..66da2c52ab
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/entityGraph.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Pure helpers behind the Explore view's visual language.
+ *
+ * Two things carry meaning here and both are derived from the data, never
+ * decorative: how big a node is (how often a topic comes up) and how bright
+ * it is (how recently). The time bar next to each topic is the same idea in
+ * list form — where in your history this topic actually lived.
+ */
+import { describe, expect, it } from "vitest";
+
+import {
+ corpusSpan,
+ nodeRadius,
+ recencyTint,
+ spanBar,
+ type SpannedEntity,
+} from "@/lib/entityGraph";
+
+const entity = (first: string, last: string, mentions = 1): SpannedEntity => ({
+ first_seen: first,
+ last_seen: last,
+ mentions,
+});
+
+describe("corpusSpan", () => {
+ it("brackets the earliest and latest moment across all topics", () => {
+ const span = corpusSpan([
+ entity("2026-03-01T00:00:00Z", "2026-04-01T00:00:00Z"),
+ entity("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z"),
+ ]);
+
+ expect(span.start).toBe(Date.parse("2026-01-01T00:00:00Z"));
+ expect(span.end).toBe(Date.parse("2026-04-01T00:00:00Z"));
+ });
+
+ it("returns an empty span for no topics rather than NaN", () => {
+ expect(corpusSpan([])).toEqual({ start: 0, end: 0 });
+ });
+
+ it("ignores unparseable timestamps instead of poisoning the span", () => {
+ const span = corpusSpan([
+ entity("not-a-date", "also-not"),
+ entity("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z"),
+ ]);
+
+ expect(span.start).toBe(Date.parse("2026-01-01T00:00:00Z"));
+ expect(span.end).toBe(Date.parse("2026-02-01T00:00:00Z"));
+ });
+});
+
+describe("spanBar", () => {
+ const span = {
+ start: Date.parse("2026-01-01T00:00:00Z"),
+ end: Date.parse("2026-05-01T00:00:00Z"),
+ };
+
+ it("places a topic that ran the whole time across the full width", () => {
+ const bar = spanBar(entity("2026-01-01T00:00:00Z", "2026-05-01T00:00:00Z"), span);
+
+ expect(bar.offset).toBeCloseTo(0);
+ expect(bar.width).toBeCloseTo(1);
+ });
+
+ it("places a late, short-lived topic at the right edge", () => {
+ const bar = spanBar(entity("2026-04-01T00:00:00Z", "2026-05-01T00:00:00Z"), span);
+
+ expect(bar.offset).toBeGreaterThan(0.7);
+ expect(bar.width).toBeLessThan(0.3);
+ });
+
+ it("gives a single-moment topic a visible minimum width", () => {
+ const bar = spanBar(entity("2026-03-01T00:00:00Z", "2026-03-01T00:00:00Z"), span);
+
+ // A zero-width bar would render as nothing at all — the one case where
+ // being literal makes the data invisible.
+ expect(bar.width).toBeGreaterThan(0);
+ expect(bar.offset + bar.width).toBeLessThanOrEqual(1);
+ });
+
+ it("falls back to the full width when the corpus has no time span", () => {
+ const bar = spanBar(entity("2026-03-01T00:00:00Z", "2026-03-01T00:00:00Z"), {
+ start: 0,
+ end: 0,
+ });
+
+ expect(bar).toEqual({ offset: 0, width: 1 });
+ });
+});
+
+describe("nodeRadius", () => {
+ it("grows with mentions but keeps the rarest node visible", () => {
+ expect(nodeRadius(1, 100)).toBeGreaterThan(0);
+ expect(nodeRadius(100, 100)).toBeGreaterThan(nodeRadius(1, 100));
+ });
+
+ it("compresses the range so one dominant topic cannot swamp the canvas", () => {
+ // Linear scaling would make a 132-mention node 132x the area of a 1.
+ const ratio = nodeRadius(132, 132) / nodeRadius(1, 132);
+ expect(ratio).toBeLessThan(6);
+ });
+
+ it("does not divide by zero when every topic is equally rare", () => {
+ expect(Number.isFinite(nodeRadius(1, 1))).toBe(true);
+ });
+});
+
+describe("recencyTint", () => {
+ const span = {
+ start: Date.parse("2026-01-01T00:00:00Z"),
+ end: Date.parse("2026-05-01T00:00:00Z"),
+ };
+
+ it("returns a hex colour for both ends of the span", () => {
+ expect(recencyTint("2026-01-01T00:00:00Z", span)).toMatch(/^#[0-9a-f]{6}$/);
+ expect(recencyTint("2026-05-01T00:00:00Z", span)).toMatch(/^#[0-9a-f]{6}$/);
+ });
+
+ it("brightens towards the present", () => {
+ const old = recencyTint("2026-01-01T00:00:00Z", span);
+ const fresh = recencyTint("2026-05-01T00:00:00Z", span);
+
+ expect(old).not.toBe(fresh);
+ });
+
+ it("survives an unparseable timestamp without producing NaN colours", () => {
+ expect(recencyTint("whenever", span)).toMatch(/^#[0-9a-f]{6}$/);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/entityGraph.ts b/jarvis/ui/web/frontend/src/lib/entityGraph.ts
new file mode 100644
index 0000000000..f808f8d85b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/entityGraph.ts
@@ -0,0 +1,123 @@
+/**
+ * Visual encoding for the UltraWiki Explore view.
+ *
+ * Two properties of a topic carry meaning and both come from the data:
+ * how OFTEN it comes up (node size, mention count) and WHEN it lived in your
+ * history (the time bar in the list, the brightness in the graph). Nothing
+ * here is decoration — a reader can point at any pixel and say what it means.
+ *
+ * Kept out of the components so the encoding is unit-testable without a
+ * canvas, and so there is exactly one definition of what "recent" looks like.
+ */
+
+/** The time-bearing slice of an entity the encoding needs. */
+export interface SpannedEntity {
+ first_seen: string;
+ last_seen: string;
+ mentions: number;
+}
+
+/** Epoch-millisecond bounds of the whole corpus. */
+export interface CorpusSpan {
+ start: number;
+ end: number;
+}
+
+/** Position of a topic's bar inside the corpus span, both in 0..1. */
+export interface SpanBar {
+ offset: number;
+ width: number;
+}
+
+/** A single-moment topic still needs to be visible, so bars have a floor. */
+const MIN_BAR_WIDTH = 0.035;
+
+/** Node radius range in graph units. */
+const MIN_RADIUS = 3;
+const RADIUS_RANGE = 9;
+
+/**
+ * Oldest → newest tint. The dim end is deliberately a desaturated blue-grey
+ * rather than a second hue: two hues would read as two CATEGORIES, and
+ * recency is one continuous axis.
+ */
+const TINT_OLD = { r: 0x4c, g: 0x5a, b: 0x72 };
+const TINT_NEW = { r: 0x7d, g: 0xb8, b: 0xff };
+
+function parse(timestamp: string): number | null {
+ const value = Date.parse(timestamp);
+ return Number.isFinite(value) ? value : null;
+}
+
+/** Earliest first_seen and latest last_seen across every topic. */
+export function corpusSpan(entities: readonly SpannedEntity[]): CorpusSpan {
+ let start = Number.POSITIVE_INFINITY;
+ let end = Number.NEGATIVE_INFINITY;
+ for (const entity of entities) {
+ const first = parse(entity.first_seen);
+ const last = parse(entity.last_seen);
+ if (first !== null) start = Math.min(start, first);
+ if (last !== null) end = Math.max(end, last);
+ }
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return { start: 0, end: 0 };
+ return { start, end };
+}
+
+/**
+ * Where a topic's life sits inside the corpus, as offset + width in 0..1.
+ *
+ * A corpus with no measurable span (one moment, or unparseable dates) gives
+ * every topic the full width: claiming a position inside a span that does not
+ * exist would be inventing information.
+ */
+export function spanBar(entity: SpannedEntity, span: CorpusSpan): SpanBar {
+ const total = span.end - span.start;
+ if (total <= 0) return { offset: 0, width: 1 };
+
+ const first = parse(entity.first_seen);
+ const last = parse(entity.last_seen);
+ if (first === null || last === null) return { offset: 0, width: 1 };
+
+ const offset = Math.min(Math.max((first - span.start) / total, 0), 1);
+ const raw = Math.max((last - first) / total, 0);
+ const width = Math.min(Math.max(raw, MIN_BAR_WIDTH), 1 - offset || MIN_BAR_WIDTH);
+ return { offset: Math.min(offset, 1 - width), width };
+}
+
+/**
+ * Node radius for a mention count.
+ *
+ * Square-root rather than linear: on a real corpus the top topic is mentioned
+ * a hundred times more than the tail, and a linear scale turns that into one
+ * blob with dust around it. The root compresses the range while keeping the
+ * order intact and readable.
+ */
+export function nodeRadius(mentions: number, maxMentions: number): number {
+ const ceiling = Math.max(maxMentions, 1);
+ const share = Math.min(Math.max(mentions, 0) / ceiling, 1);
+ return MIN_RADIUS + RADIUS_RANGE * Math.sqrt(share);
+}
+
+function hex(channel: number): string {
+ return Math.round(Math.min(Math.max(channel, 0), 255))
+ .toString(16)
+ .padStart(2, "0");
+}
+
+/**
+ * Colour for "last mentioned at this point in the span" — dim for long ago,
+ * bright for recent. An unreadable timestamp lands at the dim end rather than
+ * producing a NaN colour the canvas would silently drop.
+ */
+export function recencyTint(lastSeen: string, span: CorpusSpan): string {
+ const total = span.end - span.start;
+ const last = parse(lastSeen);
+ const position =
+ total > 0 && last !== null
+ ? Math.min(Math.max((last - span.start) / total, 0), 1)
+ : 0;
+ const r = TINT_OLD.r + (TINT_NEW.r - TINT_OLD.r) * position;
+ const g = TINT_OLD.g + (TINT_NEW.g - TINT_OLD.g) * position;
+ const b = TINT_OLD.b + (TINT_NEW.b - TINT_OLD.b) * position;
+ return `#${hex(r)}${hex(g)}${hex(b)}`;
+}
diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiExploreApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiExploreApi.ts
new file mode 100644
index 0000000000..0ee59ce0db
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiExploreApi.ts
@@ -0,0 +1,185 @@
+/**
+ * Typed fetchers for the UltraWiki Explore surface
+ * (`jarvis/ui/web/ultrawiki_explore_routes.py`).
+ *
+ * Explore is the readable view over the store: entity pages, moment pages,
+ * and the graph over them, all served from the derived projection. Every
+ * answer carries the corpus counts and a named reason, so an empty view can
+ * say WHY it is empty instead of showing a blank canvas.
+ *
+ * Like the rest of the UltraWiki surface, 409 means "Ultra mode is off" (the
+ * app is healthy, the normal wiki answers) and 503 means the service is not
+ * wired yet. Both arrive as an {@link UltraWikiApiError}.
+ */
+
+import { UltraWikiApiError } from "@/lib/ultrawikiApi";
+
+// Mirrors jarvis/ultrawiki/types.py::ExploreReason — five-layer anti-drift
+// discipline (AP-4 / BUG-008). Parity-tested in
+// tests/unit/ultrawiki/test_explore_reason_parity.py; never retype elsewhere.
+export const ULTRAWIKI_EXPLORE_REASONS = [
+ "ok",
+ "no_sources",
+ "nothing_imported",
+ "nothing_distilled",
+ "no_entities",
+] as const;
+export type UltraWikiExploreReason = (typeof ULTRAWIKI_EXPLORE_REASONS)[number];
+
+/** How much the knowledge base holds — what turns "empty" into a diagnosis. */
+export interface UltraWikiCorpusCounts {
+ sources: number;
+ items: number;
+ distilled: number;
+}
+
+/** One neighbour of an entity, with the label a human should see. */
+export interface UltraWikiEntityNeighbor {
+ key: string;
+ label: string;
+ shared: number;
+}
+
+/** One browsable entity page. */
+export interface UltraWikiEntity {
+ key: string;
+ label: string;
+ mentions: number;
+ first_seen: string;
+ last_seen: string;
+ neighbors: UltraWikiEntityNeighbor[];
+}
+
+/** One distilled moment — titled by the question it answers. */
+export interface UltraWikiMoment {
+ document_id: number;
+ item_id: number;
+ title: string;
+ summary: string;
+ resolution: string;
+ entity_keys: string[];
+ timestamp_utc: string;
+ month: string;
+ source_id: string;
+ source_label: string;
+ permalink: string;
+}
+
+export interface UltraWikiEntitiesPage {
+ ok: boolean;
+ entities: UltraWikiEntity[];
+ total: number;
+ corpus: UltraWikiCorpusCounts;
+ reason: UltraWikiExploreReason;
+}
+
+export interface UltraWikiEntityDetail {
+ ok: boolean;
+ entity: UltraWikiEntity;
+ moments: UltraWikiMoment[];
+ total: number;
+ corpus: UltraWikiCorpusCounts;
+}
+
+export interface UltraWikiMomentsPage {
+ ok: boolean;
+ moments: UltraWikiMoment[];
+ total: number;
+ corpus: UltraWikiCorpusCounts;
+ reason: UltraWikiExploreReason;
+}
+
+export interface UltraWikiGraphNode {
+ key: string;
+ label: string;
+ mentions: number;
+ first_seen: string;
+ last_seen: string;
+}
+
+export interface UltraWikiGraphEdge {
+ source: string;
+ target: string;
+ weight: number;
+}
+
+export interface UltraWikiGraphPayload {
+ ok: boolean;
+ nodes: UltraWikiGraphNode[];
+ edges: UltraWikiGraphEdge[];
+ min_mentions: number;
+ total_entities: number;
+ corpus: UltraWikiCorpusCounts;
+ reason: UltraWikiExploreReason;
+}
+
+async function getJson<T>(path: string): Promise<T> {
+ const response = await fetch(path);
+ if (!response.ok) {
+ let detail: unknown = null;
+ try {
+ const body = await response.json();
+ detail = (body as { detail?: unknown })?.detail ?? body;
+ } catch {
+ detail = null;
+ }
+ throw new UltraWikiApiError(
+ `HTTP ${response.status}`,
+ response.status,
+ detail,
+ );
+ }
+ return (await response.json()) as T;
+}
+
+export async function fetchExploreEntities(
+ options: { q?: string; limit?: number } = {},
+): Promise<UltraWikiEntitiesPage> {
+ const params = new URLSearchParams();
+ if (options.q) params.set("q", options.q);
+ if (options.limit) params.set("limit", String(options.limit));
+ const query = params.toString();
+ return getJson<UltraWikiEntitiesPage>(
+ `/api/ultrawiki/explore/entities${query ? `?${query}` : ""}`,
+ );
+}
+
+export async function fetchExploreEntity(
+ key: string,
+): Promise<UltraWikiEntityDetail> {
+ return getJson<UltraWikiEntityDetail>(
+ `/api/ultrawiki/explore/entities/${encodeURIComponent(key)}`,
+ );
+}
+
+export async function fetchExploreMoments(
+ options: { entity?: string; month?: string; limit?: number } = {},
+): Promise<UltraWikiMomentsPage> {
+ const params = new URLSearchParams();
+ if (options.entity) params.set("entity", options.entity);
+ if (options.month) params.set("month", options.month);
+ if (options.limit) params.set("limit", String(options.limit));
+ const query = params.toString();
+ return getJson<UltraWikiMomentsPage>(
+ `/api/ultrawiki/explore/moments${query ? `?${query}` : ""}`,
+ );
+}
+
+export async function fetchExploreGraph(
+ minMentions: number,
+): Promise<UltraWikiGraphPayload> {
+ return getJson<UltraWikiGraphPayload>(
+ `/api/ultrawiki/explore/graph?min_mentions=${minMentions}`,
+ );
+}
+
+/**
+ * The i18n key explaining an empty Explore view.
+ *
+ * Kept next to the type so a new reason cannot be added without a matching
+ * message — a blank screen with no explanation is the exact failure this
+ * whole reason mechanism exists to prevent.
+ */
+export function exploreReasonKey(reason: UltraWikiExploreReason): string {
+ return `ultrawiki.explore.empty.${reason}`;
+}
diff --git a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx
index 6191f7b08f..7e07e74c17 100644
--- a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx
+++ b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx
@@ -19,6 +19,7 @@
import { useState } from "react";
import {
AlertTriangle,
+ Compass,
Database,
ListChecks,
MessageCircleQuestion,
@@ -39,8 +40,15 @@ import { SourcesPanel } from "@/components/ultrawiki/SourcesPanel";
import { ContentsPanel } from "@/components/ultrawiki/ContentsPanel";
import { SlotsPanel } from "@/components/ultrawiki/SlotsPanel";
import { ImportProgress } from "@/components/ultrawiki/ImportProgress";
+import { ExplorePanel } from "@/components/ultrawiki/ExplorePanel";
-type UltraTab = "check" | "ask" | "sources" | "contents" | "settings";
+type UltraTab =
+ | "check"
+ | "explore"
+ | "ask"
+ | "sources"
+ | "contents"
+ | "settings";
export function UltraWikiPanel(): JSX.Element {
const t = useT();
@@ -140,6 +148,13 @@ export function UltraWikiPanel(): JSX.Element {
label={t("ultrawiki.panel.tab_check")}
testId="ultrawiki-tab-check"
/>
+ <UltraTabButton
+ active={tab === "explore"}
+ onClick={() => setTab("explore")}
+ icon={<Compass className="h-3.5 w-3.5" aria-hidden />}
+ label={t("ultrawiki.explore.tab")}
+ testId="ultrawiki-tab-explore"
+ />
<UltraTabButton
active={tab === "ask"}
onClick={() => setTab("ask")}
@@ -177,6 +192,12 @@ export function UltraWikiPanel(): JSX.Element {
onOpenSettings={() => setTab("settings")}
/>
)}
+ {tab === "explore" && (
+ <ExplorePanel
+ onOpenSources={() => setTab("sources")}
+ onOpenSettings={() => setTab("settings")}
+ />
+ )}
{tab === "ask" && (
<AskPanel
searchLegs={status.search_legs}
diff --git a/tests/unit/ultrawiki/test_explore_reason_parity.py b/tests/unit/ultrawiki/test_explore_reason_parity.py
new file mode 100644
index 0000000000..7da6add4d1
--- /dev/null
+++ b/tests/unit/ultrawiki/test_explore_reason_parity.py
@@ -0,0 +1,62 @@
+"""Five-layer drift guard for ``ExploreReason`` (AP-4 / BUG-008).
+
+The reason code crosses Python → REST → TypeScript → i18n → UI. Each hop is a
+place where a value can be added on one side and forgotten on the other, and
+the failure mode is silent: the view falls back to a blank panel with no
+explanation, which is the exact problem the reason codes were introduced to
+end. So the TS union and the three locale files are pinned to the Python enum
+here rather than by convention.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+from jarvis.ultrawiki.types import ExploreReason
+
+FRONTEND = Path(__file__).resolve().parents[3] / "jarvis/ui/web/frontend/src"
+API_TS = FRONTEND / "lib/ultrawikiExploreApi.ts"
+LOCALES = FRONTEND / "i18n/locales"
+SUPPORTED_LOCALES = ("de", "en", "es")
+
+
+def ts_union_values() -> set[str]:
+ """The quoted members of ``ULTRAWIKI_EXPLORE_REASONS``."""
+ source = API_TS.read_text(encoding="utf-8")
+ match = re.search(
+ r"ULTRAWIKI_EXPLORE_REASONS\s*=\s*\[(.*?)\]\s*as const", source, re.DOTALL
+ )
+ assert match is not None, "ULTRAWIKI_EXPLORE_REASONS array not found"
+ return set(re.findall(r'"([^"]+)"', match.group(1)))
+
+
+def locale_keys(locale: str) -> dict:
+ return json.loads((LOCALES / f"{locale}.json").read_text(encoding="utf-8"))
+
+
+def nested(data: dict, dotted: str) -> object | None:
+ node: object = data
+ for part in dotted.split("."):
+ if not isinstance(node, dict) or part not in node:
+ return None
+ node = node[part]
+ return node
+
+
+def test_typescript_union_matches_the_python_enum():
+ assert ts_union_values() == {reason.value for reason in ExploreReason}
+
+
+def test_every_reason_has_a_message_in_every_locale():
+ # "ok" is the non-empty case and needs no empty-state copy.
+ explaining = [r.value for r in ExploreReason if r is not ExploreReason.OK]
+ for locale in SUPPORTED_LOCALES:
+ data = locale_keys(locale)
+ for reason in explaining:
+ key = f"ultrawiki.explore.empty.{reason}"
+ message = nested(data, key)
+ assert isinstance(message, str) and message.strip(), (
+ f"{locale}.json is missing a message for {key}"
+ )