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): let the 3D map fill the screen and drift slowly on its own

Ruben Lütke4c4f2870cec9
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
index 8be19bc302..6fc608bbd4 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
@@ -15,13 +15,21 @@
* Loaded lazily by `EntityGraph`, so the WebGL renderer only arrives when the
* switch says 3D.
*/
-import { useCallback, useEffect, useRef } from "react";
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type RefObject,
+} 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";
+import type { Vec3 } from "@/lib/graphCamera";
+import { useGraphOrbit, type GraphCameraApi } from "@/hooks/useGraphOrbit";
/** Node shape the Explore map renders — mirrors EntityGraph's RenderNode. */
export interface ExploreRenderNode {
@@ -98,15 +106,15 @@ export function EntityGraph3D({
const anyRef = ref as any;
const charge = anyRef.d3Force?.("charge");
if (charge && typeof charge.strength === "function") {
- charge.strength(-220);
+ charge.strength(-380);
// 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);
+ link.distance(75);
+ if (typeof link.strength === "function") link.strength(0.14);
}
// 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
@@ -115,18 +123,26 @@ export function EntityGraph3D({
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);
- }, []);
+ // Framing and the slow drift are one piece of state; one hook owns both
+ // (hooks/useGraphOrbit.ts), and it re-frames whenever this counter changes.
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ const [frameSignal, setFrameSignal] = useState(0);
+ const reframe = useCallback(() => setFrameSignal((tick) => tick + 1), []);
+
+ useGraphOrbit({
+ graphRef: graphRef as RefObject<GraphCameraApi | undefined>,
+ hostRef,
+ nodes: graphData.nodes as Array<Partial<Vec3>>,
+ frameSignal,
+ });
useEffect(() => {
if (graphData.nodes.length === 0) return;
- const timer = window.setTimeout(fitToView, 2600);
+ reframe();
+ // Backstop for a simulation that never reports a stop.
+ const timer = window.setTimeout(reframe, 2600);
return () => window.clearTimeout(timer);
- }, [graphData, fitToView]);
+ }, [graphData, reframe]);
const nodeVal = useCallback((node: NodeObject<ExploreRenderNode>): number => {
const base = (node as ExploreRenderNode).radius;
@@ -156,7 +172,10 @@ export function EntityGraph3D({
// 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;
+ // Sized against the layout's spread, not the screen: the camera frames
+ // the whole network, so a fixed pixel size would shrink into nothing on
+ // a big corpus.
+ sprite.textHeight = selected ? 6 : 4.5;
const radius = selected ? topic.radius * SELECTED_SCALE : topic.radius;
sprite.position.set(0, -(radius + 2.5), 0);
return sprite;
@@ -177,6 +196,9 @@ export function EntityGraph3D({
);
return (
+ // The wrapper is what the camera work listens on to know the user has
+ // taken the wheel; the renderer paints into its own canvas inside it.
+ <div ref={hostRef} className="h-full w-full">
<ForceGraph3D<ExploreRenderNode, ExploreRenderEdge>
ref={graphRef}
graphData={graphData}
@@ -211,8 +233,9 @@ export function EntityGraph3D({
showNavInfo={false}
cooldownTicks={80}
onEngineTick={configureForces}
- onEngineStop={fitToView}
+ onEngineStop={reframe}
/>
+ </div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
index d05c30c772..62a9ca18e5 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
@@ -19,7 +19,14 @@
* 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 {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type RefObject,
+} from "react";
import ForceGraph3D from "react-force-graph-3d";
import type { ForceGraphMethods, NodeObject } from "react-force-graph-3d";
import type { Object3D } from "three";
@@ -33,6 +40,8 @@ import {
type RenderNode,
} from "@/lib/wikiGraph";
import { CENTRING_STRENGTH, createCentringForce } from "@/lib/graphForces";
+import type { Vec3 } from "@/lib/graphCamera";
+import { useGraphOrbit, type GraphCameraApi } from "@/hooks/useGraphOrbit";
/** Sphere radius in graph units for a node whose size score is 1.0. */
const NODE_REL_SIZE = 3;
@@ -109,7 +118,7 @@ export function WikiGraph3D({
const anyRef = ref as any;
const charge = anyRef.d3Force?.("charge");
if (charge && typeof charge.strength === "function") {
- charge.strength(-250);
+ charge.strength(-420);
// 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.
@@ -117,10 +126,11 @@ export function WikiGraph3D({
}
const link = anyRef.d3Force?.("link");
if (link && typeof link.distance === "function") {
- link.distance(60);
+ link.distance(85);
// 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);
+ // pulls the cluster back into the ball the repulsion just opened. A hub
+ // with fifty children would otherwise drag them all into its own pixel.
+ if (typeof link.strength === "function") link.strength(0.16);
}
// Bounds the world. Without it a single unlinked page drifts until it is
// out of everyone's reach, and `zoomToFit` — which frames every node —
@@ -129,18 +139,28 @@ export function WikiGraph3D({
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);
- }, []);
+ // Framing and the slow drift are one piece of state, so one hook owns both
+ // (see hooks/useGraphOrbit.ts). It re-frames whenever this counter changes:
+ // new data, a settled layout, or the host's Center button.
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ const [frameSignal, setFrameSignal] = useState(0);
+ const reframe = useCallback(() => setFrameSignal((tick) => tick + 1), []);
+
+ useGraphOrbit({
+ graphRef: graphRef as RefObject<GraphCameraApi | undefined>,
+ hostRef,
+ nodes: graphData.nodes as Array<Partial<Vec3>>,
+ frameSignal,
+ });
+ // The host asked for a reset, or the data changed under us.
useEffect(() => {
if (graphData.nodes.length === 0) return;
- const timer = window.setTimeout(fitToView, 2600);
+ reframe();
+ // A simulation that never reports a stop still gets framed.
+ const timer = window.setTimeout(reframe, 2600);
return () => window.clearTimeout(timer);
- }, [graphData, resetSignal, fitToView]);
+ }, [graphData, resetSignal, reframe]);
const handleNodeClick = useCallback(
(node: NodeObject<RenderNode>): void => {
@@ -180,7 +200,10 @@ export function WikiGraph3D({
if (!label) return null;
const sprite = new SpriteText(label);
sprite.color = isActive ? "#e6ecf5" : "#a8b0c0";
- sprite.textHeight = isActive ? 3.2 : 2.4;
+ // Sized against the layout, not the screen: the camera frames the whole
+ // network, so a label has to be a readable fraction of the SPREAD
+ // between nodes rather than a fixed number of pixels.
+ sprite.textHeight = isActive ? 5.5 : 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);
@@ -211,6 +234,9 @@ export function WikiGraph3D({
const data = useMemo(() => graphData, [graphData]);
return (
+ // The renderer paints into its own canvas; this wrapper is what the camera
+ // work listens on to know the user has taken the wheel.
+ <div ref={hostRef} className="h-full w-full">
<ForceGraph3D<RenderNode, RenderEdge>
ref={graphRef}
graphData={data}
@@ -253,8 +279,9 @@ export function WikiGraph3D({
d3AlphaDecay={0.04}
warmupTicks={40}
onEngineTick={configureForces}
- onEngineStop={fitToView}
+ onEngineStop={reframe}
/>
+ </div>
);
}
diff --git a/jarvis/ui/web/frontend/src/hooks/useGraphOrbit.ts b/jarvis/ui/web/frontend/src/hooks/useGraphOrbit.ts
new file mode 100644
index 0000000000..bc05e48b3a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useGraphOrbit.ts
@@ -0,0 +1,219 @@
+/**
+ * The camera work for the 3D memory maps: fill the frame, then keep moving.
+ *
+ * Two jobs, one owner, because they are the same state. Framing decides where
+ * the middle of the network is and how far back to stand; the drift walks the
+ * camera around that same point. Split across two places they fight — the
+ * drift keeps restoring an angle the fit just changed.
+ *
+ * The motion is deliberately slow: a full turn takes well over a minute, with
+ * a slight rise and fall on top so the network reads as a solid object in
+ * space rather than a flat picture that happens to spin. It is ambient, not
+ * animation — you should be able to read a label while it moves.
+ *
+ * Three things stop it, and all three matter:
+ * - The user touching the map. Nothing is more irritating than a view that
+ * creeps away from where you just put it, so a drag or a scroll parks the
+ * drift, and when it resumes it carries on from the angle the USER left the
+ * camera at, read back out of the camera itself.
+ * - A hidden tab. Frames nobody sees still cost a GPU.
+ * - `prefers-reduced-motion`. Continuous movement is a genuine trigger for
+ * some people, and the OS switch for it is the one place they say so once
+ * instead of per app.
+ */
+import { useCallback, useEffect, useRef, type RefObject } from "react";
+
+import {
+ framingFor,
+ orbitDistance,
+ orbitFrom,
+ orbitPoint,
+ type Orbit,
+ type Vec3,
+} from "@/lib/graphCamera";
+
+/** The slice of the renderer's imperative handle the camera work needs. */
+export interface GraphCameraApi {
+ cameraPosition: (
+ position: Partial<Vec3>,
+ lookAt?: Vec3,
+ transitionMs?: number,
+ ) => void;
+ camera: () => { position: Vec3; fov?: number; aspect?: number };
+}
+
+/** One full revolution. Long enough to read while it happens. */
+const REVOLUTION_MS = 96_000;
+
+/** The rise and fall on top of the rotation. */
+const SWAY_PERIOD_MS = 19_000;
+const SWAY_RADIANS = 0.11;
+
+/** Resting height above the network's own plane — a slight look down. */
+const BASE_ELEVATION = 0.24;
+
+/** How long after the user's last touch the drift picks back up. */
+const RESUME_AFTER_MS = 3_500;
+
+/** Share of the frame the network fills once framed. */
+const FILL = 0.94;
+
+export interface GraphOrbitOptions {
+ graphRef: RefObject<GraphCameraApi | undefined>;
+ /** Element the user actually drags — where the pause listeners go. */
+ hostRef: RefObject<HTMLElement | null>;
+ /** Live node array; the simulation writes x/y/z onto these objects. */
+ nodes: readonly Partial<Vec3>[];
+ /** Bump to re-frame: new data, a settled layout, the Center button. */
+ frameSignal: number;
+}
+
+export function useGraphOrbit({
+ graphRef,
+ hostRef,
+ nodes,
+ frameSignal,
+}: GraphOrbitOptions): void {
+ const centreRef = useRef<Vec3>({ x: 0, y: 0, z: 0 });
+ const orbitRef = useRef<Orbit>({
+ distance: 0,
+ azimuth: 0,
+ elevation: BASE_ELEVATION,
+ });
+ // Phase of the sway, kept separately so pausing does not make the camera
+ // jump when it resumes at a different point in the cycle.
+ const swayRef = useRef(0);
+ const pausedUntilRef = useRef(0);
+ const resyncRef = useRef(false);
+ // Read once per mount rather than per frame; the array identity changes on
+ // every data generation but the objects inside are the live ones.
+ const nodesRef = useRef(nodes);
+ nodesRef.current = nodes;
+
+ /** Point the camera at the middle of the network, far enough back to see it. */
+ const frame = useCallback((transitionMs = 700): void => {
+ const graph = graphRef.current;
+ if (!graph) return;
+ const framing = framingFor(nodesRef.current, 0.95);
+ if (!framing) return;
+
+ const camera = graph.camera();
+ const distance = orbitDistance(
+ framing.radius,
+ camera?.fov ?? 50,
+ camera?.aspect ?? 1,
+ FILL,
+ );
+ centreRef.current = framing.centre;
+ // Keep whatever angle the camera is already at — re-framing is about how
+ // far back you stand, not about turning the map back to the front.
+ const current = camera?.position
+ ? orbitFrom(framing.centre, camera.position)
+ : null;
+ orbitRef.current = {
+ distance,
+ azimuth: current?.azimuth ?? 0,
+ elevation: BASE_ELEVATION,
+ };
+ graph.cameraPosition(
+ orbitPoint(framing.centre, orbitRef.current),
+ framing.centre,
+ transitionMs,
+ );
+ // Our own move must not be mistaken for the user's, but the transition
+ // does need to finish before the drift starts nudging the camera again.
+ pausedUntilRef.current = Math.max(
+ pausedUntilRef.current,
+ performance.now() + transitionMs + 60,
+ );
+ }, [graphRef]);
+
+ useEffect(() => {
+ // One frame's delay: on the first render after a data swap the renderer
+ // has a handle but the simulation has not written positions yet, and
+ // framing an empty cloud puts the camera nowhere useful.
+ const timer = window.setTimeout(() => frame(), 60);
+ return () => window.clearTimeout(timer);
+ }, [frame, frameSignal]);
+
+ // Pause while the user is steering, and remember to pick their angle up.
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+ const hold = () => {
+ pausedUntilRef.current = performance.now() + RESUME_AFTER_MS;
+ resyncRef.current = true;
+ };
+ // Only a held button counts as steering; a cursor crossing the map on its
+ // way somewhere else is not, and treating it as such would park the drift
+ // for good on a busy screen.
+ const onMove = (event: PointerEvent) => {
+ if (event.buttons !== 0) hold();
+ };
+ host.addEventListener("pointerdown", hold);
+ host.addEventListener("pointermove", onMove);
+ host.addEventListener("wheel", hold, { passive: true });
+ host.addEventListener("touchstart", hold, { passive: true });
+ return () => {
+ host.removeEventListener("pointerdown", hold);
+ host.removeEventListener("pointermove", onMove);
+ host.removeEventListener("wheel", hold);
+ host.removeEventListener("touchstart", hold);
+ };
+ }, [hostRef]);
+
+ useEffect(() => {
+ const reduced =
+ typeof window.matchMedia === "function" &&
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ if (reduced) return;
+
+ let raf = 0;
+ let last = performance.now();
+
+ const step = (now: number) => {
+ raf = window.requestAnimationFrame(step);
+ const elapsed = Math.min(now - last, 100);
+ last = now;
+
+ if (document.hidden) return;
+ if (now < pausedUntilRef.current) return;
+
+ const graph = graphRef.current;
+ if (!graph || orbitRef.current.distance === 0) return;
+
+ if (resyncRef.current) {
+ // Carry on from wherever the user left the camera — including how far
+ // out they zoomed — instead of yanking it back to our own angle. The
+ // sway is subtracted back out so the stored elevation stays the
+ // RESTING one; keeping the swayed value would let each pause ratchet
+ // the camera a little further up or down.
+ const camera = graph.camera();
+ if (camera?.position) {
+ const seen = orbitFrom(centreRef.current, camera.position);
+ if (seen.distance > 0) {
+ orbitRef.current = {
+ ...seen,
+ elevation: seen.elevation - Math.sin(swayRef.current) * SWAY_RADIANS,
+ };
+ }
+ }
+ resyncRef.current = false;
+ }
+
+ const orbit = orbitRef.current;
+ orbit.azimuth -= (elapsed / REVOLUTION_MS) * Math.PI * 2;
+ swayRef.current += (elapsed / SWAY_PERIOD_MS) * Math.PI * 2;
+ const elevation = orbit.elevation + Math.sin(swayRef.current) * SWAY_RADIANS;
+
+ graph.cameraPosition(
+ orbitPoint(centreRef.current, { ...orbit, elevation }),
+ centreRef.current,
+ 0,
+ );
+ };
+
+ raf = window.requestAnimationFrame(step);
+ return () => window.cancelAnimationFrame(raf);
+ }, [graphRef]);
+}
diff --git a/jarvis/ui/web/frontend/src/lib/graphCamera.test.ts b/jarvis/ui/web/frontend/src/lib/graphCamera.test.ts
new file mode 100644
index 0000000000..43772c6c5b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/graphCamera.test.ts
@@ -0,0 +1,127 @@
+/**
+ * The arithmetic behind "fill the screen and keep moving".
+ *
+ * The load-bearing rule is the percentile radius: a vault is allowed to
+ * contain a page nothing links to, and framing that one stray along with
+ * everything else is exactly what left the readable part of the map occupying
+ * a fifth of the screen.
+ */
+import { describe, expect, it } from "vitest";
+
+import {
+ framingFor,
+ orbitDistance,
+ orbitFrom,
+ orbitPoint,
+} from "@/lib/graphCamera";
+
+/** A ball of nodes around a known centre, plus optional outliers. */
+function cluster(count: number, radius: number, centre = { x: 0, y: 0, z: 0 }) {
+ return Array.from({ length: count }, (_, index) => {
+ const angle = (index / count) * Math.PI * 2;
+ return {
+ x: centre.x + Math.cos(angle) * radius,
+ y: centre.y,
+ z: centre.z + Math.sin(angle) * radius,
+ };
+ });
+}
+
+describe("framingFor", () => {
+ it("has nothing to frame when there are no nodes", () => {
+ expect(framingFor([])).toBeNull();
+ });
+
+ it("finds the middle of an off-centre network", () => {
+ const framing = framingFor(cluster(24, 50, { x: 100, y: 20, z: -40 }));
+ expect(framing).not.toBeNull();
+ expect(framing!.centre.x).toBeCloseTo(100, 5);
+ expect(framing!.centre.y).toBeCloseTo(20, 5);
+ expect(framing!.centre.z).toBeCloseTo(-40, 5);
+ expect(framing!.radius).toBeCloseTo(50, 5);
+ });
+
+ it("does not let one stray node blow the radius up", () => {
+ const nodes = [...cluster(40, 50), { x: 4000, y: 0, z: 0 }];
+ const framing = framingFor(nodes, 0.95)!;
+ // The 95th percentile of 41 nodes is still inside the cluster, so the
+ // network keeps the frame and the outlier sits just past the edge.
+ expect(framing.radius).toBeLessThan(200);
+ });
+
+ it("covers everything when asked for the full extent", () => {
+ const nodes = [...cluster(40, 50), { x: 4000, y: 0, z: 0 }];
+ const framing = framingFor(nodes, 1)!;
+ expect(framing.radius).toBeGreaterThan(3000);
+ });
+
+ it("treats missing coordinates as the origin rather than NaN", () => {
+ const framing = framingFor([{}, { x: 10 }, { x: -10 }])!;
+ expect(Number.isFinite(framing.centre.x)).toBe(true);
+ expect(Number.isFinite(framing.radius)).toBe(true);
+ });
+
+ it("keeps a floor so a single node is not framed from inside itself", () => {
+ const framing = framingFor([{ x: 0, y: 0, z: 0 }])!;
+ expect(framing.radius).toBeGreaterThan(0);
+ });
+});
+
+describe("orbitDistance", () => {
+ it("stands further back for a bigger network", () => {
+ const near = orbitDistance(50, 50, 1.6);
+ const far = orbitDistance(500, 50, 1.6);
+ expect(far).toBeGreaterThan(near * 9);
+ });
+
+ it("uses the narrower of the two frustum angles", () => {
+ // A tall window is limited horizontally, a wide one vertically; either way
+ // the network must not spill out of the short side.
+ const wide = orbitDistance(100, 50, 3);
+ const tall = orbitDistance(100, 50, 0.4);
+ expect(tall).toBeGreaterThan(wide);
+ });
+
+ it("frames tighter as the fill share rises", () => {
+ const loose = orbitDistance(100, 50, 1.6, 0.5);
+ const tight = orbitDistance(100, 50, 1.6, 0.95);
+ expect(tight).toBeLessThan(loose);
+ });
+
+ it("never puts the camera inside the network", () => {
+ expect(orbitDistance(100, 50, 1.6, 0.99)).toBeGreaterThan(100);
+ expect(orbitDistance(100, 179, 1.6, 0.99)).toBeGreaterThan(100);
+ });
+
+ it("survives a viewport that has not been measured yet", () => {
+ expect(Number.isFinite(orbitDistance(100, 50, 0))).toBe(true);
+ expect(Number.isFinite(orbitDistance(100, 50, Number.NaN))).toBe(true);
+ });
+});
+
+describe("orbitPoint / orbitFrom", () => {
+ it("round-trips an orbit through a position and back", () => {
+ const centre = { x: 12, y: -4, z: 30 };
+ const orbit = { distance: 260, azimuth: 1.1, elevation: 0.24 };
+ const back = orbitFrom(centre, orbitPoint(centre, orbit));
+ expect(back.distance).toBeCloseTo(orbit.distance, 5);
+ expect(back.azimuth).toBeCloseTo(orbit.azimuth, 5);
+ expect(back.elevation).toBeCloseTo(orbit.elevation, 5);
+ });
+
+ it("keeps the camera at the same distance as it rotates", () => {
+ const centre = { x: 0, y: 0, z: 0 };
+ for (const azimuth of [0, 1, 2, 3, 4, 5, 6]) {
+ const point = orbitPoint(centre, { distance: 100, azimuth, elevation: 0.3 });
+ const length = Math.hypot(point.x, point.y, point.z);
+ expect(length).toBeCloseTo(100, 5);
+ }
+ });
+
+ it("reports a degenerate orbit rather than dividing by zero", () => {
+ const orbit = orbitFrom({ x: 5, y: 5, z: 5 }, { x: 5, y: 5, z: 5 });
+ expect(orbit.distance).toBe(0);
+ expect(Number.isFinite(orbit.azimuth)).toBe(true);
+ expect(Number.isFinite(orbit.elevation)).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/graphCamera.ts b/jarvis/ui/web/frontend/src/lib/graphCamera.ts
new file mode 100644
index 0000000000..2b2fdd892d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/graphCamera.ts
@@ -0,0 +1,155 @@
+/**
+ * Where to put the camera so a 3D graph fills the screen — and how to walk it
+ * slowly around the network without ever losing that framing.
+ *
+ * The renderer's own `zoomToFit` was not enough for either job. It frames
+ * EVERY node, so a single page nobody links to shrinks the whole vault to a
+ * marble in the middle of a black rectangle; and it hands back no way to keep
+ * orbiting from where it left the camera. Both are solved by computing the
+ * framing here and driving the camera directly.
+ *
+ * Everything in this file is pure arithmetic — no three.js, no React — so the
+ * rules that decide "this is the middle of the network and this is how far
+ * back you stand" are testable without a GPU.
+ */
+
+/** A point in graph space. The simulation writes these onto its nodes. */
+export interface Vec3 {
+ x: number;
+ y: number;
+ z: number;
+}
+
+/** Where the network sits and how big it is. */
+export interface Framing {
+ centre: Vec3;
+ radius: number;
+}
+
+/** A camera position expressed as an angle pair and a distance. */
+export interface Orbit {
+ distance: number;
+ /** Rotation in the horizontal plane, radians. */
+ azimuth: number;
+ /** Height above that plane, radians. ±π/2 is straight down/up. */
+ elevation: number;
+}
+
+/** Never divide by zero, and never frame a single node from a millimetre away. */
+const MIN_RADIUS = 12;
+
+function coordinate(value: number | undefined): number {
+ return Number.isFinite(value) ? (value as number) : 0;
+}
+
+/**
+ * The middle of the network and a radius that covers the bulk of it.
+ *
+ * The radius is a PERCENTILE, not a maximum, and that is the whole point. A
+ * vault is allowed to contain a page nothing links to; it drifts to the edge
+ * of the layout, and framing it along with everything else is what left the
+ * readable part of the map occupying a fifth of the screen. Taking the 95th
+ * percentile means the network fills the frame and the handful of outliers sit
+ * just past the edge — where a slowly orbiting camera brings them back into
+ * view anyway, and where a scroll wheel finds them immediately.
+ *
+ * @param points node positions as the simulation last left them
+ * @param percentile share of nodes the radius must cover, 0..1
+ * @returns null when there is nothing to frame
+ */
+export function framingFor(
+ points: readonly Partial<Vec3>[],
+ percentile = 0.95,
+): Framing | null {
+ if (points.length === 0) return null;
+
+ let sx = 0;
+ let sy = 0;
+ let sz = 0;
+ for (const point of points) {
+ sx += coordinate(point.x);
+ sy += coordinate(point.y);
+ sz += coordinate(point.z);
+ }
+ const centre: Vec3 = {
+ x: sx / points.length,
+ y: sy / points.length,
+ z: sz / points.length,
+ };
+
+ const distances = points
+ .map((point) => {
+ const dx = coordinate(point.x) - centre.x;
+ const dy = coordinate(point.y) - centre.y;
+ const dz = coordinate(point.z) - centre.z;
+ return Math.sqrt(dx * dx + dy * dy + dz * dz);
+ })
+ .sort((a, b) => a - b);
+
+ const share = Math.min(Math.max(percentile, 0), 1);
+ const index = Math.min(
+ distances.length - 1,
+ Math.max(0, Math.ceil(share * distances.length) - 1),
+ );
+ return { centre, radius: Math.max(distances[index], MIN_RADIUS) };
+}
+
+/**
+ * How far back the camera has to stand for a sphere of `radius` to fill
+ * `fill` of the frame.
+ *
+ * The limiting direction is whichever of the two frustum half-angles is
+ * narrower — on a wide window that is the vertical one, on a tall one the
+ * horizontal — so the network fills the screen without spilling out the short
+ * side.
+ *
+ * @param radius graph units
+ * @param fovDeg the camera's VERTICAL field of view, degrees
+ * @param aspect viewport width / height
+ * @param fill share of the frame the network should occupy, 0..1
+ */
+export function orbitDistance(
+ radius: number,
+ fovDeg: number,
+ aspect: number,
+ fill = 0.95,
+): number {
+ const safeAspect = Number.isFinite(aspect) && aspect > 0 ? aspect : 1;
+ const halfVertical = (Math.max(fovDeg, 1) * Math.PI) / 360;
+ const halfHorizontal = Math.atan(Math.tan(halfVertical) * safeAspect);
+ const half = Math.min(halfVertical, halfHorizontal);
+ // The sphere subtends `asin(radius / distance)`; asking it to subtend
+ // `fill` of the half-angle and solving for distance gives this.
+ const target = Math.max(Math.min(fill, 0.99), 0.05) * half;
+ return Math.max(radius / Math.sin(target), radius + 1);
+}
+
+/** The camera position for an orbit around `centre`. */
+export function orbitPoint(centre: Vec3, orbit: Orbit): Vec3 {
+ const horizontal = Math.cos(orbit.elevation) * orbit.distance;
+ return {
+ x: centre.x + Math.cos(orbit.azimuth) * horizontal,
+ y: centre.y + Math.sin(orbit.elevation) * orbit.distance,
+ z: centre.z + Math.sin(orbit.azimuth) * horizontal,
+ };
+}
+
+/**
+ * The inverse: read an orbit back out of wherever the camera currently is.
+ *
+ * This is what lets the automatic rotation resume from the user's own viewing
+ * angle after they have dragged the map around, instead of snapping back to
+ * where it was before they touched it.
+ */
+export function orbitFrom(centre: Vec3, position: Vec3): Orbit {
+ const dx = position.x - centre.x;
+ const dy = position.y - centre.y;
+ const dz = position.z - centre.z;
+ const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
+ if (distance === 0) return { distance: 0, azimuth: 0, elevation: 0 };
+ return {
+ distance,
+ azimuth: Math.atan2(dz, dx),
+ elevation: Math.asin(Math.min(Math.max(dy / distance, -1), 1)),
+ };
+}