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(wiki): add a 3D memory map with a 2D/3D switch on both wiki surfaces

Ruben Lütke445d5175877b
diff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.json
index 1ff200922d..ace0ea66eb 100644
--- a/jarvis/ui/web/frontend/package-lock.json
+++ b/jarvis/ui/web/frontend/package-lock.json
@@ -33,6 +33,7 @@
"react-arborist": "^3.5.0",
"react-dom": "^18.3.1",
"react-force-graph-2d": "^1.25.0",
+ "react-force-graph-3d": "^1.29.1",
"react-markdown": "^9.1.0",
"react-use-websocket": "^4.13.0",
"recharts": "^3.8.1",
@@ -42,6 +43,8 @@
"remark-gfm": "^4.0.1",
"shiki": "^1.29.2",
"tailwind-merge": "^2.5.2",
+ "three": "^0.185.1",
+ "three-spritetext": "^1.10.0",
"zod": "^3.23.8",
"zustand": "^5.0.0"
},
@@ -51,6 +54,7 @@
"@types/node": "^25.6.0",
"@types/react": "^18.3.10",
"@types/react-dom": "^18.3.0",
+ "@types/three": "^0.185.3",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.20",
"jsdom": "^25.0.0",
@@ -505,6 +509,13 @@
"node": ">=18"
}
},
+ "node_modules/@dimforge/rapier3d-compat": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
@@ -2505,6 +2516,35 @@
"@types/react": "^18.0.0"
}
},
+ "node_modules/@types/stats.js": {
+ "version": "0.17.4",
+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/three": {
+ "version": "0.185.3",
+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.185.3.tgz",
+ "integrity": "sha512-8TqTn1+fjPWuJ4mR6Igtg56DCf9b5EeAlwhb5xaa6WlBrsg7SvG0NQbyctGRkHCKwg0uftfCspOEsTXelgktMA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "~0.12.0",
+ "@tweenjs/tween.js": "~23.1.3",
+ "@types/stats.js": "*",
+ "@types/webxr": ">=0.5.17",
+ "fflate": "~0.8.2",
+ "meshoptimizer": "~1.1.1"
+ }
+ },
+ "node_modules/@types/three/node_modules/@tweenjs/tween.js": {
+ "version": "23.1.3",
+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
@@ -2517,6 +2557,13 @@
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
"license": "MIT"
},
+ "node_modules/@types/webxr": {
+ "version": "0.5.24",
+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@ungap/structured-clone": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@@ -2765,6 +2812,22 @@
"d3-zoom": "^3.0.0"
}
},
+ "node_modules/3d-force-graph": {
+ "version": "1.80.0",
+ "resolved": "https://registry.npmjs.org/3d-force-graph/-/3d-force-graph-1.80.0.tgz",
+ "integrity": "sha512-tzI353gW1nXPpnC7VTa3JjMg+3cp77qOLUFO0vucPTfF+q5R6sQsNsIqVTbRIb7RSypn14nBa4yfkOe9ThxASw==",
+ "license": "MIT",
+ "dependencies": {
+ "accessor-fn": "1",
+ "kapsule": "^1.16",
+ "three": ">=0.179 <1",
+ "three-forcegraph": "1",
+ "three-render-objects": "^1.41"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/accessor-fn": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/accessor-fn/-/accessor-fn-1.5.3.tgz",
@@ -3548,6 +3611,18 @@
"node": ">=12"
}
},
+ "node_modules/data-bind-mapper": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/data-bind-mapper/-/data-bind-mapper-1.0.3.tgz",
+ "integrity": "sha512-QmU3lyEnbENQPo0M1F9BMu4s6cqNNp8iJA+b/HP2sSb7pf3dxwF3+EP1eO69rwBfH9kFJ1apmzrtogAmVt2/Xw==",
+ "license": "MIT",
+ "dependencies": {
+ "accessor-fn": "1"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/data-urls": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
@@ -3966,6 +4041,13 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -5123,6 +5205,13 @@
"node": ">= 8"
}
},
+ "node_modules/meshoptimizer": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/micromark": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",
@@ -5791,6 +5880,44 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/ngraph.events": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/ngraph.events/-/ngraph.events-1.4.0.tgz",
+ "integrity": "sha512-NeDGI4DSyjBNBRtA86222JoYietsmCXbs8CEB0dZ51Xeh4lhVl1y3wpWLumczvnha8sFQIW4E0vvVWwgmX2mGw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/ngraph.forcelayout": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/ngraph.forcelayout/-/ngraph.forcelayout-3.3.1.tgz",
+ "integrity": "sha512-MKBuEh1wujyQHFTW57y5vd/uuEOK0XfXYxm3lC7kktjJLRdt/KEKEknyOlc6tjXflqBKEuYBBcu7Ax5VY+S6aw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "ngraph.events": "^1.0.0",
+ "ngraph.merge": "^1.0.0",
+ "ngraph.random": "^1.0.0"
+ }
+ },
+ "node_modules/ngraph.graph": {
+ "version": "20.1.2",
+ "resolved": "https://registry.npmjs.org/ngraph.graph/-/ngraph.graph-20.1.2.tgz",
+ "integrity": "sha512-W/G3GBR3Y5UxMLHTUCPP9v+pbtpzwuAEIqP5oZV+9IwgxAIEZwh+Foc60iPc1idlnK7Zxu0p3puxAyNmDvBd0Q==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "ngraph.events": "^1.4.0"
+ }
+ },
+ "node_modules/ngraph.merge": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/ngraph.merge/-/ngraph.merge-1.0.0.tgz",
+ "integrity": "sha512-5J8YjGITUJeapsomtTALYsw7rFveYkM+lBj3QiYZ79EymQcuri65Nw3knQtFxQBU1r5iOaVRXrSwMENUPK62Vg==",
+ "license": "MIT"
+ },
+ "node_modules/ngraph.random": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/ngraph.random/-/ngraph.random-1.2.0.tgz",
+ "integrity": "sha512-4EUeAGbB2HWX9njd6bP6tciN6ByJfoaAvmVL9QTaZSeXrW46eNGA9GajiXiPBbvFqxUWFkEbyo6x5qsACUuVfA==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/node-releases": {
"version": "2.0.37",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz",
@@ -5947,6 +6074,18 @@
"node": ">= 6"
}
},
+ "node_modules/polished": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/polished/-/polished-4.3.1.tgz",
+ "integrity": "sha512-OBatVyC/N7SCW/FaDHrSd+vn0o5cS855TOmYi4OkdWUMSJCET/xip//ch8xGUvtr3i44X9LVyWwQlRMTN3pwSA==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.17.8"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.24",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.24.tgz",
@@ -6303,6 +6442,23 @@
"react": "*"
}
},
+ "node_modules/react-force-graph-3d": {
+ "version": "1.29.1",
+ "resolved": "https://registry.npmjs.org/react-force-graph-3d/-/react-force-graph-3d-1.29.1.tgz",
+ "integrity": "sha512-5Vp+PGpYnO+zLwgK2NvNqdXHvsWLrFzpDfJW1vUA1twjo9SPvXqfUYQrnRmAbD+K2tOxkZw1BkbH31l5b4TWHg==",
+ "license": "MIT",
+ "dependencies": {
+ "3d-force-graph": "^1.79",
+ "prop-types": "15",
+ "react-kapsule": "^2.5"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "react": "*"
+ }
+ },
"node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
@@ -7077,6 +7233,68 @@
"node": ">=0.8"
}
},
+ "node_modules/three": {
+ "version": "0.185.1",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
+ "integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==",
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/three-forcegraph": {
+ "version": "1.43.4",
+ "resolved": "https://registry.npmjs.org/three-forcegraph/-/three-forcegraph-1.43.4.tgz",
+ "integrity": "sha512-FtmiZP/T16ZQaHza3JDaDn0YTXFtg9e7pGnTeU8nzu0NNkx7MpWbF/GvmpbQsWHx3rukHtkRv1fTorLPB3FDEA==",
+ "license": "MIT",
+ "dependencies": {
+ "accessor-fn": "1",
+ "d3-array": "1 - 3",
+ "d3-force-3d": "2 - 3",
+ "d3-scale": "1 - 4",
+ "d3-scale-chromatic": "1 - 3",
+ "data-bind-mapper": "1",
+ "kapsule": "^1.16",
+ "ngraph.forcelayout": "3",
+ "ngraph.graph": "20",
+ "tinycolor2": "1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "three": ">=0.118.3"
+ }
+ },
+ "node_modules/three-render-objects": {
+ "version": "1.42.0",
+ "resolved": "https://registry.npmjs.org/three-render-objects/-/three-render-objects-1.42.0.tgz",
+ "integrity": "sha512-KYfkPrYGEbIK8ChFocWqOF1aAN80FBUBWVYB8mB2oBpVuVN+52FvvngVYB5ieFANQu7Rt21rPYZ/xKaAgVWWRQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@tweenjs/tween.js": "18 - 25",
+ "accessor-fn": "1",
+ "float-tooltip": "^1.7",
+ "kapsule": "^1.16",
+ "polished": "4"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "three": ">=0.179"
+ }
+ },
+ "node_modules/three-spritetext": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/three-spritetext/-/three-spritetext-1.10.0.tgz",
+ "integrity": "sha512-t08iP1FCU1lQh8T5MmCpdijKgas8GDHJE0LqMGBuVu3xqMMpFnEZhTlih7FlxLPQizHIGoumUSpfOlY1GO/Tgg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "three": ">=0.86.0"
+ }
+ },
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
diff --git a/jarvis/ui/web/frontend/package.json b/jarvis/ui/web/frontend/package.json
index 2d580f2b20..da9309fe92 100644
--- a/jarvis/ui/web/frontend/package.json
+++ b/jarvis/ui/web/frontend/package.json
@@ -35,6 +35,7 @@
"react-arborist": "^3.5.0",
"react-dom": "^18.3.1",
"react-force-graph-2d": "^1.25.0",
+ "react-force-graph-3d": "^1.29.1",
"react-markdown": "^9.1.0",
"react-use-websocket": "^4.13.0",
"recharts": "^3.8.1",
@@ -44,6 +45,8 @@
"remark-gfm": "^4.0.1",
"shiki": "^1.29.2",
"tailwind-merge": "^2.5.2",
+ "three": "^0.185.1",
+ "three-spritetext": "^1.10.0",
"zod": "^3.23.8",
"zustand": "^5.0.0"
},
@@ -53,6 +56,7 @@
"@types/node": "^25.6.0",
"@types/react": "^18.3.10",
"@types/react-dom": "^18.3.0",
+ "@types/three": "^0.185.3",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.20",
"jsdom": "^25.0.0",
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.dimension.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.dimension.test.tsx
new file mode 100644
index 0000000000..49b38241e2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.dimension.test.tsx
@@ -0,0 +1,162 @@
+/**
+ * The 2D/3D switch on the UltraWiki topic map.
+ *
+ * Same contract as the vault Memory Map's, and deliberately the same
+ * preference: flipping the switch here flips it there too, because one control
+ * labelled "3D" that only applies to the screen you happened to be on is two
+ * settings wearing one name. The chrome around the map — mention floor,
+ * legend, expand — has to survive the swap, since none of it is a property of
+ * the projection.
+ */
+import { afterEach, beforeEach, describe, 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";
+import {
+ GRAPH_DIMENSION_KEY,
+ resetWebglProbe,
+ setGraphDimension,
+} from "@/lib/graphDimension";
+
+class ResizeObserverPolyfill {
+ constructor(_callback: ResizeObserverCallback) {}
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+}
+if (typeof globalThis.ResizeObserver === "undefined") {
+ globalThis.ResizeObserver =
+ ResizeObserverPolyfill as unknown as typeof ResizeObserver;
+}
+
+vi.mock("react-force-graph-2d", async () => {
+ const { forwardRef } = await import("react");
+ return {
+ default: forwardRef(function ForceGraphMock(
+ _props: Record<string, unknown>,
+ _ref,
+ ) {
+ return <div data-testid="explore-graph-2d-stub" />;
+ }),
+ };
+});
+
+// three.js wants a WebGL context jsdom cannot give; which renderer mounts is
+// the whole question here, so a stand-in is the right amount of 3D.
+vi.mock("@/components/ultrawiki/EntityGraph3D", () => ({
+ EntityGraph3D: () => <div data-testid="explore-graph-3d-stub" />,
+}));
+
+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() {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({ ok: true, status: 200, json: async () => PAYLOAD })),
+ );
+}
+
+/** Make the WebGL probe answer yes, the way a real GPU-backed window does. */
+function pretendWebglWorks(): void {
+ vi.stubGlobal("WebGLRenderingContext", class {});
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
+ getExtension: () => null,
+ } as unknown as RenderingContext);
+ resetWebglProbe();
+}
+
+function renderGraph() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },
+ });
+ return render(
+ <QueryClientProvider client={client}>
+ <EntityGraph
+ minMentions={2}
+ onMinMentionsChange={() => {}}
+ selectedKey={null}
+ onSelect={() => {}}
+ />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+ setGraphDimension("2d");
+ resetWebglProbe();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ resetWebglProbe();
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+});
+
+describe("EntityGraph 2D/3D switch", () => {
+ it("draws the flat map by default", async () => {
+ pretendWebglWorks();
+ installFetch();
+ renderGraph();
+
+ expect(await screen.findByTestId("explore-graph-2d-stub")).toBeDefined();
+ expect(screen.queryByTestId("explore-graph-3d-stub")).toBeNull();
+ });
+
+ it("swaps to the 3D scene and keeps the map's own controls", async () => {
+ pretendWebglWorks();
+ installFetch();
+ renderGraph();
+ await screen.findByTestId("explore-graph-2d-stub");
+
+ fireEvent.click(screen.getByTestId("graph-dimension-3d"));
+
+ expect(await screen.findByTestId("explore-graph-3d-stub")).toBeDefined();
+ await waitFor(() => {
+ expect(screen.queryByTestId("explore-graph-2d-stub")).toBeNull();
+ });
+ // The mention floor and the expand button describe the data and the panel,
+ // not the projection — losing them on the way into 3D would be a downgrade.
+ expect(screen.getByTestId("explore-graph-floor")).toBeDefined();
+ expect(screen.getByTestId("explore-graph-expand-toggle")).toBeDefined();
+ expect(screen.getByTestId("explore-graph-shown")).toBeDefined();
+ });
+
+ it("stays flat without a WebGL context, whatever the stored preference says", async () => {
+ setGraphDimension("3d");
+ installFetch();
+ renderGraph();
+
+ expect(await screen.findByTestId("explore-graph-2d-stub")).toBeDefined();
+ expect(screen.queryByTestId("explore-graph-3d-stub")).toBeNull();
+ expect(
+ (screen.getByTestId("graph-dimension-3d") as HTMLButtonElement).disabled,
+ ).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.tsx
index 6ecc9db714..eb81692d1f 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph.tsx
@@ -23,7 +23,15 @@
* flex row sets that row's floor — which is how the whole section grew a
* horizontal scrollbar it could never shrink back out of.
*/
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import {
+ Suspense,
+ lazy,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useQuery } from "@tanstack/react-query";
import { Maximize2, Minimize2 } from "lucide-react";
import ForceGraph2D from "react-force-graph-2d";
@@ -36,12 +44,23 @@ import type {
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { sizeChanged } from "@/lib/wikiGraph";
+import { useGraphDimension } from "@/lib/graphDimension";
+import { GraphDimensionToggle } from "@/components/wiki/GraphDimensionToggle";
import { corpusSpan, nodeRadius, recencyTint } from "@/lib/entityGraph";
import {
fetchExploreEntity,
fetchExploreGraph,
} from "@/lib/ultrawikiExploreApi";
+// The WebGL renderer is the heaviest dependency in the app. Behind `lazy` it
+// is fetched the first time somebody switches this map into space, and never
+// otherwise — including for everyone who only ever reads the flat one.
+const EntityGraph3D = lazy(() =>
+ import("@/components/ultrawiki/EntityGraph3D").then((mod) => ({
+ default: mod.EntityGraph3D,
+ })),
+);
+
export interface EntityGraphProps {
minMentions: number;
onMinMentionsChange: (value: number) => void;
@@ -98,6 +117,10 @@ export function EntityGraph({
>(undefined);
const [size, setSize] = useState({ w: 0, h: 0 });
const [isExpanded, setIsExpanded] = useState(false);
+ // Flat canvas or WebGL scene — the same preference the vault Memory Map
+ // reads, already degraded back to flat where 3D cannot be rendered at all.
+ const { dimension } = useGraphDimension();
+ const isSpatial = dimension === "3d";
const query = useQuery({
queryKey: ["ultrawiki", "explore", "graph", minMentions],
@@ -208,6 +231,25 @@ export function EntityGraph({
>
{t("ultrawiki.explore.graph_empty")}
</p>
+ ) : isSpatial ? (
+ <Suspense
+ fallback={
+ <p
+ data-testid="explore-graph-3d-loading"
+ className="flex h-full items-center justify-center px-6 text-center text-xs text-muted-foreground"
+ >
+ {t("wiki_graph.loading_3d")}
+ </p>
+ }
+ >
+ <EntityGraph3D
+ graphData={graphData}
+ width={size.w}
+ height={size.h}
+ selectedKey={selectedKey}
+ onSelect={onSelect}
+ />
+ </Suspense>
) : (
<ForceGraph2D<RenderNode, RenderEdge>
ref={graphRef}
@@ -310,6 +352,8 @@ export function EntityGraph({
</p>
</div>
+ <div className="pointer-events-auto flex shrink-0 items-center gap-2">
+ <GraphDimensionToggle className="uw-stage-pill border-transparent bg-transparent" />
<button
type="button"
data-testid="explore-graph-expand-toggle"
@@ -334,6 +378,7 @@ export function EntityGraph({
<Maximize2 className="h-3.5 w-3.5" aria-hidden />
)}
</button>
+ </div>
</div>
<div className="pointer-events-none absolute inset-x-0 bottom-0 flex flex-wrap items-end justify-between gap-2 p-3">
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
new file mode 100644
index 0000000000..8be19bc302
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
@@ -0,0 +1,219 @@
+/**
+ * The topic map of UltraWiki Explore, drawn in space.
+ *
+ * Same nodes, same edges, same encoding as the flat map next door: size is how
+ * often a topic comes up, warmth is how recently — both straight out of
+ * `lib/entityGraph.ts`, so the two projections never disagree about what a
+ * pixel means. Only the layout gains an axis.
+ *
+ * This is where the third dimension earns the most. A co-occurrence network on
+ * a real corpus is far denser than a wikilink network — hundreds of topics,
+ * each tied to a dozen others — and on a plane the middle of it collapses into
+ * a solid mat. Given room to spread, the clusters that were hiding inside that
+ * mat come apart.
+ *
+ * Loaded lazily by `EntityGraph`, so the WebGL renderer only arrives when the
+ * switch says 3D.
+ */
+import { useCallback, useEffect, useRef } from "react";
+import ForceGraph3D from "react-force-graph-3d";
+import type { ForceGraphMethods, NodeObject } from "react-force-graph-3d";
+import type { Object3D } from "three";
+import SpriteText from "three-spritetext";
+
+import { CENTRING_STRENGTH, createCentringForce } from "@/lib/graphForces";
+
+/** Node shape the Explore map renders — mirrors EntityGraph's RenderNode. */
+export interface ExploreRenderNode {
+ id: string;
+ label: string;
+ mentions: number;
+ radius: number;
+ colour: string;
+}
+
+/** Edge shape the Explore map renders — weight is shared-moment count. */
+export interface ExploreRenderEdge {
+ source: string;
+ target: string;
+ weight: number;
+}
+
+/**
+ * Labelling floor, in graph units of node radius.
+ *
+ * The flat map shows a label once you zoom past 1.4×, for the selection, or
+ * for anything bigger than this. A 3D scene has no single zoom factor to test
+ * — every node sits at its own distance from the camera — so the size rule is
+ * the one that carries over, and it is the one that mattered: the topics that
+ * hold the network together stay named, the long tail stays quiet.
+ */
+const LABEL_RADIUS_FLOOR = 8;
+
+/** How much larger the selected topic draws, so it is findable at a glance. */
+const SELECTED_SCALE = 1.4;
+
+export interface EntityGraph3DProps {
+ graphData: { nodes: ExploreRenderNode[]; links: ExploreRenderEdge[] };
+ width: number;
+ height: number;
+ selectedKey: string | null;
+ onSelect: (key: string) => void;
+}
+
+export function EntityGraph3D({
+ graphData,
+ width,
+ height,
+ selectedKey,
+ onSelect,
+}: EntityGraph3DProps): JSX.Element {
+ const graphRef = useRef<
+ ForceGraphMethods<ExploreRenderNode, ExploreRenderEdge> | undefined
+ >(undefined);
+
+ // Accessors read the selection through a ref so choosing a topic does not
+ // swap the prop functions and make the renderer re-ingest every node.
+ const selectedRef = useRef(selectedKey);
+ selectedRef.current = selectedKey;
+
+ // Forces are set once per data generation, never per tick: d3's setters walk
+ // every node and every link, so per-frame calls are a tax on the simulation.
+ const forcesConfiguredRef = useRef(false);
+ useEffect(() => {
+ forcesConfiguredRef.current = false;
+ }, [graphData]);
+
+ /**
+ * A co-occurrence network is the densest thing this app draws, and the third
+ * axis only helps if the forces spend it. On the library defaults (charge
+ * −30, link 30) hundreds of topics tied to a dozen neighbours each settle
+ * into one marble — the very hairball the extra dimension was meant to open.
+ */
+ const configureForces = useCallback((): void => {
+ 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;
+ const charge = anyRef.d3Force?.("charge");
+ if (charge && typeof charge.strength === "function") {
+ charge.strength(-220);
+ // Bounded reach: past this distance a node is already outside the map
+ // and pushing it further only costs the camera its framing.
+ if (typeof charge.distanceMax === "function") charge.distanceMax(220);
+ }
+ const link = anyRef.d3Force?.("link");
+ if (link && typeof link.distance === "function") {
+ link.distance(55);
+ if (typeof link.strength === "function") link.strength(0.2);
+ }
+ // A topic mentioned once, sharing a moment with nothing, has no link to
+ // hold it. Without this it drifts out of the world and takes the camera
+ // with it — see lib/graphForces.ts.
+ anyRef.d3Force?.("centreGravity", createCentringForce(CENTRING_STRENGTH));
+ forcesConfiguredRef.current = true;
+ }, []);
+
+ // Framed once the layout has settled; fitting a still-collapsing bounding
+ // box would park the camera inside the cluster. The timer is the backstop
+ // for a simulation that never reports a stop.
+ const fitToView = useCallback((): void => {
+ graphRef.current?.zoomToFit(600, 60);
+ }, []);
+
+ useEffect(() => {
+ if (graphData.nodes.length === 0) return;
+ const timer = window.setTimeout(fitToView, 2600);
+ return () => window.clearTimeout(timer);
+ }, [graphData, fitToView]);
+
+ const nodeVal = useCallback((node: NodeObject<ExploreRenderNode>): number => {
+ const base = (node as ExploreRenderNode).radius;
+ const radius = node.id === selectedRef.current ? base * SELECTED_SCALE : base;
+ // Cubed, because the renderer takes the cube root to get a sphere radius —
+ // this is what makes the sphere exactly as wide as the flat map's dot.
+ return radius ** 3;
+ }, []);
+
+ const nodeColor = useCallback(
+ (node: NodeObject<ExploreRenderNode>) => (node as ExploreRenderNode).colour,
+ [],
+ );
+
+ const nodeLabel = useCallback(
+ (node: NodeObject<ExploreRenderNode>) => (node as ExploreRenderNode).label,
+ [],
+ );
+
+ const nodeThreeObject = useCallback(
+ (node: NodeObject<ExploreRenderNode>): SpriteText | null => {
+ const topic = node as ExploreRenderNode;
+ const selected = node.id === selectedRef.current;
+ if (!selected && topic.radius <= LABEL_RADIUS_FLOOR) return null;
+ const sprite = new SpriteText(topic.label);
+ // The selection has no ring to wear in space, so it wears the brightest
+ // label instead — white against the ash-to-yellow ramp every other node
+ // is tinted with.
+ sprite.color = selected ? "#ffffff" : "rgba(255,255,255,0.62)";
+ sprite.textHeight = selected ? 4 : 3;
+ const radius = selected ? topic.radius * SELECTED_SCALE : topic.radius;
+ sprite.position.set(0, -(radius + 2.5), 0);
+ return sprite;
+ },
+ [],
+ );
+
+ const handleNodeClick = useCallback(
+ (node: NodeObject<ExploreRenderNode>): void => {
+ if (node?.id !== undefined) onSelect(String(node.id));
+ },
+ [onSelect],
+ );
+
+ const linkWidth = useCallback(
+ (link: ExploreRenderEdge) => Math.min(0.2 + (link.weight ?? 1) * 0.08, 1.2),
+ [],
+ );
+
+ return (
+ <ForceGraph3D<ExploreRenderNode, ExploreRenderEdge>
+ ref={graphRef}
+ graphData={graphData}
+ width={width || undefined}
+ height={height || undefined}
+ backgroundColor="rgba(0,0,0,0)"
+ nodeId="id"
+ nodeRelSize={1}
+ nodeVal={nodeVal}
+ nodeColor={nodeColor}
+ nodeLabel={nodeLabel}
+ nodeOpacity={0.9}
+ nodeResolution={10}
+ // A falsy return means "no extra object, just draw the sphere" — the
+ // documented behaviour — but the typings insist on an Object3D. The cast
+ // is narrower than handing back an empty Object3D per unlabelled node,
+ // which on a corpus of a thousand topics is a thousand scene-graph
+ // entries and a thousand per-frame matrix updates for nothing.
+ nodeThreeObject={
+ nodeThreeObject as unknown as (
+ node: NodeObject<ExploreRenderNode>,
+ ) => Object3D
+ }
+ nodeThreeObjectExtend
+ linkColor={() => "rgba(255, 214, 10, 0.28)"}
+ linkOpacity={0.22}
+ linkWidth={linkWidth}
+ onNodeClick={handleNodeClick}
+ controlType="orbit"
+ // English-only overlay baked into the library; this app ships in three
+ // languages, and the switch's tooltip explains how to steer.
+ showNavInfo={false}
+ cooldownTicks={80}
+ onEngineTick={configureForces}
+ onEngineStop={fitToView}
+ />
+ );
+}
+
+export default EntityGraph3D;
diff --git a/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx b/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx
new file mode 100644
index 0000000000..42f006f860
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx
@@ -0,0 +1,81 @@
+/**
+ * The flat/space switch that sits on top of both memory maps.
+ *
+ * Two segments rather than a checkbox, because "off" is not what the other
+ * state is: 2D and 3D are two ways of reading the same network, and a switch
+ * labelled only "3D" makes the flat map look like the absence of a feature.
+ * Both labels are always visible, so the current state is readable without
+ * hovering anything.
+ *
+ * When the machine cannot give a WebGL context the 3D segment stays visible
+ * but disabled and says why. Hiding it would leave the user guessing whether
+ * the feature exists; letting them press it would paint a black rectangle.
+ */
+import { Box, Square } from "lucide-react";
+
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { useGraphDimension, type GraphDimension } from "@/lib/graphDimension";
+
+export interface GraphDimensionToggleProps {
+ /** Placement + surface styling; the host owns where this floats. */
+ className?: string;
+}
+
+export function GraphDimensionToggle({
+ className,
+}: GraphDimensionToggleProps): JSX.Element {
+ const t = useT();
+ const { dimension, setDimension, webglSupported } = useGraphDimension();
+
+ const segment = (value: GraphDimension) => {
+ const active = dimension === value;
+ const blocked = value === "3d" && !webglSupported;
+ const title = blocked
+ ? t("wiki_graph.dimension_unavailable")
+ : t(value === "3d" ? "wiki_graph.dimension_3d_title" : "wiki_graph.dimension_2d_title");
+ const Icon = value === "3d" ? Box : Square;
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={active}
+ aria-label={title}
+ title={title}
+ disabled={blocked}
+ data-testid={`graph-dimension-${value}`}
+ data-active={active ? "true" : "false"}
+ onClick={() => setDimension(value)}
+ className={cn(
+ "inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] font-medium tabular-nums transition-colors",
+ active
+ ? "bg-primary/15 text-foreground"
+ : "text-muted-foreground hover:text-foreground",
+ blocked && "cursor-not-allowed opacity-40 hover:text-muted-foreground",
+ )}
+ >
+ <Icon className="h-3 w-3" aria-hidden />
+ {t(value === "3d" ? "wiki_graph.dimension_3d" : "wiki_graph.dimension_2d")}
+ </button>
+ );
+ };
+
+ return (
+ <div
+ role="radiogroup"
+ aria-label={t("wiki_graph.dimension_label")}
+ data-testid="graph-dimension-toggle"
+ data-dimension={dimension}
+ data-webgl={webglSupported ? "true" : "false"}
+ className={cn(
+ "inline-flex items-center gap-0.5 rounded-md border border-border bg-card/80 p-0.5 backdrop-blur",
+ className,
+ )}
+ >
+ {segment("2d")}
+ {segment("3d")}
+ </div>
+ );
+}
+
+export default GraphDimensionToggle;
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.dimension.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.dimension.test.tsx
new file mode 100644
index 0000000000..bff08c04cd
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.dimension.test.tsx
@@ -0,0 +1,164 @@
+/**
+ * The 2D/3D switch on the Memory Map.
+ *
+ * Three things have to hold, and the third is the one that keeps the feature
+ * honest on machines that are not the developer's:
+ *
+ * 1. Flat is what you get by default — no WebGL chunk downloaded to read a
+ * map that never needed one.
+ * 2. Choosing 3D actually swaps the renderer, and the choice is remembered.
+ * 3. On a machine with no WebGL context to give, the 3D segment is visibly
+ * disabled and the map stays flat — even when a stored preference (say,
+ * from a profile synced off a machine that could) asks for 3D.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { PropsWithChildren } from "react";
+
+import { WikiGraph } from "@/components/wiki/WikiGraph";
+import {
+ GRAPH_DIMENSION_KEY,
+ resetWebglProbe,
+ setGraphDimension,
+} from "@/lib/graphDimension";
+
+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 <div data-testid="wiki-graph-2d-stub" />;
+ }),
+ };
+});
+
+// The real 3D component pulls in three.js and asks for a WebGL context, which
+// jsdom cannot give. What this file tests is which renderer gets mounted, so a
+// stand-in is exactly the right amount of 3D.
+vi.mock("@/components/wiki/WikiGraph3D", () => ({
+ WikiGraph3D: (props: { width: number; height: number }) => (
+ <div
+ data-testid="wiki-graph-3d-stub"
+ data-width={props.width}
+ data-height={props.height}
+ />
+ ),
+}));
+
+const PAYLOAD = {
+ ok: true,
+ nodes: [
+ { id: "ruben", kind: "entity", title: "Ruben" },
+ { id: "harald", kind: "entity", title: "Harald" },
+ ],
+ edges: [{ source: "ruben", target: "harald", context: "knows" }],
+ broken: [],
+};
+
+/** Make the WebGL probe answer yes, the way a real GPU-backed window does. */
+function pretendWebglWorks(): void {
+ vi.stubGlobal("WebGLRenderingContext", class {});
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
+ getExtension: () => null,
+ } as unknown as RenderingContext);
+ resetWebglProbe();
+}
+
+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>;
+}
+
+function renderGraph() {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ new Response(JSON.stringify(PAYLOAD), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ ),
+ );
+ return render(
+ <Wrapper client={makeClient()}>
+ <WikiGraph onNodeClick={() => {}} />
+ </Wrapper>,
+ );
+}
+
+beforeEach(() => {
+ forceGraphProps.length = 0;
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+ setGraphDimension("2d");
+ resetWebglProbe();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ resetWebglProbe();
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+});
+
+describe("WikiGraph 2D/3D switch", () => {
+ it("draws the flat map by default", async () => {
+ pretendWebglWorks();
+ renderGraph();
+
+ expect(await screen.findByTestId("wiki-graph-2d-stub")).toBeDefined();
+ expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
+ expect(
+ screen.getByTestId("graph-dimension-toggle").getAttribute("data-dimension"),
+ ).toBe("2d");
+ });
+
+ it("swaps to the 3D scene when the switch is flipped, and remembers it", async () => {
+ pretendWebglWorks();
+ renderGraph();
+ await screen.findByTestId("wiki-graph-2d-stub");
+
+ fireEvent.click(screen.getByTestId("graph-dimension-3d"));
+
+ expect(await screen.findByTestId("wiki-graph-3d-stub")).toBeDefined();
+ await waitFor(() => {
+ expect(screen.queryByTestId("wiki-graph-2d-stub")).toBeNull();
+ });
+ expect(window.localStorage.getItem(GRAPH_DIMENSION_KEY)).toBe("3d");
+ });
+
+ it("hands the measured canvas size to the 3D scene", async () => {
+ pretendWebglWorks();
+ setGraphDimension("3d");
+ renderGraph();
+
+ const stub = await screen.findByTestId("wiki-graph-3d-stub");
+ expect(Number(stub.getAttribute("data-width"))).toBeGreaterThan(0);
+ expect(Number(stub.getAttribute("data-height"))).toBeGreaterThan(0);
+ });
+
+ it("stays flat and disables the 3D segment without a WebGL context", async () => {
+ // No WebGL globals stubbed: this is the headless/locked-down machine.
+ setGraphDimension("3d");
+ renderGraph();
+
+ expect(await screen.findByTestId("wiki-graph-2d-stub")).toBeDefined();
+ expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
+ const segment = screen.getByTestId("graph-dimension-3d") as HTMLButtonElement;
+ expect(segment.disabled).toBe(true);
+ expect(segment.getAttribute("title")).toContain("cannot render 3D");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
index ff5519a146..43516dd374 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
@@ -1,13 +1,28 @@
-// Force-directed 2D graph of the Obsidian-vault wikilink network.
+// Force-directed graph of the Obsidian-vault wikilink network.
//
// Owned by Agent C of Phase B3. Pure view component — it fetches
// `/api/wiki/graph` via React Query and renders nodes/edges with
// `react-force-graph-2d`. No filter chips, no custom force tweaks; this is the
// landing view inside the Wiki tab, so it stays minimal and fast.
//
+// This file owns the DATA and the chrome; the projection is a choice. The flat
+// canvas below is the default and lives here; the 3D scene is `WikiGraph3D`,
+// lazily loaded so nobody downloads a WebGL renderer to read a flat map. Both
+// draw the same nodes, the same colours and the same size encoding out of
+// `lib/wikiGraph.ts`, so switching between them changes the projection and
+// nothing else.
+//
// Visual contract: docs/plans/b3/00-OVERVIEW.md §3. Node colours live in
// `lib/wikiGraph.ts:NODE_COLOUR` — never hardcoded here.
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ Suspense,
+ lazy,
+ 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";
@@ -16,15 +31,27 @@ import {
BROKEN_EDGE_COLOUR,
clampCenterToView,
NODE_COLOUR,
+ nodeSizeScore,
sizeChanged,
toGraphData,
type RenderEdge,
type RenderNode,
type WikiGraphPayload,
} from "@/lib/wikiGraph";
+import { useGraphDimension } from "@/lib/graphDimension";
+import { GraphDimensionToggle } from "@/components/wiki/GraphDimensionToggle";
import { useEventStore } from "@/store/events";
import { useT, useUiLanguage } from "@/i18n";
+// Three.js and the WebGL renderer are by far the heaviest thing this app can
+// pull in. Keeping them behind `lazy` means the chunk is fetched the first
+// time somebody actually asks for the 3D map, and never otherwise.
+const WikiGraph3D = lazy(() =>
+ import("@/components/wiki/WikiGraph3D").then((mod) => ({
+ default: mod.WikiGraph3D,
+ })),
+);
+
const GRAPH_QUERY_KEY = ["wiki", "graph"] as const;
/** Extra render-loop controls the library exposes but the typings omit. */
@@ -83,13 +110,14 @@ 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;
+/**
+ * Node radius in graph units — shared by the hit area and the label offset.
+ * Range 1.0 … 2.6, so with `nodeRelSize=2` a dot is roughly 2.8 px (leaf) to
+ * 4.6 px (hub). The scale itself lives in `lib/wikiGraph.ts` so the 3D map
+ * sizes its spheres by exactly the same rule.
+ */
+function sizeOf(node: RenderNode, isActive: boolean): number {
+ return nodeSizeScore(node.backlinkCount ?? 0, isActive);
}
export interface WikiGraphProps {
@@ -129,6 +157,14 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
if (slug) onNodeClickRef.current(slug);
}, []);
+ // Flat canvas or WebGL scene. Shared with the UltraWiki map, and already
+ // degraded back to flat on a machine that cannot render 3D at all.
+ const { dimension } = useGraphDimension();
+ const isSpatial = dimension === "3d";
+ // The Center button drives two very different cameras. The flat one is reset
+ // imperatively below; the 3D scene watches this counter and re-frames itself.
+ const [resetTick, setResetTick] = useState(0);
+
const { data, isLoading, isError } = useQuery({
queryKey: GRAPH_QUERY_KEY,
queryFn: fetchGraph,
@@ -394,6 +430,10 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
);
const handleResetView = useCallback((): void => {
+ // Bumped FIRST, because everything below is flat-canvas work that bails
+ // out the moment the 3D scene is the one on screen. The scene re-frames
+ // its own camera off this counter.
+ setResetTick((tick) => tick + 1);
const ref = graphRef.current;
if (!ref) return;
// User explicitly asked for centring → clear the pan-touched flag
@@ -577,7 +617,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
const nodeVal = useCallback(
(node: NodeObject<RenderNode>) =>
- nodeSizeScore(node as RenderNode, node.id === highlightRef.current),
+ sizeOf(node as RenderNode, node.id === highlightRef.current),
[],
);
@@ -599,7 +639,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
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;
+ const radius = sizeOf(node as RenderNode, isActive) * 2;
if (isActive) {
ctx.save();
ctx.beginPath();
@@ -750,15 +790,18 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
role="group"
aria-label={t("wiki_graph.relationship_graph")}
>
- <button
- type="button"
- onClick={handleResetView}
- data-testid="wiki-graph-reset-view"
- className="absolute top-3 right-3 z-10 rounded-md border border-border bg-card/80 px-3 py-1.5 text-xs text-muted-foreground backdrop-blur transition hover:text-foreground hover:bg-card"
- title={t("wiki_graph.reset_view_title")}
- >
- {t("wiki_graph.center")}
- </button>
+ <div className="absolute top-3 right-3 z-10 flex items-center gap-2">
+ <GraphDimensionToggle />
+ <button
+ type="button"
+ onClick={handleResetView}
+ data-testid="wiki-graph-reset-view"
+ className="rounded-md border border-border bg-card/80 px-3 py-1.5 text-xs text-muted-foreground backdrop-blur transition hover:text-foreground hover:bg-card"
+ title={t("wiki_graph.reset_view_title")}
+ >
+ {t("wiki_graph.center")}
+ </button>
+ </div>
<ul data-testid="wiki-graph-node-list" className="sr-only">
{nodeListItems}
</ul>
@@ -766,6 +809,29 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
{edgeListItems}
</ul>
+ {isSpatial ? (
+ <Suspense
+ fallback={
+ <div
+ data-testid="wiki-graph-3d-loading"
+ className="flex h-full items-center justify-center text-sm text-muted-foreground"
+ >
+ {t("wiki_graph.loading_3d")}
+ </div>
+ }
+ >
+ <WikiGraph3D
+ graphData={graphData}
+ width={winSize.w}
+ height={winSize.h}
+ highlightSlug={highlightSlug}
+ onNodeClick={selectNode}
+ resetSignal={resetTick}
+ nodeLabel={nodeLabel}
+ linkLabel={linkLabel}
+ />
+ </Suspense>
+ ) : (
<ForceGraph2D<RenderNode, RenderEdge>
// NO remount key. react-force-graph-2d (via react-kapsule) maps the
// width/height props onto live `.width()/.height()` calls that resize
@@ -826,6 +892,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E
onEngineStop={handleEngineStop}
onNodeClick={handleNodeClick}
/>
+ )}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
new file mode 100644
index 0000000000..d05c30c772
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
@@ -0,0 +1,261 @@
+/**
+ * The vault Memory Map, drawn in space instead of on a plane.
+ *
+ * This is the SAME graph as `WikiGraph`'s flat canvas — same request, same
+ * nodes, same colours, same size encoding out of `lib/wikiGraph.ts`. Only the
+ * projection changes, which is the whole point: a dense wikilink network runs
+ * out of room in two dimensions long before it runs out of structure, and
+ * clusters that overlap into a hairball on a plane pull apart when the layout
+ * has a third axis to spend.
+ *
+ * It is loaded lazily and only ever mounted while the 2D/3D switch says 3D, so
+ * the WebGL renderer (the largest dependency in the app by a wide margin) is
+ * never downloaded by someone who reads the flat map.
+ *
+ * Two things the flat map does that space cannot, and what replaces them:
+ * - Dashed lines for unresolved wikilinks. The 3D renderer draws solid tubes
+ * only, so a broken link keeps its rose colour and loses its arrow instead.
+ * - Always-on labels. Text in a 3D scene is a textured sprite, one draw call
+ * each, and a thousand of them turn a smooth orbit into a slideshow — so
+ * labels go to the nodes that carry the network plus whatever is selected.
+ */
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import ForceGraph3D from "react-force-graph-3d";
+import type { ForceGraphMethods, NodeObject } from "react-force-graph-3d";
+import type { Object3D } from "three";
+import SpriteText from "three-spritetext";
+
+import {
+ BROKEN_EDGE_COLOUR,
+ NODE_COLOUR,
+ nodeSizeScore,
+ type RenderEdge,
+ type RenderNode,
+} from "@/lib/wikiGraph";
+import { CENTRING_STRENGTH, createCentringForce } from "@/lib/graphForces";
+
+/** Sphere radius in graph units for a node whose size score is 1.0. */
+const NODE_REL_SIZE = 3;
+
+/**
+ * Above this many nodes, only hubs and the selection get a text sprite.
+ * Below it every node is labelled, the way the flat map does it.
+ */
+const LABEL_ALL_BELOW = 220;
+
+/** A hub, once the scene is too crowded to label everything. */
+const HUB_BACKLINKS = 2;
+
+export interface WikiGraph3DProps {
+ graphData: { nodes: RenderNode[]; links: RenderEdge[] };
+ width: number;
+ height: number;
+ highlightSlug?: string;
+ onNodeClick: (slug: string) => void;
+ /** Any change re-frames the camera; the host's Center button bumps it. */
+ resetSignal: number;
+ /** Tooltip text for a node — same wording as the flat map's. */
+ nodeLabel: (node: NodeObject<RenderNode>) => string;
+ /** Tooltip text for an edge. */
+ linkLabel: (link: RenderEdge) => string;
+}
+
+export function WikiGraph3D({
+ graphData,
+ width,
+ height,
+ highlightSlug,
+ onNodeClick,
+ resetSignal,
+ nodeLabel,
+ linkLabel,
+}: WikiGraph3DProps): JSX.Element {
+ const graphRef = useRef<ForceGraphMethods<RenderNode, RenderEdge> | undefined>(
+ undefined,
+ );
+
+ // Read through a ref for the same reason the flat map does: swapping the
+ // accessor functions makes the library re-ingest its whole accessor set, and
+ // a selection change only needs the next painted frame to read a new value.
+ const highlightRef = useRef(highlightSlug);
+ highlightRef.current = highlightSlug;
+
+ const labelEverything = graphData.nodes.length <= LABEL_ALL_BELOW;
+
+ // Forces are set once per data generation, never per tick — d3's setters
+ // re-initialise the force over every node and every link, so calling them
+ // per frame is an O(n) tax on the simulation. Same discipline as the flat
+ // map's `configureForces`.
+ const forcesConfiguredRef = useRef(false);
+ useEffect(() => {
+ forcesConfiguredRef.current = false;
+ }, [graphData]);
+
+ /**
+ * A third axis does not spread a dense graph on its own — the FORCES have to
+ * want the room.
+ *
+ * The flat map tunes its own (charge −180, link 55) and those numbers live
+ * inside the 2D renderer, so a 3D scene left on the library defaults
+ * (charge −30, link 30) collapsed a vault of a thousand wikilinks into one
+ * marble. Space costs repulsion: a stronger charge and a longer, slacker
+ * link are what turn the marble back into a network you can fly through.
+ */
+ const configureForces = useCallback((): void => {
+ 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;
+ const charge = anyRef.d3Force?.("charge");
+ if (charge && typeof charge.strength === "function") {
+ charge.strength(-250);
+ // Same reach as the flat map's. A larger radius keeps pushing a node
+ // that is already outside the cluster, which is how a single unlinked
+ // page ends up a long way from everything and drags the camera with it.
+ if (typeof charge.distanceMax === "function") charge.distanceMax(220);
+ }
+ const link = anyRef.d3Force?.("link");
+ if (link && typeof link.distance === "function") {
+ link.distance(60);
+ // Slacker than the flat map's 0.85: in three dimensions a stiff link
+ // pulls the cluster back into the ball the repulsion just opened.
+ if (typeof link.strength === "function") link.strength(0.25);
+ }
+ // Bounds the world. Without it a single unlinked page drifts until it is
+ // out of everyone's reach, and `zoomToFit` — which frames every node —
+ // renders the entire vault as a marble in an empty room.
+ anyRef.d3Force?.("centreGravity", createCentringForce(CENTRING_STRENGTH));
+ forcesConfiguredRef.current = true;
+ }, []);
+
+ // Frame the whole network once the layout has settled — `zoomToFit` on a
+ // still-collapsing bounding box lands the camera inside the cluster. The
+ // timer is the backstop for a simulation that never reports a stop.
+ const fitToView = useCallback((): void => {
+ graphRef.current?.zoomToFit(600, 80);
+ }, []);
+
+ useEffect(() => {
+ if (graphData.nodes.length === 0) return;
+ const timer = window.setTimeout(fitToView, 2600);
+ return () => window.clearTimeout(timer);
+ }, [graphData, resetSignal, fitToView]);
+
+ const handleNodeClick = useCallback(
+ (node: NodeObject<RenderNode>): void => {
+ const id = (node.id as string | undefined) ?? "";
+ if (id) onNodeClick(id);
+ },
+ [onNodeClick],
+ );
+
+ const nodeVal = useCallback((node: NodeObject<RenderNode>): number => {
+ const score = nodeSizeScore(
+ (node as RenderNode).backlinkCount ?? 0,
+ node.id === highlightRef.current,
+ );
+ // The renderer takes the CUBE ROOT of this to get a sphere radius, so
+ // cubing here is what makes `nodeSizeScore` mean the same thing in both
+ // maps: radius = NODE_REL_SIZE * score, exactly as on the plane.
+ return score ** 3;
+ }, []);
+
+ const nodeColor = useCallback(
+ (node: NodeObject<RenderNode>) =>
+ (node as RenderNode).colour ?? NODE_COLOUR.entity ?? "#8b95a7",
+ [],
+ );
+
+ const nodeThreeObject = useCallback(
+ (node: NodeObject<RenderNode>): SpriteText | null => {
+ const rendered = node as RenderNode;
+ const isActive = node.id === highlightRef.current;
+ const backlinks = rendered.backlinkCount ?? 0;
+ if (!labelEverything && !isActive && backlinks < HUB_BACKLINKS) {
+ // No extra object — the sphere the renderer draws is the whole node.
+ return null;
+ }
+ const label = rendered.title || String(node.id ?? "");
+ if (!label) return null;
+ const sprite = new SpriteText(label);
+ sprite.color = isActive ? "#e6ecf5" : "#a8b0c0";
+ sprite.textHeight = isActive ? 3.2 : 2.4;
+ // Clear of the sphere, so a hub's label does not sit inside its own dot.
+ const radius = NODE_REL_SIZE * nodeSizeScore(backlinks, isActive);
+ sprite.position.set(0, -(radius + 2), 0);
+ return sprite;
+ },
+ [labelEverything],
+ );
+
+ const linkColor = useCallback(
+ (link: RenderEdge) =>
+ link.broken ? BROKEN_EDGE_COLOUR : "rgba(106, 169, 255, 0.55)",
+ [],
+ );
+
+ // An unresolved link points at a page that does not exist, so an arrowhead
+ // claiming a destination would be the wrong story; the rose colour carries
+ // it instead — the same signal the flat map's dashes carry.
+ const linkArrowLength = useCallback(
+ (link: RenderEdge) => (link.broken ? 0 : 3.5),
+ [],
+ );
+
+ const linkArrowColor = useCallback(
+ () => "rgba(106, 169, 255, 0.85)",
+ [],
+ );
+
+ const data = useMemo(() => graphData, [graphData]);
+
+ return (
+ <ForceGraph3D<RenderNode, RenderEdge>
+ ref={graphRef}
+ graphData={data}
+ width={width}
+ height={height}
+ backgroundColor="rgba(0,0,0,0)"
+ nodeId="id"
+ nodeLabel={nodeLabel}
+ nodeRelSize={NODE_REL_SIZE}
+ nodeVal={nodeVal}
+ nodeColor={nodeColor}
+ nodeOpacity={0.92}
+ nodeResolution={12}
+ // A falsy return means "no extra object, just draw the sphere" — the
+ // documented behaviour — but the typings insist on an Object3D. The cast
+ // is narrower than handing back an empty Object3D per unlabelled node,
+ // which would buy a scene-graph entry and a per-frame matrix update on
+ // exactly the crowded graphs where the labels were dropped for speed.
+ nodeThreeObject={
+ nodeThreeObject as unknown as (node: NodeObject<RenderNode>) => Object3D
+ }
+ nodeThreeObjectExtend
+ linkLabel={linkLabel}
+ linkColor={linkColor}
+ linkOpacity={0.5}
+ linkWidth={0.4}
+ linkDirectionalArrowLength={linkArrowLength}
+ linkDirectionalArrowRelPos={0.85}
+ linkDirectionalArrowColor={linkArrowColor}
+ onNodeClick={handleNodeClick}
+ // Drag to rotate, wheel to zoom, right-drag to pan — the mapping people
+ // already know from every other 3D viewer.
+ controlType="orbit"
+ // The built-in hint overlay is English-only text baked into the library,
+ // and this app ships in three languages. The switch's own tooltip says
+ // how to steer instead.
+ showNavInfo={false}
+ cooldownTicks={200}
+ d3VelocityDecay={0.6}
+ d3AlphaDecay={0.04}
+ warmupTicks={40}
+ onEngineTick={configureForces}
+ onEngineStop={fitToView}
+ />
+ );
+}
+
+export default WikiGraph3D;
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 895697f4fc..2d29f42fc1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2272,7 +2272,14 @@
"node_details": "{0} ({1}) · {2} {3}",
"backlink_one": "Backlink",
"backlink_many": "Backlinks",
- "unresolved": "nicht aufgelöst"
+ "unresolved": "nicht aufgelöst",
+ "dimension_label": "Kartenansicht",
+ "dimension_2d": "2D",
+ "dimension_3d": "3D",
+ "dimension_2d_title": "Karte flach anzeigen",
+ "dimension_3d_title": "Karte im Raum anzeigen, zum Drehen ziehen",
+ "dimension_unavailable": "Dieser Rechner kann keine 3D-Grafik darstellen, die Karte bleibt flach.",
+ "loading_3d": "3D-Karte wird geladen…"
},
"tree_sidebar": {
"load_error": "Konnte das Wiki nicht laden.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 94026b7521..8411273120 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2273,7 +2273,14 @@
"node_details": "{0} ({1}) · {2} {3}",
"backlink_one": "backlink",
"backlink_many": "backlinks",
- "unresolved": "unresolved"
+ "unresolved": "unresolved",
+ "dimension_label": "Map view",
+ "dimension_2d": "2D",
+ "dimension_3d": "3D",
+ "dimension_2d_title": "Show the map flat",
+ "dimension_3d_title": "Show the map in space, rotate it by dragging",
+ "dimension_unavailable": "This machine cannot render 3D graphics, so the map stays flat.",
+ "loading_3d": "Loading the 3D map…"
},
"tree_sidebar": {
"load_error": "Could not load the wiki.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 78ca0f7d5a..9bec1d647d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2272,7 +2272,14 @@
"node_details": "{0} ({1}) · {2} {3}",
"backlink_one": "retroenlace",
"backlink_many": "retroenlaces",
- "unresolved": "sin resolver"
+ "unresolved": "sin resolver",
+ "dimension_label": "Vista del mapa",
+ "dimension_2d": "2D",
+ "dimension_3d": "3D",
+ "dimension_2d_title": "Mostrar el mapa plano",
+ "dimension_3d_title": "Mostrar el mapa en el espacio, arrastra para girarlo",
+ "dimension_unavailable": "Este equipo no puede representar gráficos 3D, así que el mapa se queda plano.",
+ "loading_3d": "Cargando el mapa 3D…"
},
"tree_sidebar": {
"load_error": "No se pudo cargar el wiki.",
diff --git a/jarvis/ui/web/frontend/src/lib/graphDimension.test.ts b/jarvis/ui/web/frontend/src/lib/graphDimension.test.ts
new file mode 100644
index 0000000000..c8f81b2ae1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/graphDimension.test.ts
@@ -0,0 +1,72 @@
+/**
+ * The flat/space preference and the honesty rule attached to it.
+ *
+ * The rule that matters is the last one: a machine that cannot give a WebGL
+ * context must never be handed a 3D scene. It would paint nothing, and a map
+ * that silently paints nothing is worse than a flat map that works.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import {
+ DEFAULT_GRAPH_DIMENSION,
+ GRAPH_DIMENSION_KEY,
+ parseGraphDimension,
+ readGraphDimension,
+ resolveGraphDimension,
+ writeGraphDimension,
+} from "@/lib/graphDimension";
+
+beforeEach(() => {
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+});
+
+afterEach(() => {
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+});
+
+describe("parseGraphDimension", () => {
+ it("accepts the two known values", () => {
+ expect(parseGraphDimension("2d")).toBe("2d");
+ expect(parseGraphDimension("3d")).toBe("3d");
+ });
+
+ it("treats anything else as unset", () => {
+ expect(parseGraphDimension(null)).toBeNull();
+ expect(parseGraphDimension("")).toBeNull();
+ expect(parseGraphDimension("4d")).toBeNull();
+ expect(parseGraphDimension("3D")).toBeNull();
+ });
+});
+
+describe("readGraphDimension", () => {
+ it("falls back to flat when nothing is stored", () => {
+ expect(readGraphDimension()).toBe(DEFAULT_GRAPH_DIMENSION);
+ expect(DEFAULT_GRAPH_DIMENSION).toBe("2d");
+ });
+
+ it("round-trips a stored preference", () => {
+ writeGraphDimension("3d");
+ expect(window.localStorage.getItem(GRAPH_DIMENSION_KEY)).toBe("3d");
+ expect(readGraphDimension()).toBe("3d");
+ });
+
+ it("ignores a corrupted value instead of failing", () => {
+ window.localStorage.setItem(GRAPH_DIMENSION_KEY, "hologram");
+ expect(readGraphDimension()).toBe("2d");
+ });
+});
+
+describe("resolveGraphDimension", () => {
+ it("honours 3D when the machine can render it", () => {
+ expect(resolveGraphDimension("3d", true)).toBe("3d");
+ });
+
+ it("degrades 3D to the flat map when WebGL is missing", () => {
+ expect(resolveGraphDimension("3d", false)).toBe("2d");
+ });
+
+ it("leaves the flat map alone either way", () => {
+ expect(resolveGraphDimension("2d", true)).toBe("2d");
+ expect(resolveGraphDimension("2d", false)).toBe("2d");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/graphDimension.ts b/jarvis/ui/web/frontend/src/lib/graphDimension.ts
new file mode 100644
index 0000000000..11a38bcd29
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/graphDimension.ts
@@ -0,0 +1,178 @@
+/**
+ * Flat map or space: which dimension the memory maps are drawn in.
+ *
+ * Both graph surfaces — the vault Memory Map in the normal Wiki and the topic
+ * map in UltraWiki Explore — read this one preference, so the choice follows
+ * the user around instead of having to be made twice. It is a view preference,
+ * not knowledge: it lives in localStorage next to the other per-machine view
+ * settings (`jarvis.agenticIde.workspaceView`, `jarvis.ui.sound`) rather than
+ * in `jarvis.toml`, because a monitor that can render a 3D scene is a property
+ * of the machine in front of the user, not of the install.
+ *
+ * The WebGL probe is the honest half of the feature. 3D needs a hardware
+ * (or software-emulated) graphics context, and there are real machines that
+ * cannot give one: a locked-down WebView, a VM with no GPU passthrough, a
+ * remote desktop session. Offering a button that silently paints nothing there
+ * would be worse than not offering it, so the probe decides whether the switch
+ * is live and the UI says why when it is not.
+ *
+ * Pure + framework-free apart from the tiny store at the bottom, so the
+ * parsing and fallback rules are unit-testable without a renderer.
+ */
+import { create } from "zustand";
+
+/** `2d` is the flat canvas map, `3d` the WebGL scene. */
+export type GraphDimension = "2d" | "3d";
+
+/** Where the preference is stored. Shared by both graph surfaces. */
+export const GRAPH_DIMENSION_KEY = "jarvis.wiki.graphDimension";
+
+/** Flat stays the default: it works on every machine and costs no download. */
+export const DEFAULT_GRAPH_DIMENSION: GraphDimension = "2d";
+
+/** Narrow an arbitrary stored string; anything else is treated as unset. */
+export function parseGraphDimension(raw: string | null): GraphDimension | null {
+ return raw === "2d" || raw === "3d" ? raw : null;
+}
+
+/**
+ * What to actually render, given the stored wish and what the machine can do.
+ *
+ * A stored `3d` on a machine without WebGL degrades to the flat map instead of
+ * a black rectangle. The preference itself is left alone — plug the same
+ * profile into a machine that can render it and 3D comes back.
+ */
+export function resolveGraphDimension(
+ stored: GraphDimension,
+ webglSupported: boolean,
+): GraphDimension {
+ return stored === "3d" && !webglSupported ? "2d" : stored;
+}
+
+/** The stored preference, or the default when storage is unavailable/empty. */
+export function readGraphDimension(): GraphDimension {
+ try {
+ return (
+ parseGraphDimension(window.localStorage.getItem(GRAPH_DIMENSION_KEY)) ??
+ DEFAULT_GRAPH_DIMENSION
+ );
+ } catch {
+ // Private mode / storage disabled — a view preference is never worth
+ // taking the Wiki tab down for.
+ return DEFAULT_GRAPH_DIMENSION;
+ }
+}
+
+/** Persist the preference; a storage failure only costs the memory of it. */
+export function writeGraphDimension(value: GraphDimension): void {
+ try {
+ window.localStorage.setItem(GRAPH_DIMENSION_KEY, value);
+ } catch {
+ // Same reasoning as readGraphDimension: never fatal.
+ }
+}
+
+// Creating a WebGL context is not free and browsers cap how many can exist at
+// once, so the answer is probed once per page and remembered.
+let webglProbe: boolean | null = null;
+
+/**
+ * Can this machine render a WebGL scene at all?
+ *
+ * Deliberately a CAPABILITY probe rather than a platform or browser check: the
+ * same build runs inside the desktop WebView on Windows, macOS and Linux, in a
+ * plain browser tab against `--dev`, and in jsdom during tests. Only actually
+ * asking for a context tells the truth in all four.
+ */
+export function detectWebgl(): boolean {
+ if (webglProbe !== null) return webglProbe;
+ webglProbe = probeWebgl();
+ return webglProbe;
+}
+
+/** Drop the cached probe result. Exists for tests that switch the answer. */
+export function resetWebglProbe(): void {
+ webglProbe = null;
+}
+
+function probeWebgl(): boolean {
+ try {
+ if (typeof document === "undefined") return false;
+ // Ask the cheap question first. jsdom (and any environment without WebGL
+ // at all) does not define these constructors, and calling `getContext` on
+ // its canvas raises a "not implemented" error into the console — noise
+ // during every test run for an answer we already have.
+ if (
+ typeof WebGLRenderingContext === "undefined" &&
+ typeof WebGL2RenderingContext === "undefined"
+ ) {
+ return false;
+ }
+ const canvas = document.createElement("canvas");
+ const context =
+ (canvas.getContext("webgl2") as WebGLRenderingContext | null) ??
+ (canvas.getContext("webgl") as WebGLRenderingContext | null);
+ if (!context) return false;
+ // Hand the context straight back. Without this the probe permanently
+ // occupies one of the handful of contexts a browser allows per page, and
+ // the graph itself would be the one that fails to get one.
+ const lose = context.getExtension("WEBGL_lose_context") as {
+ loseContext?: () => void;
+ } | null;
+ lose?.loseContext?.();
+ return true;
+ } catch {
+ // Some environments throw rather than return null (jsdom, hardened
+ // WebViews). Either way the answer is "no 3D here".
+ return false;
+ }
+}
+
+interface GraphDimensionStore {
+ /** What the user asked for, regardless of what the machine can do. */
+ preference: GraphDimension;
+ setPreference: (value: GraphDimension) => void;
+}
+
+const useGraphDimensionStore = create<GraphDimensionStore>((set) => ({
+ preference: readGraphDimension(),
+ setPreference: (value) => {
+ writeGraphDimension(value);
+ set({ preference: value });
+ },
+}));
+
+/**
+ * Set the preference from outside React — the same path the switch takes, so
+ * every mounted graph reacts. Used by non-component callers and by tests that
+ * need a surface to start in 3D.
+ */
+export function setGraphDimension(value: GraphDimension): void {
+ useGraphDimensionStore.getState().setPreference(value);
+}
+
+export interface GraphDimensionHandle {
+ /** The dimension to render — already degraded when WebGL is missing. */
+ dimension: GraphDimension;
+ /** What the user last chose, even if it cannot be honoured right now. */
+ preference: GraphDimension;
+ setDimension: (value: GraphDimension) => void;
+ webglSupported: boolean;
+}
+
+/**
+ * The switch state, shared by every graph on screen: flipping it in UltraWiki
+ * Explore also flips the vault Memory Map, which is what a single preference
+ * called "3D" has to mean.
+ */
+export function useGraphDimension(): GraphDimensionHandle {
+ const preference = useGraphDimensionStore((s) => s.preference);
+ const setDimension = useGraphDimensionStore((s) => s.setPreference);
+ const webglSupported = detectWebgl();
+ return {
+ dimension: resolveGraphDimension(preference, webglSupported),
+ preference,
+ setDimension,
+ webglSupported,
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/lib/graphForces.ts b/jarvis/ui/web/frontend/src/lib/graphForces.ts
new file mode 100644
index 0000000000..10125a568b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/graphForces.ts
@@ -0,0 +1,78 @@
+/**
+ * A soft pull toward the origin, for force layouts that would otherwise let a
+ * node drift out of the world.
+ *
+ * Why this has to exist: a node with no links feels repulsion and nothing
+ * else. It accelerates away from the cluster until it is out of every other
+ * node's reach, and then it simply stays there. On a flat canvas that is a dot
+ * near the edge; in a 3D scene it is worse, because "frame everything" is how
+ * the camera decides where to sit — one stray node ten cluster-widths out and
+ * the whole network is rendered as a marble in the middle of an empty room.
+ * A vault with a single unlinked page is enough to trigger it.
+ *
+ * The library's own `center` force does not solve this: it translates every
+ * node so the CENTROID lands on the origin, which moves the stray node and the
+ * cluster together and changes nothing about the distance between them. What
+ * is needed is a per-node pull, which is what this is — d3's `forceX(0)`,
+ * `forceY(0)` and `forceZ(0)` in one pass, written out rather than pulled in
+ * as a dependency because it is nine lines of arithmetic.
+ *
+ * Strength is deliberately tiny. It has to be weaker than the repulsion
+ * between neighbours (or the layout collapses into a ball) while still being
+ * the only force acting a long way out, where repulsion has fallen off. That
+ * is what bounds the world without compressing it.
+ */
+
+/** The mutable slice of a node a force integrates over. */
+interface SimNode {
+ x?: number;
+ y?: number;
+ z?: number;
+ vx?: number;
+ vy?: number;
+ vz?: number;
+}
+
+/** A d3-force-shaped force: callable, with an `initialize` hook. */
+export interface CentringForce {
+ (alpha: number): void;
+ initialize: (nodes: SimNode[]) => void;
+}
+
+/**
+ * Build the pull.
+ *
+ * @param strength velocity change per unit of distance per tick, scaled by the
+ * simulation's alpha so it fades out with the rest of the layout.
+ */
+export function createCentringForce(strength: number): CentringForce {
+ let nodes: SimNode[] = [];
+
+ const force = ((alpha: number): void => {
+ const k = strength * alpha;
+ if (k === 0) return;
+ for (const node of nodes) {
+ node.vx = (node.vx ?? 0) - (node.x ?? 0) * k;
+ node.vy = (node.vy ?? 0) - (node.y ?? 0) * k;
+ node.vz = (node.vz ?? 0) - (node.z ?? 0) * k;
+ }
+ }) as CentringForce;
+
+ // d3 calls this whenever the simulation's node array is (re)assigned, which
+ // is also how a fresh data generation reaches an already-registered force.
+ force.initialize = (next: SimNode[]): void => {
+ nodes = next ?? [];
+ };
+
+ return force;
+}
+
+/**
+ * Strength used by both 3D maps.
+ *
+ * Tuned against a real vault of 59 pages whose one unlinked page sat far
+ * enough out to shrink the entire network to a tenth of the frame. Paired with
+ * a bounded repulsion radius it now settles just outside the cluster, and the
+ * connected core keeps the spread the repulsion gave it.
+ */
+export const CENTRING_STRENGTH = 0.04;
diff --git a/jarvis/ui/web/frontend/src/lib/wikiGraph.ts b/jarvis/ui/web/frontend/src/lib/wikiGraph.ts
index 60ce2f0052..e5847498b0 100644
--- a/jarvis/ui/web/frontend/src/lib/wikiGraph.ts
+++ b/jarvis/ui/web/frontend/src/lib/wikiGraph.ts
@@ -199,6 +199,20 @@ export function nodeRadius(backlinkCount: number): number {
return Math.max(8, Math.min(24, 8 + backlinkCount * 2));
}
+/**
+ * How big a node draws, relative to its peers — the shared size encoding for
+ * BOTH the flat map and the 3D one.
+ *
+ * The range is 1.0 (a leaf) to 2.6 (a hub with eight or more backlinks), and
+ * the selected node is half again as large so it can be found without reading
+ * a single label. It lives here rather than in either renderer so a hub does
+ * not silently change meaning when the user flips the map into space.
+ */
+export function nodeSizeScore(backlinkCount: number, isActive: boolean): number {
+ const score = 1.0 + Math.min(Math.max(backlinkCount, 0), 8) * 0.2;
+ return isActive ? score * 1.5 : score;
+}
+
/**
* Count how often each `target` appears as the destination of a wikilink.
* Returns a Map keyed by node `id`. Edges to unknown nodes are ignored