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.

fix(wiki): the memory map hands its WebGL context back, and survives losing it

Harald01fead861c0c
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx
index fd8285590e..a39979115a 100644
--- a/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx
@@ -15,7 +15,7 @@ import {
type RenderNode,
type WikiGraphPayload,
} from "@/lib/wikiGraph";
-import { detectWebgl } from "@/lib/graphDimension";
+import { detectWebgl, useWebglSupported } from "@/lib/graphDimension";
import { useDeckSlotPowered } from "@/components/deck/DeckReveal";
import { DeckCard, DeckIconButton } from "@/components/deck/DeckCard";
import { HudLamp, useElementSize } from "@/components/deck/HudFrame";
@@ -92,7 +92,9 @@ function DeckWikiScene({
}) {
const t = useT();
const [ref, size] = useElementSize<HTMLDivElement>();
- const webgl = useMemo(() => detectWebgl(), []);
+ // Not a plain `detectWebgl()`: a context this page already lost for good
+ // takes the flat map's side, here as everywhere else.
+ const webgl = useWebglSupported();
const titles = useMemo(
() => new Map(graphData.nodes.map((n) => [n.id, n.title])),
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
index 0d3c02a1d3..757b7617da 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/EntityGraph3D.tsx
@@ -32,6 +32,7 @@ import { CENTRING_STRENGTH, createCentringForce } from "@/lib/graphForces";
import { endpointId as endpointKey } from "@/lib/wikiGraph";
import type { Vec3 } from "@/lib/graphCamera";
import { useGraphOrbit, type GraphCameraApi } from "@/hooks/useGraphOrbit";
+import { useWebglSurface } from "@/hooks/useWebglSurface";
/** Node shape the Explore map renders — mirrors EntityGraph's RenderNode. */
export interface ExploreRenderNode {
@@ -108,6 +109,11 @@ export function EntityGraph3D({
const graphRef = useRef<
ForceGraphMethods<ExploreRenderNode, ExploreRenderEdge> | undefined
>(undefined);
+ // The element the renderer paints into, and the guard that keeps its WebGL
+ // context alive: it hands the context back when this map goes away, and
+ // rebuilds the scene if the browser takes the context off us.
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ const { generation } = useWebglSurface(hostRef);
// 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.
@@ -160,9 +166,11 @@ export function EntityGraph3D({
// 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);
+ // New data, or a scene rebuilt after a lost context — a rebuild hands back a
+ // NEW renderer whose forces are the library defaults again.
useEffect(() => {
forcesConfiguredRef.current = false;
- }, [graphData]);
+ }, [graphData, generation]);
/**
* A co-occurrence network is the densest thing this app draws, and the third
@@ -198,7 +206,6 @@ export function EntityGraph3D({
// 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), []);
@@ -229,7 +236,9 @@ export function EntityGraph3D({
window.setTimeout(reframe, delay),
);
return () => timers.forEach(window.clearTimeout);
- }, [graphData, reframe, width, height]);
+ // `generation` belongs here too: a rebuilt scene starts on the library's
+ // default camera and would sit off-frame until the next reset.
+ }, [graphData, reframe, width, height, generation]);
const nodeVal = useCallback((node: NodeObject<ExploreRenderNode>): number => {
const base = (node as ExploreRenderNode).radius * SPHERE_SCALE;
@@ -312,6 +321,10 @@ export function EntityGraph3D({
// taken the wheel; the renderer paints into its own canvas inside it.
<div ref={hostRef} className="wiki-space relative h-full w-full">
<ForceGraph3D<ExploreRenderNode, ExploreRenderEdge>
+ // The ONLY thing that remounts this renderer: a lost graphics context.
+ // The canvas that lost it stays dead, so the scene is built again on a
+ // fresh one. Size and data changes go through live setters instead.
+ key={generation}
ref={graphRef}
graphData={graphData}
width={width || undefined}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx b/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx
index 42f006f860..fe20ab7ba9 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx
@@ -26,13 +26,20 @@ export function GraphDimensionToggle({
className,
}: GraphDimensionToggleProps): JSX.Element {
const t = useT();
- const { dimension, setDimension, webglSupported } = useGraphDimension();
+ const { dimension, setDimension, webglSupported, webglState } = useGraphDimension();
const segment = (value: GraphDimension) => {
const active = dimension === value;
const blocked = value === "3d" && !webglSupported;
+ // Two different "no", two different sentences: a machine that never had a
+ // graphics context is not the same as a session that lost one, and the
+ // second one a reload can undo.
const title = blocked
- ? t("wiki_graph.dimension_unavailable")
+ ? t(
+ webglState === "lost"
+ ? "wiki_graph.dimension_lost"
+ : "wiki_graph.dimension_unavailable",
+ )
: t(value === "3d" ? "wiki_graph.dimension_3d_title" : "wiki_graph.dimension_2d_title");
const Icon = value === "3d" ? Box : Square;
return (
@@ -67,6 +74,7 @@ export function GraphDimensionToggle({
data-testid="graph-dimension-toggle"
data-dimension={dimension}
data-webgl={webglSupported ? "true" : "false"}
+ data-webgl-state={webglState}
className={cn(
"inline-flex items-center gap-0.5 rounded-md border border-border bg-card/80 p-0.5 backdrop-blur",
className,
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.contextLoss.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.contextLoss.test.tsx
new file mode 100644
index 0000000000..3b30cf2ea7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.contextLoss.test.tsx
@@ -0,0 +1,152 @@
+/**
+ * What the maps do once a graphics context is gone for good.
+ *
+ * A lost context is not one card's problem: the browser hands them out per
+ * page, so a scene that could not get one back is telling every other scene
+ * what is about to happen to it. So the flag is shared — one dead surface and
+ * every map on screen goes flat, with the switch saying WHY in the user's own
+ * language, instead of each of them painting the browser's broken-canvas
+ * placeholder in turn.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, 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,
+ reportWebglLost,
+ resetWebglProbe,
+ setGraphDimension,
+} from "@/lib/graphDimension";
+
+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="wiki-graph-2d-stub" />;
+ }),
+ };
+});
+
+vi.mock("@/components/wiki/WikiGraph3D", () => ({
+ WikiGraph3D: () => <div data-testid="wiki-graph-3d-stub" />,
+}));
+
+const PAYLOAD = {
+ ok: true,
+ nodes: [
+ { id: "user", kind: "entity", title: "User" },
+ { id: "log", kind: "meta", title: "Log" },
+ ],
+ edges: [{ source: "user", target: "log", context: "wrote" }],
+ 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 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={new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })}
+ >
+ <WikiGraph onNodeClick={() => {}} />
+ </Wrapper>,
+ );
+}
+
+beforeEach(() => {
+ reportWebglLost(false);
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+ setGraphDimension("3d");
+ resetWebglProbe();
+});
+
+afterEach(() => {
+ cleanup();
+ reportWebglLost(false);
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ resetWebglProbe();
+ window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
+});
+
+describe("a graphics context lost for good", () => {
+ it("takes the map flat instead of leaving a dead canvas on screen", async () => {
+ pretendWebglWorks();
+ renderGraph();
+ // A generous wait: the lazy 3D module resolves on a microtask, and a busy
+ // machine running the whole suite at once can be a beat behind.
+ await screen.findByTestId("wiki-graph-3d-stub", {}, { timeout: 5_000 });
+
+ act(() => reportWebglLost(true));
+
+ await waitFor(
+ () => {
+ expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
+ },
+ { timeout: 5_000 },
+ );
+ expect(screen.getByTestId("wiki-graph-2d-stub")).toBeDefined();
+ });
+
+ it("says a context was lost, not that the machine cannot do 3D", async () => {
+ pretendWebglWorks();
+ renderGraph();
+ // A generous wait: the lazy 3D module resolves on a microtask, and a busy
+ // machine running the whole suite at once can be a beat behind.
+ await screen.findByTestId("wiki-graph-3d-stub", {}, { timeout: 5_000 });
+
+ act(() => reportWebglLost(true));
+
+ const segment = (await screen.findByTestId(
+ "graph-dimension-3d",
+ )) as HTMLButtonElement;
+ await waitFor(() => expect(segment.disabled).toBe(true), { timeout: 5_000 });
+ expect(segment.getAttribute("title")).toContain("lost its graphics context");
+ expect(segment.getAttribute("title")).not.toContain("cannot render 3D");
+ expect(
+ screen.getByTestId("graph-dimension-toggle").getAttribute("data-webgl-state"),
+ ).toBe("lost");
+ });
+
+ it("keeps the stored preference, so a reload offers the spatial map again", async () => {
+ pretendWebglWorks();
+ renderGraph();
+ // A generous wait: the lazy 3D module resolves on a microtask, and a busy
+ // machine running the whole suite at once can be a beat behind.
+ await screen.findByTestId("wiki-graph-3d-stub", {}, { timeout: 5_000 });
+
+ act(() => reportWebglLost(true));
+ await waitFor(
+ () => {
+ expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
+ },
+ { timeout: 5_000 },
+ );
+
+ expect(window.localStorage.getItem(GRAPH_DIMENSION_KEY)).toBe("3d");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
index c9e2d1fe91..1f2f7f4b6a 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph3D.tsx
@@ -57,6 +57,7 @@ import {
} from "@/lib/orbitalLayout";
import type { Vec3 } from "@/lib/graphCamera";
import { useGraphOrbit, type GraphCameraApi } from "@/hooks/useGraphOrbit";
+import { useWebglSurface } from "@/hooks/useWebglSurface";
import { useThemeValue } from "@/hooks/useTheme";
import { buildSunObject, sunPalette, syncSystemDecor } from "@/components/wiki/wikiSystem";
@@ -133,6 +134,11 @@ export function WikiGraph3D({
const graphRef = useRef<ForceGraphMethods<RenderNode, RenderEdge> | undefined>(
undefined,
);
+ // The element the renderer paints into, and the guard that keeps its WebGL
+ // context alive: it hands the context back when this scene goes away, and
+ // rebuilds the scene if the browser takes the context off us.
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ const { generation } = useWebglSurface(hostRef);
const theme = useThemeValue();
const themeRef = useRef(theme);
themeRef.current = theme;
@@ -205,9 +211,6 @@ export function WikiGraph3D({
// 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]);
const pivotSlugRef = useRef(pivotSlug);
pivotSlugRef.current = pivotSlug;
/** The live pivot node object (set below, once the data is known). */
@@ -224,6 +227,13 @@ export function WikiGraph3D({
const hopsRef = useRef(hops);
hopsRef.current = hops;
const decorKeyRef = useRef("");
+ // New data, or a scene rebuilt after a lost context. A rebuild hands back a
+ // NEW renderer with an empty scene graph, so the forces have to be set on it
+ // again and the sun's decor has to be built again.
+ useEffect(() => {
+ forcesConfiguredRef.current = false;
+ decorKeyRef.current = "";
+ }, [graphData, generation]);
const reducedMotion = useMemo(
() =>
typeof window.matchMedia === "function" &&
@@ -338,7 +348,6 @@ export function WikiGraph3D({
// 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), []);
@@ -378,7 +387,9 @@ export function WikiGraph3D({
window.setTimeout(reframe, delay),
);
return () => timers.forEach(window.clearTimeout);
- }, [graphData, resetSignal, reframe, width, height]);
+ // `generation` belongs here too: a rebuilt scene starts with the library's
+ // default camera, and the map would sit off-frame until the next reset.
+ }, [graphData, resetSignal, reframe, width, height, generation]);
const handleNodeClick = useCallback(
(node: NodeObject<RenderNode>): void => {
@@ -570,6 +581,11 @@ export function WikiGraph3D({
// the space the network floats in (see .wiki-space in index.css).
<div ref={hostRef} className="wiki-space relative h-full w-full">
<ForceGraph3D<RenderNode, RenderEdge>
+ // The ONLY thing that remounts this renderer. Size and data changes go
+ // through live setters (see the flat map's note on why a size key is a
+ // bug); a lost graphics context cannot — the canvas that lost it stays
+ // dead, so the scene is built again on a fresh one.
+ key={generation}
ref={graphRef}
graphData={data}
width={width}
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebglSurface.test.tsx b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.test.tsx
new file mode 100644
index 0000000000..534ba75cc6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.test.tsx
@@ -0,0 +1,112 @@
+/**
+ * The guard that keeps a 3D map from turning into a white rectangle.
+ *
+ * Three promises, and the first one is the one that caused the bug this hook
+ * exists for (2026-08-21): a scene that goes away has to hand its WebGL
+ * context BACK. `WebGLRenderer.dispose()` does not, so every trip into the
+ * Wiki section and back leaked one of the browser's sixteen contexts, and once
+ * they ran out the browser killed the oldest scene on the page — the deck's
+ * wiki card — and painted its own broken-canvas placeholder over it.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { useRef } from "react";
+
+import { MAX_CONTEXT_RECOVERIES, useWebglSurface } from "@/hooks/useWebglSurface";
+import { isWebglLost, reportWebglLost } from "@/lib/graphDimension";
+
+/** A canvas whose context can be asked for and taken away, jsdom-style. */
+function fakeCanvas(): { canvas: HTMLCanvasElement; loseContext: () => void } {
+ const canvas = document.createElement("canvas");
+ const loseContext = vi.fn();
+ const context = {
+ getExtension: (name: string) =>
+ name === "WEBGL_lose_context" ? { loseContext } : null,
+ };
+ // jsdom's canvas has no WebGL at all; a context and one extension is the
+ // whole surface this hook touches.
+ canvas.getContext = ((type: string) =>
+ /webgl/.test(type) ? context : null) as HTMLCanvasElement["getContext"];
+ return { canvas, loseContext };
+}
+
+/** A host div with the renderer's canvas already inside it. */
+function Surface({ canvas }: { canvas: HTMLCanvasElement }) {
+ const hostRef = useRef<HTMLDivElement | null>(null);
+ const { generation } = useWebglSurface(hostRef);
+ return (
+ <div
+ ref={(node) => {
+ hostRef.current = node;
+ if (node && !node.contains(canvas)) node.appendChild(canvas);
+ }}
+ data-testid="host"
+ data-generation={generation}
+ />
+ );
+}
+
+/** Fire the event the browser fires when it takes a context away. */
+function dropContext(canvas: HTMLCanvasElement): Event {
+ const event = new Event("webglcontextlost", { cancelable: true });
+ act(() => {
+ canvas.dispatchEvent(event);
+ });
+ return event;
+}
+
+afterEach(() => {
+ cleanup();
+ reportWebglLost(false);
+ vi.restoreAllMocks();
+});
+
+describe("useWebglSurface", () => {
+ it("hands the WebGL context back when the scene goes away", async () => {
+ const { canvas, loseContext } = fakeCanvas();
+ const view = render(<Surface canvas={canvas} />);
+ await waitFor(() => expect(canvas.parentElement).not.toBeNull());
+
+ view.unmount();
+
+ expect(loseContext).toHaveBeenCalledTimes(1);
+ });
+
+ it("survives a lost context: prevents the default and rebuilds the scene", async () => {
+ const { canvas } = fakeCanvas();
+ const view = render(<Surface canvas={canvas} />);
+ await waitFor(() => expect(canvas.parentElement).not.toBeNull());
+
+ const event = dropContext(canvas);
+
+ // Without preventDefault the browser writes the context off for good and
+ // never fires `webglcontextrestored` — the canvas stays a sad face.
+ expect(event.defaultPrevented).toBe(true);
+ await waitFor(() => {
+ expect(view.getByTestId("host").getAttribute("data-generation")).toBe("1");
+ });
+ expect(isWebglLost()).toBe(false);
+ });
+
+ it("gives up after one loss too many and degrades every graph to the flat map", async () => {
+ const { canvas } = fakeCanvas();
+ const view = render(<Surface canvas={canvas} />);
+ await waitFor(() => expect(canvas.parentElement).not.toBeNull());
+
+ for (let attempt = 1; attempt <= MAX_CONTEXT_RECOVERIES; attempt++) {
+ dropContext(canvas);
+ await waitFor(() => {
+ expect(view.getByTestId("host").getAttribute("data-generation")).toBe(
+ String(attempt),
+ );
+ });
+ }
+ // One more than the surface is willing to rebuild.
+ dropContext(canvas);
+
+ await waitFor(() => expect(isWebglLost()).toBe(true));
+ expect(view.getByTestId("host").getAttribute("data-generation")).toBe(
+ String(MAX_CONTEXT_RECOVERIES),
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebglSurface.ts b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.ts
new file mode 100644
index 0000000000..f37b532631
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useWebglSurface.ts
@@ -0,0 +1,157 @@
+/**
+ * Keeps a WebGL scene alive across the two things that kill one: running out
+ * of contexts, and being told the context is gone.
+ *
+ * A browser allows a small, fixed number of live WebGL contexts per page —
+ * Chromium's limit is 16 — and it enforces it by silently taking the OLDEST
+ * one away when a new one is asked for. `WebGLRenderer.dispose()` does NOT
+ * hand a context back; only `WEBGL_lose_context` does. So a page that mounts
+ * and unmounts 3D scenes leaks one context per mount, and after sixteen the
+ * browser kills the longest-running scene on screen — measured 2026-08-21:
+ * fourteen trips into the Wiki section and back left fifteen live contexts
+ * behind ONE canvas, and the deck's map (the oldest context in the page) was
+ * the one that died.
+ *
+ * A dead canvas is not blank, either. With no `webglcontextlost` handler the
+ * browser never offers the context back, and Chromium paints its own
+ * broken-canvas placeholder into the element: a white rectangle with a small
+ * sad face in the corner. That is the failure the maintainer screenshotted.
+ *
+ * So this hook does both halves:
+ * - on unmount (and between rebuilds) it RELEASES the context, so scenes that
+ * come and go do not spend the page's budget;
+ * - on a lost context it calls `preventDefault()` — without it the browser
+ * never fires `webglcontextrestored` — and rebuilds the scene by bumping a
+ * remount key, twice, before it gives up and degrades every graph on screen
+ * to the flat map with a stated reason.
+ */
+import { useEffect, useRef, useState, type RefObject } from "react";
+
+import { reportWebglLost } from "@/lib/graphDimension";
+
+/** How often one surface rebuilds itself before the flat map takes over. */
+export const MAX_CONTEXT_RECOVERIES = 2;
+
+/**
+ * A beat between the loss and the rebuild, so a browser that means to hand the
+ * context back gets the chance — and a GPU reset that takes several scenes
+ * down at once is not answered by all of them in the same frame.
+ */
+const REBUILD_DELAY_MS = 250;
+
+/** A scene that has run this long without trouble has earned its retries back. */
+const STABLE_MS = 60_000;
+
+/** How long to keep looking for the renderer's canvas after a mount. */
+const MAX_ATTACH_FRAMES = 60;
+
+export interface WebglSurface {
+ /**
+ * Remount key for the renderer. It only ever changes when a context was
+ * lost, so a resize or a data change still reaches the live scene instead of
+ * restarting the simulation.
+ */
+ generation: number;
+}
+
+/** Hand a canvas's WebGL context back to the browser. Safe to call twice. */
+export function releaseWebglContext(canvas: HTMLCanvasElement): void {
+ try {
+ const gl = (canvas.getContext("webgl2") ??
+ canvas.getContext("webgl")) as WebGLRenderingContext | null;
+ // Absent on a context that is already lost, and on the software renderers
+ // some locked-down WebViews ship — neither is worth an exception.
+ const lose = gl?.getExtension("WEBGL_lose_context") as {
+ loseContext?: () => void;
+ } | null;
+ lose?.loseContext?.();
+ } catch {
+ /* A context we cannot reach is one we cannot leak either. */
+ }
+}
+
+/**
+ * @param hostRef the element the renderer paints its canvas into.
+ */
+export function useWebglSurface(
+ hostRef: RefObject<HTMLElement | null>,
+): WebglSurface {
+ const [generation, setGeneration] = useState(0);
+ const recoveriesRef = useRef(0);
+
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+
+ let canvas: HTMLCanvasElement | null = null;
+ let released = false;
+ let rebuilt = false;
+ let frame = 0;
+ let attempts = 0;
+ let rebuildTimer = 0;
+
+ const rebuild = () => {
+ if (released || rebuilt) return;
+ rebuilt = true;
+ setGeneration((n) => n + 1);
+ };
+
+ const onLost = (event: Event) => {
+ // THE line that matters: without it the browser writes the context off
+ // for good and never fires `webglcontextrestored`.
+ event.preventDefault();
+ if (released) return;
+ if (recoveriesRef.current >= MAX_CONTEXT_RECOVERIES) {
+ // Twice was not a fluke. Say so once, out loud, and let every graph
+ // fall back to the flat map rather than paint a broken canvas.
+ reportWebglLost(true);
+ return;
+ }
+ recoveriesRef.current += 1;
+ rebuildTimer = window.setTimeout(rebuild, REBUILD_DELAY_MS);
+ };
+
+ const onRestored = () => {
+ // The context is back but empty — the renderer's buffers, textures and
+ // programs all went with it, so the scene has to be built again.
+ window.clearTimeout(rebuildTimer);
+ rebuild();
+ };
+
+ const attach = () => {
+ canvas = host.querySelector("canvas");
+ if (!canvas) {
+ // The renderer mounts in its own layout effect; on a slow first paint
+ // it can be a frame or two behind this one.
+ if (attempts++ < MAX_ATTACH_FRAMES) frame = requestAnimationFrame(attach);
+ return;
+ }
+ canvas.addEventListener("webglcontextlost", onLost);
+ canvas.addEventListener("webglcontextrestored", onRestored);
+ };
+ attach();
+
+ const stable = window.setTimeout(() => {
+ recoveriesRef.current = 0;
+ }, STABLE_MS);
+
+ return () => {
+ released = true;
+ cancelAnimationFrame(frame);
+ window.clearTimeout(rebuildTimer);
+ window.clearTimeout(stable);
+ if (!canvas) return;
+ canvas.removeEventListener("webglcontextlost", onLost);
+ canvas.removeEventListener("webglcontextrestored", onRestored);
+ // The renderer's own destructor stops its animation loop; touching the
+ // graph ref here would reach the NEXT scene, because React commits a
+ // rebuilt child BEFORE it runs this cleanup — that mistake left the
+ // rebuilt map paused and black (2026-08-21).
+ releaseWebglContext(canvas);
+ };
+ }, [generation, hostRef]);
+
+ return { generation };
+}
+
+export default useWebglSurface;
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 48c7378b5c..5a6fff40fe 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2544,7 +2544,8 @@
"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…"
+ "loading_3d": "3D-Karte wird geladen…",
+ "dimension_lost": "Die 3D-Karte hat ihren Grafik-Kontext verloren, deshalb übernimmt die flache Karte. Ein Neuladen der Seite holt sie zurück."
},
"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 3a401c87c0..83263d46e7 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2544,7 +2544,8 @@
"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…"
+ "loading_3d": "Loading the 3D map…",
+ "dimension_lost": "The 3D map lost its graphics context, so the flat map took over. Reloading the page brings it back."
},
"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 ba4951d747..d198ac012a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2544,7 +2544,8 @@
"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…"
+ "loading_3d": "Cargando el mapa 3D…",
+ "dimension_lost": "El mapa 3D perdió su contexto gráfico, así que el mapa plano tomó el relevo. Recargar la página lo recupera."
},
"tree_sidebar": {
"load_error": "No se pudo cargar el wiki.",
diff --git a/jarvis/ui/web/frontend/src/lib/graphDimension.ts b/jarvis/ui/web/frontend/src/lib/graphDimension.ts
index 11a38bcd29..5ad6830e6d 100644
--- a/jarvis/ui/web/frontend/src/lib/graphDimension.ts
+++ b/jarvis/ui/web/frontend/src/lib/graphDimension.ts
@@ -128,10 +128,20 @@ function probeWebgl(): boolean {
}
}
+/** What the machine can do right now, and why not when it cannot. */
+export type WebglState = "ok" | "absent" | "lost";
+
interface GraphDimensionStore {
/** What the user asked for, regardless of what the machine can do. */
preference: GraphDimension;
setPreference: (value: GraphDimension) => void;
+ /**
+ * Set once a graphics context was taken away and could not be rebuilt.
+ * A page-lifetime fact, not a preference: it is never persisted, so a
+ * reload offers 3D again.
+ */
+ webglLost: boolean;
+ setWebglLost: (value: boolean) => void;
}
const useGraphDimensionStore = create<GraphDimensionStore>((set) => ({
@@ -140,8 +150,39 @@ const useGraphDimensionStore = create<GraphDimensionStore>((set) => ({
writeGraphDimension(value);
set({ preference: value });
},
+ webglLost: false,
+ setWebglLost: (value) => set({ webglLost: value }),
}));
+/**
+ * Report that a WebGL surface gave up — the browser dropped its context and
+ * rebuilding it kept failing.
+ *
+ * Every graph on screen reads the same flag, so ONE dead scene degrades all of
+ * them to the flat map at once instead of leaving the others to paint the
+ * browser's broken-canvas placeholder in turn.
+ */
+export function reportWebglLost(value: boolean): void {
+ useGraphDimensionStore.getState().setWebglLost(value);
+}
+
+/** Read the flag outside React (tests, non-component callers). */
+export function isWebglLost(): boolean {
+ return useGraphDimensionStore.getState().webglLost;
+}
+
+/**
+ * Can a WebGL scene be drawn right now? The machine's answer, minus any
+ * context this page has already lost for good.
+ *
+ * For surfaces that always want the spatial map and never read the switch —
+ * the deck's wiki card is the one.
+ */
+export function useWebglSupported(): boolean {
+ const lost = useGraphDimensionStore((s) => s.webglLost);
+ return !lost && detectWebgl();
+}
+
/**
* 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
@@ -158,6 +199,13 @@ export interface GraphDimensionHandle {
preference: GraphDimension;
setDimension: (value: GraphDimension) => void;
webglSupported: boolean;
+ /**
+ * Why 3D is off, when it is. `absent` = this machine never had a context,
+ * `lost` = it had one and the GPU took it away mid-session. The two need
+ * different words: the first is a property of the machine, the second is an
+ * accident the user can often undo by reloading.
+ */
+ webglState: WebglState;
}
/**
@@ -168,11 +216,15 @@ export interface GraphDimensionHandle {
export function useGraphDimension(): GraphDimensionHandle {
const preference = useGraphDimensionStore((s) => s.preference);
const setDimension = useGraphDimensionStore((s) => s.setPreference);
- const webglSupported = detectWebgl();
+ const lost = useGraphDimensionStore((s) => s.webglLost);
+ // The probe stays lazy and cached: asking it here costs nothing after the
+ // first call, and the first call must not be dragged onto the boot path.
+ const webglSupported = useWebglSupported();
return {
dimension: resolveGraphDimension(preference, webglSupported),
preference,
setDimension,
webglSupported,
+ webglState: lost ? "lost" : webglSupported ? "ok" : "absent",
};
}