Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(office): retry a floor rebuild that cannot get a WebGL context

djbiz1155c344e1d1
diff --git a/src/renderer/src/scene/office/OfficeFloor.tsx b/src/renderer/src/scene/office/OfficeFloor.tsx
index 0c3422fd..76ab64f2 100644
--- a/src/renderer/src/scene/office/OfficeFloor.tsx
+++ b/src/renderer/src/scene/office/OfficeFloor.tsx
@@ -12,7 +12,9 @@ import { hexToNumber, DEFAULT_CHARACTER } from './cast';
import { pickSoloLine, pickExchange, type BreakSpot } from './cafeteriaLines';
import { colors } from '@/design/tokens';
import { loadTheme, resolveThemeMap, themeTilesetUrls } from './themeLoader';
-import { installContextLossRecovery } from './glRecovery';
+import {
+ installContextLossRecovery, planInitFailure, DEFAULT_MAX_INIT_RETRIES
+} from './glRecovery';
import type { Tile, Facing, ErrandKind, ErrandSpot } from './themeRegistry';
// The map, tileset atlases, desk-claim order, errand spots, coffee-economy
@@ -164,6 +166,10 @@ export function OfficeFloor() {
// whole scene is torn down and rebuilt through the existing mount path rather
// than through a second, parallel recovery routine.
const [glGeneration, setGlGeneration] = useState(0);
+ // Retries spent on an init that could not GET a context (see glRecovery.ts).
+ // A ref, not state: the budget has to survive the rebuilds it schedules, which
+ // re-run the effect below and would reset anything scoped to it.
+ const initRetriesRef = useRef(0);
// The active office theme (store mirror of config.officeTheme). Changing it
// tears down and rebuilds the whole scene on the new map/cast (see deps below).
const officeTheme = useStore((s) => s.officeTheme);
@@ -258,15 +264,10 @@ export function OfficeFloor() {
onRebuild: () => { if (mountIdRef.current === mountId) setGlGeneration((n) => n + 1); },
onGiveUp: () => {
if (mountIdRef.current !== mountId) return;
- const note = document.createElement('div');
- note.style.cssText =
- 'position:absolute;inset:0;display:flex;align-items:center;justify-content:center;' +
- 'padding:24px;color:#ffd0b5;font-family:monospace;font-size:13px;text-align:center;white-space:pre-wrap;';
- note.textContent =
+ host.appendChild(floorNote(
'The office floor lost its GPU context.\n\n' +
'Too many terminals are using the GPU at once.\n' +
- 'Close a few agent terminals, or restart the app, to bring it back.';
- host.appendChild(note);
+ 'Close a few agent terminals, or restart the app, to bring it back.'));
}
});
@@ -1710,17 +1711,42 @@ export function OfficeFloor() {
});
resize.observe(host);
(app as any).__resize = resize;
+ // The floor is up: give the next crowded start-up a full budget again.
+ initRetriesRef.current = 0;
};
init().catch((err) => {
if (mountIdRef.current !== mountId) return;
+ const plan = planInitFailure(err, initRetriesRef.current);
+
+ // Pixi could not get a context — usually the GPU process restarting under
+ // us — and reports that as "this browser does not support WebGL". Retry
+ // through the same rebuild path an eviction uses; the half-built app is
+ // torn down by this effect's cleanup when the generation bump re-runs it.
+ if (plan.action === 'retry') {
+ initRetriesRef.current = plan.attempt;
+ console.warn(`[OfficeFloor] could not get a WebGL context (the GPU process may be restarting) — retrying, attempt ${plan.attempt}/${DEFAULT_MAX_INIT_RETRIES}`);
+ setTimeout(() => {
+ if (mountIdRef.current === mountId) setGlGeneration((n) => n + 1);
+ }, plan.delayMs);
+ return;
+ }
+
+ // Out of budget. The stack would say "does not support WebGL", which is
+ // both untrue and unactionable; say what actually helps instead.
+ if (plan.action === 'give-up') {
+ console.error(`[OfficeFloor] still no WebGL context after ${DEFAULT_MAX_INIT_RETRIES} retries:`, err);
+ host.appendChild(floorNote(
+ 'The office floor could not get a GPU context.\n\n' +
+ 'The GPU may still be restarting, or too many terminals are\n' +
+ 'using it at once. Close a few agent terminals, or restart\n' +
+ 'the app, to bring the floor back.'));
+ return;
+ }
+
console.error('[OfficeFloor] init failed:', err);
- const banner = document.createElement('div');
- banner.style.cssText =
- 'position:absolute;inset:0;display:flex;align-items:center;justify-content:center;' +
- 'padding:24px;color:#ffd0b5;font-family:monospace;font-size:13px;text-align:center;white-space:pre-wrap;';
- banner.textContent = 'OfficeFloor failed to start:\n' + (err?.stack || err?.message || String(err));
- host.appendChild(banner);
+ host.appendChild(floorNote(
+ 'OfficeFloor failed to start:\n' + (err?.stack || err?.message || String(err))));
});
return () => {
@@ -1753,6 +1779,16 @@ export function OfficeFloor() {
);
}
+/** A message where the floor should be — the only thing the user sees when the
+ * scene cannot run, so all three failure paths share one look. */
+function floorNote(text: string): HTMLDivElement {
+ const note = document.createElement('div');
+ note.style.cssText =
+ 'position:absolute;inset:0;display:flex;align-items:center;justify-content:center;' +
+ 'padding:24px;color:#ffd0b5;font-family:monospace;font-size:13px;text-align:center;white-space:pre-wrap;';
+ note.textContent = text;
+ return note;
+}
function hexNum(n: number): number { return n; }
function hex(n: number): string { return '#' + n.toString(16).padStart(6, '0'); }
function safeDestroy(app: Application) {
diff --git a/src/renderer/src/scene/office/glRecovery.ts b/src/renderer/src/scene/office/glRecovery.ts
index d9957dc3..4b3c7590 100644
--- a/src/renderer/src/scene/office/glRecovery.ts
+++ b/src/renderer/src/scene/office/glRecovery.ts
@@ -76,3 +76,82 @@ export function installContextLossRecovery(
canvas.removeEventListener('webglcontextlost', onLost as EventListener, false);
};
}
+
+/* ─── Failing to GET a context in the first place ──────────────────────────────
+ *
+ * The recovery above only starts listening once `app.init()` has resolved, so it
+ * cannot help when the REBUILD it schedules cannot get a context either. That is
+ * what happens when the GPU process dies rather than when a context is evicted:
+ * the floor loses its context, the rebuild fires 1500ms later, and Chromium is
+ * still bringing the GPU process back. getContext() returns null and Pixi turns
+ * that into
+ *
+ * Error: This browser does not support WebGL. Try using the canvas renderer
+ *
+ * which OfficeFloor then painted onto the floor as a wall of minified frames.
+ * The message is a lie about the cause — the browser supports WebGL fine, the
+ * GPU process just is not there yet — so treating it as fatal leaves the floor
+ * dead until the whole app is restarted, over a condition that clears itself in
+ * a second or two.
+ *
+ * REPRODUCED on v0.4.5 (Windows, Intel UHD, Electron 32) by killing the app's
+ * --type=gpu-process out from under a live floor: the eviction path logs its
+ * rebuild, and the rebuild's init() throws the error above.
+ *
+ * Note the two are NOT the same failure. Eviction pressure alone does not get
+ * here: a getContext() call that pushes past Chromium's ~16-context cap evicts
+ * somebody else and SUCCEEDS, so the floor's rebuild always wins its slot back.
+ * It takes an absent GPU process for the request itself to fail.
+ *
+ * Kept as a pure classifier + planner so the policy is testable without a
+ * browser, a GPU or Pixi — same as the loss path.
+ */
+
+/** Retries before we accept that the floor cannot have a context right now.
+ * Three at 1500ms covers a GPU process restart with room to spare. */
+export const DEFAULT_MAX_INIT_RETRIES = 3;
+
+/** Messages meaning "no context for you", across Pixi and Chromium wordings.
+ * Deliberately narrow: anything that is NOT recognised here is reported as the
+ * bug it probably is, rather than hidden behind several seconds of retries. */
+const CONTEXT_UNAVAILABLE = [
+ /does not support webgl/i, // Pixi 8, verbatim
+ /web(gl|gpu)\d?\s*(is\s+)?(not\s+(supported|available)|unsupported|unavailable)/i,
+ /(unable|failed) to (create|get|obtain)[^.]*context/i,
+ /no (webgl|gpu|rendering) context/i,
+];
+
+/** True when `err` says a rendering context could not be obtained — a busy
+ * process, not a browser without WebGL. Follows the `cause` chain so a caller
+ * that wrapped the failure in its own Error still classifies correctly. */
+export function isContextUnavailableError(err: unknown): boolean {
+ for (let e: unknown = err, depth = 0; e && depth < 5; depth++) {
+ const msg = typeof e === 'string' ? e : (e as { message?: unknown })?.message;
+ if (typeof msg === 'string' && CONTEXT_UNAVAILABLE.some((re) => re.test(msg))) return true;
+ e = (e as { cause?: unknown })?.cause;
+ }
+ return false;
+}
+
+export type InitFailurePlan =
+ /** Wait `delayMs`, then build the scene again from scratch. */
+ | { action: 'retry'; delayMs: number; attempt: number }
+ /** Out of budget: tell the user, in words, that the GPU is oversubscribed. */
+ | { action: 'give-up' }
+ /** Not a context problem — show the error, it is a real failure. */
+ | { action: 'report' };
+
+/** Decide what a rejected `app.init()` means. `attemptsUsed` is how many retries
+ * this mount has already spent, so the budget survives across rebuilds. */
+export function planInitFailure(
+ err: unknown,
+ attemptsUsed: number,
+ opts: { maxRetries?: number; delayMs?: number } = {}
+): InitFailurePlan {
+ if (!isContextUnavailableError(err)) return { action: 'report' };
+ const max = opts.maxRetries ?? DEFAULT_MAX_INIT_RETRIES;
+ if (attemptsUsed >= max) return { action: 'give-up' };
+ // Same delay as a rebuild: a GPU process takes a moment to come back, and
+ // asking again immediately just gets the same null.
+ return { action: 'retry', delayMs: opts.delayMs ?? DEFAULT_REBUILD_DELAY_MS, attempt: attemptsUsed + 1 };
+}
diff --git a/test/office-gl-recovery.test.cjs b/test/office-gl-recovery.test.cjs
index fcafe367..e21239f2 100644
--- a/test/office-gl-recovery.test.cjs
+++ b/test/office-gl-recovery.test.cjs
@@ -18,7 +18,8 @@ const assert = require('node:assert');
const load = require('./load-ts.cjs');
const {
- installContextLossRecovery, DEFAULT_MAX_REBUILDS, DEFAULT_REBUILD_DELAY_MS
+ installContextLossRecovery, DEFAULT_MAX_REBUILDS, DEFAULT_REBUILD_DELAY_MS,
+ isContextUnavailableError, planInitFailure, DEFAULT_MAX_INIT_RETRIES
} = load('src/renderer/src/scene/office/glRecovery.ts');
/** A canvas stand-in: EventTarget is all the recovery code touches. */
@@ -114,6 +115,87 @@ test('uninstalling stops recovery — a torn-down scene must not resurrect itsel
assert.equal(clock.pending, 0, 'still listening after uninstall');
});
+/**
+ * The blank-office bug, second half: losing the context is survivable, but
+ * NOT GETTING ONE IN THE FIRST PLACE was fatal.
+ *
+ * installContextLossRecovery() is wired up AFTER `app.init()` resolves, so it
+ * never sees the case where the REBUILD it schedules cannot get a context
+ * either. When the GPU process dies (a driver reset, a TDR, a Chromium GPU
+ * crash) the floor loses its context, the rebuild fires 1500ms later, and the
+ * GPU process is still coming back. getContext() returns null and Pixi throws
+ *
+ * Error: This browser does not support WebGL. Try using the canvas renderer
+ * at _GlContextSystem.createContext (WebGLRenderer...)
+ * at async _Application.init (index...)
+ *
+ * which OfficeFloor painted onto the floor as a wall of minified frames, where
+ * it stayed until the whole app was restarted. The browser supports WebGL
+ * perfectly well; it just asked a second too early.
+ *
+ * CONFIRMED against the shipped v0.4.5 build over CDP on Windows/Intel UHD by
+ * killing the app's --type=gpu-process out from under a live floor: it logged
+ * the rebuild, and the rebuild produced exactly the stack above.
+ *
+ * Eviction pressure alone does NOT get here, which is why this is a separate
+ * failure and not the one above: a getContext() that pushes past the ~16-context
+ * cap evicts somebody else and succeeds, so the rebuild always wins its slot
+ * back. Verified the same way — 24 held contexts plus a steady drip produced
+ * eviction, a rebuild, and a healthy floor.
+ */
+
+test('Pixi\'s "does not support WebGL" is read as a busy GPU, not a dead browser', () => {
+ // The verbatim message Pixi 8 throws out of GlContextSystem.createContext.
+ assert.equal(isContextUnavailableError(
+ new Error('This browser does not support WebGL. Try using the canvas renderer')), true);
+ // Wording varies across Pixi/Chromium versions, so match the family.
+ assert.equal(isContextUnavailableError(new Error('WebGL not supported')), true);
+ assert.equal(isContextUnavailableError(new Error('WebGPU is not available')), true);
+ assert.equal(isContextUnavailableError(new Error('Unable to create a WebGL context')), true);
+ assert.equal(isContextUnavailableError(new Error('Failed to get rendering context')), true);
+ // Wrapped by a caller that added its own framing.
+ assert.equal(isContextUnavailableError(
+ new Error('renderer boot failed', { cause: new Error('WebGL not supported') })), true);
+});
+
+test('a broken theme or texture is NOT mistaken for a busy GPU', () => {
+ // Retrying these would just hide a real bug behind a 6-second delay.
+ assert.equal(isContextUnavailableError(new Error('failed to load tileset office.png')), false);
+ assert.equal(isContextUnavailableError(new Error('theme bundle is malformed')), false);
+ assert.equal(isContextUnavailableError(new TypeError('map.tilesets is not iterable')), false);
+ assert.equal(isContextUnavailableError(undefined), false);
+ assert.equal(isContextUnavailableError(null), false);
+});
+
+test('an init that could not get a context retries instead of printing a stack', () => {
+ const err = new Error('This browser does not support WebGL. Try using the canvas renderer');
+ const plan = planInitFailure(err, 0);
+ assert.equal(plan.action, 'retry', 'a stack trace on the floor is the bug');
+ assert.equal(plan.attempt, 1);
+ // Same reasoning as the rebuild delay: contexts free up as terminals close,
+ // and asking again inside the same burst just fails again.
+ assert.ok(plan.delayMs >= 500, `init retry delay too short: ${plan.delayMs}`);
+ assert.equal(plan.delayMs, DEFAULT_REBUILD_DELAY_MS);
+});
+
+test('init retries are capped, then it says something a human can act on', () => {
+ const err = new Error('This browser does not support WebGL. Try using the canvas renderer');
+ for (let used = 0; used < DEFAULT_MAX_INIT_RETRIES; used++) {
+ assert.equal(planInitFailure(err, used).action, 'retry', `gave up with budget left (used ${used})`);
+ assert.equal(planInitFailure(err, used).attempt, used + 1);
+ }
+ assert.equal(planInitFailure(err, DEFAULT_MAX_INIT_RETRIES).action, 'give-up');
+ assert.equal(planInitFailure(err, DEFAULT_MAX_INIT_RETRIES + 9).action, 'give-up');
+});
+
+test('a real init bug is reported immediately and never retried', () => {
+ const bug = new TypeError('map.tilesets is not iterable');
+ assert.equal(planInitFailure(bug, 0).action, 'report');
+ // Still 'report' deep into the budget: retry count must not turn a bug into a
+ // "close some terminals" message that sends the user chasing the wrong thing.
+ assert.equal(planInitFailure(bug, DEFAULT_MAX_INIT_RETRIES).action, 'report');
+});
+
test('recovery survives repeated losses across rebuilds, one budget per install', () => {
const canvas = fakeCanvas();
const clock = fakeClock();