Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(glyphgrid): a restore that never arrives falls back instead of stranding the canvas
enesc6c840da14f0
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.mdindex 5b2ed2274..a7c4e03c8 100644--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md@@ -495,21 +495,42 @@ Auto after you switched builds, that is why: re-select Shared and carry on.## 5. Failure paths-- [ ] **5.1 Forced context loss — the canvas comes BACK.** Force a loss on the shared canvas- (`document.querySelector('.glyphgrid-canvas').getContext('webgl2')- .getExtension('WEBGL_lose_context').loseContext()`). Expect: a brief blank canvas, then every- terminal repaints on the SHARED renderer with its text intact and its cursor where it was —- no reload, no re-registration, and terminals that were streaming keep streaming. The console- carries exactly TWO glyphgrid lines, one naming the loss and one naming the restore; the- Settings row still reads Shared and the mode is NOT failed. Note anything that comes back- wrong rather than blank (soft or garbled glyphs would mean the atlas page did not survive the- GPU event, which the restore assumes it does).-- [ ] **5.2 A second loss inside a minute falls back permanently, as designed.** Immediately after- 5.1 (within 60 s — `RESTORE_COOLDOWN_MS`), force the loss again. Expect: NO second restore,- one warning naming the repeat loss, and every terminal back on readable DOM text with nothing+> **READ THIS BEFORE 5.1–5.2b.** `WEBGL_lose_context.loseContext()` is a **synthetic** loss: the+> context stays lost until `restoreContext()` is called **on the same extension object**, and the+> app's `preventDefault()` does nothing for it (that only asks the browser to restore a loss the+> browser itself caused). So keep the extension in a variable and drive both halves by hand — a+> bare `loseContext()` tests item 5.2b, not 5.1.++- [ ] **5.1 Forced context loss — the canvas comes BACK.** In the DevTools console:+ ```js+ const x = document.querySelector('.glyphgrid-canvas')+ .getContext('webgl2').getExtension('WEBGL_lose_context')+ x.loseContext(); setTimeout(() => x.restoreContext(), 500)+ ```+ Expect: the canvas blanks for about half a second, then every terminal repaints on the SHARED+ renderer with its text intact and its cursor where it was — no reload, no re-registration, and+ terminals that were streaming keep streaming. The console carries exactly TWO glyphgrid lines,+ one naming the loss and one naming the restore; the Settings row still reads Shared and the+ mode is NOT failed. Note anything that comes back WRONG rather than blank (soft or garbled+ glyphs would mean the atlas page did not survive the GPU event, which the restore assumes it+ does — the fix is a forced repack, and `GlyphAtlas` already has the machinery for it).+ **Keep `x` — 5.2 needs the same object.**+- [ ] **5.2 A second loss inside a minute falls back permanently, as designed.** Within 60 s of 5.1+ (`RESTORE_COOLDOWN_MS` — the cooldown is armed by 5.1's SUCCESSFUL restore, so 5.1 must have+ passed first), on the same `x`: `x.loseContext()`. Expect: NO second restore attempt, ONE+ warning naming the repeat loss, and every terminal back on readable DOM text with nothingblank. The session stays failed until relaunch — that floor is deliberate, because handing afailing GPU its context back over and over is how one failure becomes a flicker. Switching toAuto and back still renders normally on Auto.+- [ ] **5.2b A loss that is never restored gives up on its own.** Reload the app (5.2 leaves the+ session failed), then force a loss and do NOT restore it: `document+ .querySelector('.glyphgrid-canvas').getContext('webgl2')+ .getExtension('WEBGL_lose_context').loseContext()`. Expect: the canvas blanks, and within ~5 s+ (`RESTORE_TIMEOUT_MS`) every terminal returns to readable DOM text with a second console line+ naming the give-up (`…lost and never restored`). The failure mode this guards is the canvas+ waiting FOREVER — transparent node bodies over a canvas that never paints again, with no+ second line on the console. If the terminals stay blank past ~10 s, that is a **BLOCKING**+ finding.- [ ] **5.3 No WebGL2.** On a machine/profile without WebGL2 (or with it disabled in flags):selecting Shared silently leaves every terminal on the DOM renderer — no error dialog, noblank terminals.diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.tsindex 5e561ec51..b186b2402 100644--- a/src/renderer/canvas/SharedGlyphLayer.test.ts+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts@@ -1587,11 +1587,17 @@ describe('createContextLossPolicy', () => {failures(): { reason: string; err?: unknown }[]/** Make the next `revive()` throw — a driver that will not rebuild. */breakRevive(): void+ /** How many watchdog timers are armed right now. */+ pendingTimers(): number+ /** Fire every armed timer — "the restore never arrived". */+ fireTimers(): void} {let clock = 0let suspends = 0let revives = 0let broken = false+ let handle = 1+ const timers = new Map<number, () => void>()const failures: { reason: string; err?: unknown }[] = []return {deps: {@@ -1605,6 +1611,14 @@ describe('createContextLossPolicy', () => {},fail: (reason, err) => {failures.push({ reason, err })+ },+ setTimer: (cb) => {+ const h = handle+++ timers.set(h, cb)+ return h+ },+ clearTimer: (h) => {+ timers.delete(h)}},at: (ms) => {@@ -1615,6 +1629,12 @@ describe('createContextLossPolicy', () => {failures: () => failures,breakRevive: () => {broken = true+ },+ pendingTimers: () => timers.size,+ fireTimers: () => {+ const due = [...timers.values()]+ timers.clear()+ for (const cb of due) cb()}}}@@ -1711,6 +1731,84 @@ describe('createContextLossPolicy', () => {expect(h.failures()).toEqual([])})+ it('a restore that NEVER arrives falls back instead of stranding the canvas', () => {+ // The worst outcome this policy can produce, and it is worse than the Phase-1b floor it+ // promises to keep: suspended engine, stopped runtime, and `failed` still FALSE — so every+ // node keeps a transparent body and keeps writing rows into a canvas that paints nothing, for+ // the rest of the session, with no second line on the console. `preventDefault()` is only a+ // REQUEST, and a synthetic `loseContext()` is never auto-restored at all.+ const h = harness()+ const policy = createContextLossPolicy(h.deps)+ policy.onLost()+ expect(h.pendingTimers()).toBe(1)+ h.fireTimers()+ expect(h.failures()).toHaveLength(1)+ expect(h.failures()[0].reason).toMatch(/never restored/i)+ // Terminal, like every other give-up branch: a restore that turns up after we have given up+ // must not rebuild anything.+ policy.onRestored()+ expect(h.revives()).toBe(0)+ expect(h.failures()).toHaveLength(1)+ })++ it('the watchdog is disarmed by a restore that does arrive', () => {+ // A timer left running would fail a session that recovered perfectly well.+ const h = harness()+ const policy = createContextLossPolicy(h.deps)+ policy.onLost()+ policy.onRestored()+ expect(h.pendingTimers()).toBe(0)+ h.fireTimers()+ expect(h.failures()).toEqual([])+ })++ it('the give-up branches arm no watchdog', () => {+ // Nothing is waiting for a restore on either terminal path, and a timer that fired afterwards+ // would log a second, contradictory reason for the same failure.+ const withinCooldown = harness()+ const a = createContextLossPolicy(withinCooldown.deps)+ a.onLost()+ a.onRestored()+ withinCooldown.at(RESTORE_COOLDOWN_MS - 1)+ a.onLost()+ expect(withinCooldown.pendingTimers()).toBe(0)++ const throwing = harness()+ const b = createContextLossPolicy(throwing.deps)+ b.onLost()+ throwing.breakRevive()+ b.onRestored()+ expect(throwing.pendingTimers()).toBe(0)+ })++ it('the loss itself is announced, not only its outcome', () => {+ // The one branch a regression could silence without any assertion going red — and the one a+ // device tester reads first, since it is what says "the canvas is blank ON PURPOSE, wait".+ const h = harness()+ const policy = createContextLossPolicy(h.deps)+ policy.onLost()+ expect(warn.mock.calls.map((c: unknown[]) => String(c[0])).join('\n')).toMatch(+ /context lost/i+ )+ })++ it('stop() disarms the watchdog, so it cannot fail a session that has moved on', () => {+ // The layer unmounts for reasons that have nothing to do with a failure — the mode switched+ // off hands the context back and disposes it. A watchdog firing after that would set the+ // session's `failed` flag, and re-enabling the mode would then do nothing until a relaunch.+ const h = harness()+ const policy = createContextLossPolicy(h.deps)+ policy.onLost()+ policy.stop()+ expect(h.pendingTimers()).toBe(0)+ h.fireTimers()+ expect(h.failures()).toEqual([])+ // …and it is terminal, like every other end state.+ expect(policy.onLost()).toBe(false)+ policy.onRestored()+ expect(h.revives()).toBe(0)+ })+it('a duplicate loss for the SAME outage is not a second failure', () => {// Two `webglcontextlost` events before any restore is one outage, not a GPU that failed twice// — suspending again would be harmless but failing the session would not.diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsxindex 55fba6d7b..9a1fb7bbf 100644--- a/src/renderer/canvas/SharedGlyphLayer.tsx+++ b/src/renderer/canvas/SharedGlyphLayer.tsx@@ -1401,8 +1401,29 @@ export function createCursorBlinkClock(deps: CursorBlinkClockDeps): CursorBlinkC*/export const RESTORE_COOLDOWN_MS = 60_000-/** Everything the policy touches, injected — so the once-only rule and the cooldown are testable- * without a GPU, a canvas or a clock, exactly as `createBoardFrameGate`'s policy is. */+/**+ * How long a suspended canvas waits for the restore it asked for before giving up.+ *+ * **`preventDefault()` is a REQUEST, not a guarantee**, and there are two ordinary ways the restore+ * never arrives: Chromium declines to restore a context whose GPU process has reset repeatedly, and+ * a SYNTHETIC loss (`WEBGL_lose_context.loseContext()` — which is how the device checklist forces+ * one) is never auto-restored at all; only an explicit `restoreContext()` on the same extension+ * object brings that one back. Without a watchdog both cases strand the session in the worst state+ * this module can produce: the engine suspended, the runtime stopped, and `failed` still FALSE — so+ * every node keeps a transparent body and keeps writing rows into a canvas that paints nothing,+ * with ONE line on the console and no second one ever, until the app is relaunched. That is+ * strictly worse than the Phase-1b behaviour this task promises to keep as its floor.+ *+ * Five seconds: a real restore lands within a few hundred milliseconds (a GPU-process restart being+ * the slow case), so this is generous by an order of magnitude, while a canvas that is never coming+ * back stays blank for a blink instead of for a session. A bounded ONE-SHOT is not the retry loop+ * the design forbids — it never asks for a second restore, it only stops waiting for the first.+ */+export const RESTORE_TIMEOUT_MS = 5000++/** Everything the policy touches, injected — so the once-only rule, the cooldown and the watchdog+ * are testable without a GPU, a canvas, a clock or a timer, the same split+ * `createBoardFrameGate` and `createCursorBlinkClock` make. */export interface ContextLossDeps {now(): number/** Park everything that could draw and drop the engine's GPU objects. */@@ -1412,6 +1433,8 @@ export interface ContextLossDeps {revive(): void/** The permanent fallback (`failSharedGlyph`). */fail(reason: string, err?: unknown): void+ setTimer(cb: () => void, ms: number): number+ clearTimer(handle: number): void}export interface ContextLossPolicy {@@ -1420,6 +1443,11 @@ export interface ContextLossPolicy {onLost(): boolean/** Handle `webglcontextrestored`. */onRestored(): void+ /** Teardown: disarm the watchdog and make every later event inert. The watchdog is the one thing+ * here that can outlive its owner, and it must not — a timer that fires after the layer has gone+ * would fail a session whose context was merely handed back (the mode switched off), which then+ * could not be re-enabled without a relaunch. */+ stop(): void}/**@@ -1432,15 +1460,17 @@ export interface ContextLossPolicy {* and an unacceptable one for the DEFAULT, because a GPU reset — sleep/wake, a driver hiccup —* would silently take every user's shared renderer away with no message.*- * Three rules, and the second and third are the floor Phase 1b's behaviour becomes:+ * Four rules, and every one but the first is the floor Phase 1b's behaviour becomes:* 1. A first loss suspends and asks for a restore; the restore rebuilds and resumes.* 2. A second loss WITHIN `RESTORE_COOLDOWN_MS` of that restore falls back permanently. The* restore is not retried, the event is not prevented, and the session goes back to the DOM* renderer through the usual funnel.* 3. A restore that THROWS falls back permanently too — a half-rebuilt context draws nothing, and* a canvas of transparent node bodies drawing nothing is indistinguishable from a freeze.+ * 4. A restore that NEVER ARRIVES falls back on a bounded watchdog (`RESTORE_TIMEOUT_MS`). Waiting+ * forever is the one outcome that is worse than not restoring at all — see that constant.*- * Both outcomes are announced on the console, and that is a requirement rather than a courtesy: a+ * Every outcome is announced on the console, and that is a requirement rather than a courtesy: a* silent restore looks exactly like a frozen canvas to whoever is debugging one, and a silent* fallback looks exactly like a soft-text bug.*/@@ -1451,6 +1481,21 @@ export function createContextLossPolicy(deps: ContextLossDeps): ContextLossPoliclet awaiting = false/** Terminal: the session has fallen back, and no further event may do anything. */let done = false+ /** The armed watchdog, or 0 for none. Exactly one can exist: it is armed only on the transition+ * into `awaiting` and cleared on every way out of it. */+ let watchdog = 0+ const disarm = (): void => {+ if (!watchdog) return+ deps.clearTimer(watchdog)+ watchdog = 0+ }+ /** The one place a give-up is spelled: disarm first, so no timer can fire a second, contradictory+ * reason for a failure that has already been reported. */+ const giveUp = (reason: string, err?: unknown): void => {+ disarm()+ done = true+ deps.fail(reason, err)+ }return {onLost(): boolean {if (done) return false@@ -1458,8 +1503,7 @@ export function createContextLossPolicy(deps: ContextLossDeps): ContextLossPolic// teardown) is not a second failure — we are already suspended and already waiting.if (awaiting) return trueif (restoredAt !== null && deps.now() - restoredAt < RESTORE_COOLDOWN_MS) {- done = true- deps.fail(+ giveUp(`the WebGL context was lost again within ${Math.round(RESTORE_COOLDOWN_MS / 1000)}s of a restore — not restoring a second time`@@ -1470,6 +1514,14 @@ export function createContextLossPolicy(deps: ContextLossDeps): ContextLossPolicconsole.warn('[glyphgrid] WebGL context lost — GPU objects dropped and frames parked; asking the browser to restore it')+ // Armed BEFORE the suspend, so the wait can never outlive its own bound even if the suspend+ // path throws on its way through the runtime teardown.+ watchdog = deps.setTimer(() => {+ watchdog = 0+ if (done || !awaiting) return+ awaiting = false+ giveUp('the WebGL context was lost and never restored')+ }, RESTORE_TIMEOUT_MS)deps.suspend()return true},@@ -1479,11 +1531,13 @@ export function createContextLossPolicy(deps: ContextLossDeps): ContextLossPolic// session has already been told it is on the DOM renderer.if (done || !awaiting) returnawaiting = false+ // The wait is over however it ends — a watchdog left running would fail a session that has+ // just recovered perfectly well.+ disarm()try {deps.revive()} catch (err) {- done = true- deps.fail('rebuilding the GPU objects after a context restore threw', err)+ giveUp('rebuilding the GPU objects after a context restore threw', err)return}// Recorded only on SUCCESS — the cooldown measures "how long did the restored context@@ -1492,6 +1546,10 @@ export function createContextLossPolicy(deps: ContextLossDeps): ContextLossPolicconsole.warn('[glyphgrid] WebGL context restored — GPU objects and every registered grid rebuilt; the canvas repaints in full')+ },+ stop(): void {+ disarm()+ done = true}}}@@ -1536,6 +1594,31 @@ export function SharedGlyphLayer(): JSX.Element {const canvas = ctx.canvashost.appendChild(canvas)+ // THE ONE INVARIANT SPANNING THE MODULE SINGLETON AND THIS EFFECT: the engine's suspended state+ // outlives the component, while the restore POLICY below is effect-scoped. A layer that+ // unmounted between a loss and its restore would therefore come back with a policy that is not+ // waiting for anything (`awaiting` false, so `onRestored` short-circuits) while the engine is+ // still suspended and `failed` is still false — the stranded canvas again, by a different road.+ // Unreachable today (every path that unmounts this effect disposes the context first, and a+ // fresh context is never suspended), which is exactly why it is worth a guard rather than a+ // comment: nothing enforces that ordering, and a mount is the one moment we can still decide.+ if (ctx.engine.gpuIsSuspended()) {+ try {+ ctx.engine.reviveGpu()+ console.warn('[glyphgrid] mounted onto a suspended engine — GPU objects rebuilt')+ } catch (err) {+ // The context is still gone (its programs will not compile), so there is nothing to mount+ // onto. `failSharedGlyph` disposes it and re-runs this effect with `failed` true.+ failSharedGlyph('a suspended engine could not be revived at mount', err)+ return+ }+ }++ // DELIBERATELY OUTSIDE `startRuntime` BELOW — it must keep running through a context outage.+ // It draws nothing (`setViewport` only resizes the backing store and dirties), and it is what+ // keeps the GL layer's `deviceW`/`deviceH` current while the context is gone, so the viewport+ // the rebuild re-pushes is the size the canvas actually is. Moved into the runtime, a window+ // resized during an outage would come back with its grids culled against a stale viewport.const pushViewport = (): void => {const dpr = currentDpr()// A display change (the window dragged onto a monitor with a different pixel ratio) arrives@@ -1559,7 +1642,8 @@ export function SharedGlyphLayer(): JSX.Element {window.addEventListener('resize', pushViewport)/**- * EVERYTHING THAT CAN DRAW OR SCHEDULE, as one startable/stoppable unit.+ * EVERYTHING THAT CAN DRAW OR SCHEDULE A FRAME, as one startable/stoppable unit. (The+ * ResizeObserver above is the deliberate exception — it schedules nothing; see its comment.)** It is a unit because a lost context has to take ALL of it down at once and a restore has to* bring exactly it back: the rAF chain, the heartbeat timer, the blink clock's interval, the@@ -1701,7 +1785,9 @@ export function SharedGlyphLayer(): JSX.Element {ctx.engine.reviveGpu()runtime = startRuntime()},- fail: (reason, err) => failSharedGlyph(reason, err)+ fail: (reason, err) => failSharedGlyph(reason, err),+ setTimer: (cb, ms) => window.setTimeout(cb, ms),+ clearTimer: (h) => window.clearTimeout(h)})// `preventDefault()` is the request for a `webglcontextrestored` event, so it is called only// when the policy actually intends to use one. Phase 1b never called it at all.@@ -1716,8 +1802,10 @@ export function SharedGlyphLayer(): JSX.Element {// Nothing may outlive the context — this is also the teardown for the `ctx.disposed` and// `failSharedGlyph` paths, both of which re-run this effect. `runtime` is read (not captured)// so a cleanup after a restore stops the CURRENT runtime rather than the one this effect run- // started with.+ // started with. The policy goes with it, so its watchdog cannot outlive the context it was+ // waiting on.runtime.stop()+ policy.stop()ro.disconnect()window.removeEventListener('resize', pushViewport)canvas.removeEventListener('webglcontextlost', onLost)diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.tsindex d1e47ade3..6c9ac6b3f 100644--- a/src/renderer/glyphgrid/engine.test.ts+++ b/src/renderer/glyphgrid/engine.test.ts@@ -1031,6 +1031,20 @@ describe('suspendGpu / reviveGpu', () => {expect(e.frame()).toBe(false)})+ it('reports whether it is suspended — the layer\'s mount guard reads this', () => {+ // The engine is a module singleton and the restore policy is scoped to a React effect, so a+ // mount landing on a suspended engine is the one case no policy is waiting for. Nothing else+ // can detect it.+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.register(spec('a', 0))+ expect(e.gpuIsSuspended()).toBe(false)+ e.suspendGpu()+ expect(e.gpuIsSuspended()).toBe(true)+ e.reviveGpu()+ expect(e.gpuIsSuspended()).toBe(false)+ })+it('a second suspend is a no-op — the buffers are already gone', () => {const gl = fakeGL()const e = new GlyphGridEngine(gl, atlas())diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.tsindex c53aeb294..37925495d 100644--- a/src/renderer/glyphgrid/engine.ts+++ b/src/renderer/glyphgrid/engine.ts@@ -366,11 +366,17 @@ export class GlyphGridEngine {* Drop every grid at once: free each GPU buffer, empty the registry, and leave every handle* ever handed out INERT — exactly as if its owner had called `dispose()` itself.*- * This is the layer's teardown / context-loss path. On a lost context the grid buffers are- * already gone from the driver's side, and the owners (terminal nodes) are still holding live- * handles; without a sweep those handles would keep writing rows into a registry whose GPU- * objects no longer exist. Reaching them is what `Grid.dead` is for — see its comment: the- * engine deliberately keeps no list of handles, so the shared Grid object is the channel.+ * This is the layer's TEARDOWN path — the context being handed back for good (the mode switched+ * off, a font or dpr rebuild, a permanent failure). **It is NOT the context-loss path**, which is+ * `suspendGpu` below: that one drops the same GPU objects while KEEPING the registry, and the two+ * must not be confused. Running THIS on a lost context leaves every terminal on the canvas+ * holding a dead handle with nothing to re-register into — which is exactly the Phase-1b+ * behaviour (limitation L9) that the suspend/revive cycle exists to remove.+ *+ * Every owner (a terminal node) is still holding a live handle when this runs, and without a+ * sweep those handles would keep writing rows into a registry whose GPU objects no longer exist.+ * Reaching them is what `Grid.dead` is for — see its comment: the engine deliberately keeps no+ * list of handles, so the shared Grid object is the channel.** Idempotent, and change-gated: sweeping an empty registry changes nothing on screen, so it* must not dirty — the same discipline as setCamera/setViewport, and the reason `frame()` can@@ -402,6 +408,18 @@ export class GlyphGridEngine {* waking here would schedule a frame against the context that has just gone away. The revive* dirties instead, which is the moment there is something to draw with again.*/+ /**+ * Are the GPU objects currently gone (between a `suspendGpu` and its `reviveGpu`)?+ *+ * Exists for ONE caller: the layer's mount path. The engine is a module singleton while the+ * restore policy that drives this cycle is scoped to a React effect, so a mount that lands on a+ * suspended engine is a mount whose policy is not waiting for anything — and nothing else can+ * detect that. See the guard in `SharedGlyphLayer`'s effect.+ */+ gpuIsSuspended(): boolean {+ return this.gpuSuspended+ }+suspendGpu(): void {if (this.gpuSuspended) returnthis.gpuSuspended = true