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
perf(glyphgrid): park the rAF driver when the canvas is idle
enes6f1555edbb94
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.mdindex 04e98887a..535193bc9 100644--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md@@ -400,6 +400,20 @@ Auto after you switched builds, that is why: re-select Shared and carry on.node's bottom edge onto the canvas or over the subagent cards. Reason: the 2026-08-04 devicereport, where exactly that happened and **dragging the node was the only way to heal it** (adrag re-registers the grid, which re-measures; nothing else did).+- [ ] **4.19 The rAF driver parks when the canvas is idle.** With shared mode on, leave a canvas of+ IDLE terminals (nothing streaming, no agent working, mouse still) for ~5 seconds, then look at+ Activity Monitor (the app's renderer + GPU processes) or DevTools' Performance/Rendering FPS+ meter: the frame pipeline goes QUIET rather than ticking at the display's refresh rate. Then:+ - type in one terminal → it repaints **immediately**, no perceptible first-keystroke delay+ (this is the `onDamage` wake, the mechanism);+ - pan and zoom the canvas → everything keeps repainting smoothly throughout;+ - switch to another application for a minute and come back → the canvas is live again+ (focus/visibilitychange wake).+ **BLOCKING symptom to name explicitly: if ANY terminal ever stops repainting until you drag+ it, click it, or resize something, that is a MISSED WAKE** — the failure this design fears,+ and far worse than the idle CPU it saves. Report it with what the terminal was doing when it+ froze and how long it stayed frozen (a heartbeat is supposed to heal it within ~1 second, so a+ freeze that lasts longer than that means the heartbeat is gone too).## 5. Failure pathsdiff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsxindex 82ca7ab02..204ceac24 100644--- a/src/renderer/canvas/SharedGlyphLayer.tsx+++ b/src/renderer/canvas/SharedGlyphLayer.tsx@@ -38,6 +38,7 @@ import {} from '../glyphgrid/atlas'import type { Camera } from '../glyphgrid/camera'import { GlyphGridEngine } from '../glyphgrid/engine'+import { createFrameLoop } from '../glyphgrid/frame-driver'import type { GlyphGL } from '../glyphgrid/gl'import { createWebgl2GL } from '../glyphgrid/gl-webgl2'import { createCanvasRasterizer } from '../glyphgrid/raster'@@ -1064,24 +1065,38 @@ export function SharedGlyphLayer(): JSX.Element {// monitor) leaves the CSS box identical while the backing store must change.window.addEventListener('resize', pushViewport)- let raf = 0- const tick = (): void => {- // The context can be torn down synchronously between the schedule and this callback (font- // change, mode switched off). Skipping the frame — and NOT rescheduling — leaves the loop to- // the effect run that the accompanying generation bump triggers; the cleanup below cancels- // this handle either way.- if (ctx.disposed) return- try {- ctx.engine.frame()- } catch (err) {- // `frame()` rethrows by contract, having restored its own damage. There is no recovery in- // 1b: the whole session goes back to the DOM renderer.- failSharedGlyph('frame threw', err)- return // no reschedule — the cleanup below still cancels the (already fired) handle- }- raf = requestAnimationFrame(tick)+ // The frame loop PARKS when the canvas goes quiet — an always-registered rAF keeps Chromium's+ // whole frame pipeline ticking at the display's refresh rate to draw nothing. All the+ // scheduling and the park/heartbeat policy live in `createFrameLoop` (unit-tested there); this+ // effect only supplies the seams and the wake signals.+ const loop = createFrameLoop({+ // The context can be torn down synchronously between a schedule and its callback (font+ // change, mode switched off); the loop stops itself rather than rescheduling, and the+ // cleanup below is idempotent either way.+ alive: () => !ctx.disposed,+ frame: () => ctx.engine.frame(),+ // `frame()` rethrows by contract, having restored its own damage. There is no recovery in+ // 1b: the whole session goes back to the DOM renderer.+ onError: (err) => failSharedGlyph('frame threw', err),+ requestFrame: (cb) => requestAnimationFrame(cb),+ cancelFrame: (h) => cancelAnimationFrame(h),+ setTimer: (cb, ms) => window.setTimeout(cb, ms),+ clearTimer: (h) => window.clearTimeout(h)+ })+ // THE wake mechanism: the engine funnels every damage write through `markDirty`, which calls+ // out on the clean→dirty edge. A parked loop resumes on the very next damaging write.+ const damage = ctx.engine.onDamage(() => loop.wake())+ // Belt and braces for the background-throttling case (Task 9): a park entered while the window+ // was occluded must not outlive the return, and a throttled/coalesced rAF can leave the loop+ // parked with damage pending. Both are cheap — `wake()` only schedules a frame that draws+ // nothing when there is nothing to draw.+ const onVisible = (): void => {+ if (!document.hidden) loop.wake()}- raf = requestAnimationFrame(tick)+ const onFocus = (): void => loop.wake()+ window.addEventListener('focus', onFocus)+ document.addEventListener('visibilitychange', onVisible)+ loop.start()// Phase 2 owns real context restoration; here a lost context is simply the end of the shared// renderer for this session. `preventDefault()` is deliberately NOT called — that is the@@ -1090,7 +1105,15 @@ export function SharedGlyphLayer(): JSX.Element {canvas.addEventListener('webglcontextlost', onLost)return () => {- cancelAnimationFrame(raf)+ // Everything the loop owns goes at once — the pending frame, the heartbeat TIMER and the+ // damage subscription. A surviving timer would keep calling `frame()` on a context this+ // effect run has let go of, and a surviving subscription would keep a dead loop reachable+ // from the engine. `stop()` is idempotent, so the `ctx.disposed` and `failSharedGlyph` paths+ // (which stop the loop themselves) land here safely too.+ loop.stop()+ damage.dispose()+ window.removeEventListener('focus', onFocus)+ document.removeEventListener('visibilitychange', onVisible)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 fcdd4a208..364834a86 100644--- a/src/renderer/glyphgrid/engine.test.ts+++ b/src/renderer/glyphgrid/engine.test.ts@@ -655,6 +655,94 @@ describe('per-grid buffers + row-range damage', () => {expect(e.frame()).toBe(false)})+})++/** The wake signal the parked rAF driver resumes on — see `createFrameLoop`. The whole point is+ * that it fires on the clean→dirty EDGE, so a busy terminal costs one call per frame at most+ * instead of one per row write. */+describe('onDamage', () => {+ it('fires on the clean→dirty transition and not again while already dirty', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('a', 0, 0, { rows: 3 }))+ e.frame() // consume the registration damage — the engine is clean from here+ const woke = vi.fn()+ e.onDamage(woke)+ h.updateRow(0, rowOf(2))+ expect(woke).toHaveBeenCalledTimes(1)+ // Already dirty: sixty row writes before the next frame are still ONE wake.+ h.updateRow(1, rowOf(2))+ h.updateRow(2, rowOf(2))+ e.setCamera({ x: 5, y: 0, zoom: 1 })+ expect(woke).toHaveBeenCalledTimes(1)+ })++ it('fires again after a frame() has cleared the flag', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('a', 0, 0, { rows: 3 }))+ e.frame()+ const woke = vi.fn()+ e.onDamage(woke)+ h.updateRow(0, rowOf(2))+ e.frame() // clears the flag+ h.updateRow(1, rowOf(2))+ expect(woke).toHaveBeenCalledTimes(2)+ })++ it('a HIDDEN grid’s updateRow does not fire it', () => {+ // The visibility-scoped damage rule, restated at the wake seam: a hidden grid's write sets+ // only ITS row range, so it must neither dirty the engine nor un-park the driver. Waking the+ // loop for a grid the frame would cull is the exact cost that rule exists to remove.+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(100, 100, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('far', 5000, 0, { rows: 3 }))+ e.frame() // registration damage; the grid is culled, so it is recorded as hidden+ const woke = vi.fn()+ e.onDamage(woke)+ h.updateRow(1, rowOf(2))+ expect(woke).not.toHaveBeenCalled()+ // …and the frame that brings it back into view still wakes, because the camera dirties+ // unconditionally — the leg the whole optimization stands on.+ e.setCamera({ x: -5000, y: 0, zoom: 1 })+ expect(woke).toHaveBeenCalledTimes(1)+ })++ it('stops delivering after the subscription is disposed', () => {+ const e = new GlyphGridEngine(fakeGL(), atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ const h = e.register(spec('a', 0, 0, { rows: 3 }))+ e.frame()+ const woke = vi.fn()+ const sub = e.onDamage(woke)+ sub.dispose()+ h.updateRow(0, rowOf(2))+ expect(woke).not.toHaveBeenCalled()+ })++ it('restoring damage after a throwing frame wakes the driver again', () => {+ // The damage-restore path in frame()'s catch is a clean→dirty transition like any other: the+ // canvas is half-drawn and owes a redraw, so a PARKED driver has to hear about it.+ const gl = fakeGL()+ const e = new GlyphGridEngine(gl, atlas())+ e.setViewport(800, 600, 1)+ e.setCamera({ x: 0, y: 0, zoom: 1 })+ e.register(spec('a', 0))+ const woke = vi.fn()+ e.onDamage(woke)+ gl.beginFrame = () => {+ throw new Error('context lost')+ }+ expect(() => e.frame()).toThrow('context lost')+ expect(woke).toHaveBeenCalledTimes(1)+ })+})++describe('plate params', () => {it('drawGrid receives the plate params (bgColor + plate rect) with the grid geometry', () => {const gl = fakeGL()const e = new GlyphGridEngine(gl, atlas())diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.tsindex 1db6155d9..031efce27 100644--- a/src/renderer/glyphgrid/engine.ts+++ b/src/renderer/glyphgrid/engine.ts@@ -129,6 +129,8 @@ export class GlyphGridEngine {* setViewport always reaches the GL surface even if it passes the current w/h. */private viewDpr = 0private dirty = false+ /** Wake subscribers, notified by `markDirty` on the clean→dirty EDGE only — see `onDamage`. */+ private damageListeners = new Set<() => void>()private seq = 0/** False until an atlas source has actually reached the GPU — see `atlasUploadPending`. */private atlasUploaded = false@@ -138,6 +140,43 @@ export class GlyphGridEngine {private atlas: GlyphAtlas) {}+ /**+ * The ONE writer of the `dirty` flag. Every mutator routes its damage through here, so the wake+ * signal below cannot drift out of sync with the flag `frame()` gates on — a direct+ * `dirty = true` somewhere would be damage the parked driver never hears about, and a canvas+ * that stops repainting until the user drags something.+ *+ * Notifies on the clean→dirty TRANSITION only: a terminal streaming output dirties the engine on+ * every row write, and calling out sixty times per frame would make the wake more expensive than+ * the loop it saves. Once dirty, the driver is already coming.+ */+ private markDirty(): void {+ if (this.dirty) return+ this.dirty = true+ for (const fn of this.damageListeners) fn()+ }++ /**+ * Subscribe to damage — the signal the rAF driver parks against (see `createFrameLoop`). Fires+ * when the engine goes from clean to dirty, i.e. exactly when an idle canvas has something new+ * to draw.+ *+ * Deliberately says nothing about a HIDDEN grid's row writes: those do not dirty the engine (see+ * `updateRow`), so they do not wake the loop either. Their damage rides the frame that brings+ * the grid back into view, and every input that can change visibility dirties unconditionally.+ *+ * A listener must not call `frame()` inline — it runs inside the mutator that caused the damage,+ * and the driver's contract is to SCHEDULE.+ */+ onDamage(cb: () => void): { dispose(): void } {+ this.damageListeners.add(cb)+ return {+ dispose: () => {+ this.damageListeners.delete(cb)+ }+ }+ }+register(spec: GridSpec): GridHandle {if (this.grids.has(spec.id))throw new Error(`glyphgrid: grid "${spec.id}" already registered — dispose it first`)@@ -154,7 +193,7 @@ export class GlyphGridEngine {}this.grids.set(spec.id, grid)this.gl.createGrid(spec.id, spec.cols, spec.rows)- this.dirty = true+ this.markDirty()const engine = this// Inertness rides on `grid.dead`: once this handle's dispose() — or the engine-wide// disposeAll() — has run, every mutator below is a silent no-op. The constraint is that a@@ -188,14 +227,14 @@ export class GlyphGridEngine {// view is always drawn, and its upload pass replays the range accumulated while it was// hidden — deferred, never lost. Do not "optimize" any of those into a visibility-scoped// dirty; that is the leg this stands on.- if (grid.lastVisible) engine.dirty = true+ if (grid.lastVisible) engine.markDirty()},setOrigin(x, y) {if (grid.dead) returnif (grid.originX === x && grid.originY === y) returngrid.originX = xgrid.originY = y- engine.dirty = true+ engine.markDirty()},setPlateRect(x, y, w, h) {if (grid.dead) return@@ -208,13 +247,13 @@ export class GlyphGridEngine {grid.plateY = ygrid.plateW = wgrid.plateH = h- engine.dirty = true+ engine.markDirty()},setZ(z) {if (grid.dead) returnif (grid.z === z) returngrid.z = z- engine.dirty = true+ engine.markDirty()},resize(cols, rows) {if (grid.dead) return@@ -240,7 +279,7 @@ export class GlyphGridEngine {engine.gl.createGrid(grid.id, cols, rows)grid.dirtyFrom = 0grid.dirtyTo = rows - 1- engine.dirty = true+ engine.markDirty()},dispose() {// The handle goes inert unconditionally — this is its owner declaring teardown, and it@@ -252,7 +291,7 @@ export class GlyphGridEngine {if (engine.grids.get(grid.id) !== grid) returnengine.grids.delete(grid.id)engine.gl.disposeGrid(grid.id)- engine.dirty = true+ engine.markDirty()}}}@@ -279,13 +318,13 @@ export class GlyphGridEngine {}this.grids.clear()// Teardown is damage: the canvas still holds the disposed grids' pixels until it is redrawn.- this.dirty = true+ this.markDirty()}setCamera(cam: Camera): void {if (cam.x === this.camera.x && cam.y === this.camera.y && cam.zoom === this.camera.zoom) returnthis.camera = { ...cam }- this.dirty = true+ this.markDirty()}setViewport(w: number, h: number, dpr: number): void {@@ -298,7 +337,7 @@ export class GlyphGridEngine {this.viewH = hthis.viewDpr = dprthis.gl.resize(w, h, dpr)- this.dirty = true+ this.markDirty()}/** Visible grid ids in draw order (z ascending, ties by registration order).@@ -432,7 +471,7 @@ export class GlyphGridEngine {}this.gl.endFrame()} catch (err) {- this.dirty = true+ this.markDirty()throw err}return truediff --git a/src/renderer/glyphgrid/frame-driver.test.ts b/src/renderer/glyphgrid/frame-driver.test.tsnew file mode 100644index 000000000..a255e29f2--- /dev/null+++ b/src/renderer/glyphgrid/frame-driver.test.ts@@ -0,0 +1,255 @@+import { describe, expect, it, vi } from 'vitest'+import {+ createFrameLoop,+ HEARTBEAT_MS,+ IDLE_FRAMES_BEFORE_PARK,+ shouldPark,+ type FrameLoopHost+} from './frame-driver'++/**+ * A hand-driven scheduler: nothing runs until the test says so, so "did the loop reschedule?" is+ * an assertion about the pending handle rather than about wall-clock time. rAF and timer handles+ * are distinct id spaces on purpose — a cancel that reached the wrong one would otherwise pass.+ */+function harness(opts: { draws?: boolean[] } = {}) {+ const draws = opts.draws ? [...opts.draws] : []+ let pendingFrame: (() => void) | null = null+ let frameHandle = 0+ let pendingTimer: { cb: () => void; ms: number } | null = null+ let timerHandle = 0+ let alive = true+ const errors: unknown[] = []+ const frame = vi.fn(() => (draws.length ? !!draws.shift() : false))++ const host: FrameLoopHost = {+ frame,+ alive: () => alive,+ onError: (err) => {+ errors.push(err)+ },+ requestFrame: (cb) => {+ pendingFrame = cb+ return ++frameHandle+ },+ cancelFrame: () => {+ pendingFrame = null+ },+ setTimer: (cb, ms) => {+ pendingTimer = { cb, ms }+ return ++timerHandle+ },+ clearTimer: () => {+ pendingTimer = null+ }+ }++ return {+ host,+ frame,+ errors,+ loop: createFrameLoop(host),+ /** Is a frame scheduled? — i.e. is the loop still running rather than parked. */+ scheduled: () => pendingFrame !== null,+ timer: () => pendingTimer,+ kill: () => {+ alive = false+ },+ /** Run the pending rAF callback (which may schedule the next one). */+ runFrame: () => {+ const cb = pendingFrame+ pendingFrame = null+ cb?.()+ },+ /** Run `n` frames, stopping early if the loop parks. */+ runFrames: (n: number) => {+ for (let i = 0; i < n; i++) {+ if (!pendingFrame) return+ const cb = pendingFrame+ pendingFrame = null+ cb()+ }+ },+ runTimer: () => {+ const t = pendingTimer+ pendingTimer = null+ t?.cb()+ },+ setDraws: (next: boolean[]) => {+ draws.length = 0+ draws.push(...next)+ }+ }+}++describe('shouldPark', () => {+ it('never parks on the first idle frame — a two-frame gap between keystrokes must not thrash', () => {+ expect(shouldPark(0)).toBe(false)+ expect(shouldPark(1)).toBe(false)+ expect(shouldPark(IDLE_FRAMES_BEFORE_PARK - 1)).toBe(false)+ })++ it('parks once the streak reaches the threshold', () => {+ expect(shouldPark(IDLE_FRAMES_BEFORE_PARK)).toBe(true)+ expect(shouldPark(IDLE_FRAMES_BEFORE_PARK + 10)).toBe(true)+ })++ it('the threshold is about half a second of frames, not a couple', () => {+ expect(IDLE_FRAMES_BEFORE_PARK).toBeGreaterThanOrEqual(20)+ })+})++describe('createFrameLoop', () => {+ it('keeps rescheduling while frames draw', () => {+ const h = harness({ draws: Array(50).fill(true) })+ h.loop.start()+ h.runFrames(50)+ expect(h.frame).toHaveBeenCalledTimes(50)+ expect(h.scheduled()).toBe(true)+ })++ it('parks after the idle threshold and not before, and arms the heartbeat when it does', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK - 1)+ expect(h.scheduled()).toBe(true) // still running — an idle blip is not a park+ expect(h.timer()).toBeNull()+ h.runFrame() // the frame that completes the streak+ expect(h.scheduled()).toBe(false) // parked: no rAF registered, so Chromium can idle+ expect(h.timer()?.ms).toBe(HEARTBEAT_MS)+ })++ it('a drawn frame resets the idle streak', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK - 1)+ h.setDraws([true])+ h.runFrame() // drew → streak back to zero+ h.runFrames(IDLE_FRAMES_BEFORE_PARK - 1)+ expect(h.scheduled()).toBe(true)+ })++ it('wake() un-parks: it cancels the heartbeat and resumes the rAF loop', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ expect(h.scheduled()).toBe(false)+ h.loop.wake()+ expect(h.timer()).toBeNull()+ expect(h.scheduled()).toBe(true)+ h.setDraws([true])+ h.runFrame()+ expect(h.frame).toHaveBeenCalledTimes(IDLE_FRAMES_BEFORE_PARK + 1)+ })++ it('a wake while already running neither double-schedules nor draws synchronously', () => {+ const h = harness({ draws: [true] })+ h.loop.start()+ const before = h.frame.mock.calls.length+ h.loop.wake()+ h.loop.wake()+ expect(h.frame).toHaveBeenCalledTimes(before) // wake SCHEDULES, it never draws inline+ h.runFrame()+ expect(h.scheduled()).toBe(true)+ h.runFrame() // the single pending callback — a double schedule would show as an extra frame+ expect(h.frame).toHaveBeenCalledTimes(before + 2)+ })++ it('a wake right before the park frame keeps the loop running', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK - 1)+ h.loop.wake() // damage arrived: the streak must not carry over into a park+ h.runFrame()+ expect(h.scheduled()).toBe(true)+ })++ it('the parked heartbeat draws one frame and re-arms itself when nothing changed', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ const parkedAt = h.frame.mock.calls.length+ h.runTimer()+ expect(h.frame).toHaveBeenCalledTimes(parkedAt + 1) // exactly one no-op frame per second+ expect(h.scheduled()).toBe(false) // nothing drew → still parked+ expect(h.timer()?.ms).toBe(HEARTBEAT_MS) // …and the net stays armed+ })++ it('the heartbeat resumes the loop when it DOES draw — the missed-wake safety net', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.setDraws([true])+ h.runTimer()+ expect(h.scheduled()).toBe(true) // back on rAF+ expect(h.timer()).toBeNull() // and the heartbeat stood down+ })++ it('stop() clears the rAF and the heartbeat, and wake() afterwards is inert', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK) // park → heartbeat armed+ h.loop.stop()+ expect(h.timer()).toBeNull()+ expect(h.scheduled()).toBe(false)+ const after = h.frame.mock.calls.length+ h.loop.wake()+ expect(h.scheduled()).toBe(false) // a late onDamage must not resurrect a torn-down loop+ expect(h.frame).toHaveBeenCalledTimes(after)+ })++ it('stop() while running cancels the pending frame', () => {+ const h = harness({ draws: Array(10).fill(true) })+ h.loop.start()+ h.runFrame()+ h.loop.stop()+ expect(h.scheduled()).toBe(false)+ })++ it('a dead host stops the loop instead of rescheduling — no timer outlives the context', () => {+ const h = harness({ draws: Array(10).fill(true) })+ h.loop.start()+ h.kill()+ h.runFrame()+ expect(h.frame).not.toHaveBeenCalled() // the disposal is checked BEFORE touching the engine+ expect(h.scheduled()).toBe(false)+ expect(h.timer()).toBeNull()+ })++ it('a dead host stops the loop from the heartbeat too', () => {+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.kill()+ h.runTimer()+ expect(h.scheduled()).toBe(false)+ expect(h.timer()).toBeNull()+ })++ it('a throwing frame reports the error once and leaves nothing scheduled', () => {+ const boom = new Error('context lost')+ const h = harness()+ h.host.frame = () => {+ throw boom+ }+ h.loop.start()+ h.runFrame()+ expect(h.errors).toEqual([boom])+ expect(h.scheduled()).toBe(false)+ expect(h.timer()).toBeNull()+ })++ it('a throwing heartbeat frame reports and tears down as well', () => {+ const boom = new Error('context lost')+ const h = harness()+ h.loop.start()+ h.runFrames(IDLE_FRAMES_BEFORE_PARK)+ h.host.frame = () => {+ throw boom+ }+ h.runTimer()+ expect(h.errors).toEqual([boom])+ expect(h.scheduled()).toBe(false)+ expect(h.timer()).toBeNull()+ })+})diff --git a/src/renderer/glyphgrid/frame-driver.ts b/src/renderer/glyphgrid/frame-driver.tsnew file mode 100644index 000000000..16296a2b4--- /dev/null+++ b/src/renderer/glyphgrid/frame-driver.ts@@ -0,0 +1,152 @@+/**+ * The shared canvas's frame loop, extracted from the React effect that owns it so its one+ * non-obvious behaviour — parking — is testable without a GPU, a DOM or a rendered component.+ *+ * **Why park at all.** `GlyphGridEngine.frame()` returns false when there was no damage, and an+ * idle canvas returns false forever. But while a rAF callback is registered Chromium keeps the+ * BeginFrame pipeline running: the renderer main thread, the compositor and the GPU process all+ * tick at the display's refresh rate to produce nothing. That is a floor you cannot get under, and+ * the shared renderer is meant to become the default.+ *+ * **The failure that matters is the opposite one.** A missed wake is not a slow canvas, it is a+ * FROZEN one — every shared terminal stops repainting until something incidentally dirties the+ * engine. So the design is deliberately conservative in three ways: the wake is an edge-triggered+ * subscription on the single writer of the dirty flag (`GlyphGridEngine.markDirty`), the park only+ * happens after a long idle streak, and a heartbeat re-checks while parked so a wake that was+ * somehow missed costs a second of staleness instead of the session.+ *+ * The loop owns no DOM: rAF, timers, liveness and the error policy are all injected, and the wake+ * signals (damage, window focus, visibilitychange) are wired by the host — see `SharedGlyphLayer`.+ */++/**+ * Consecutive no-damage frames before the loop parks — half a second at 60 Hz, a quarter at 120.+ *+ * Not one, and not two: a canvas goes quiet for a handful of frames between keystrokes, and+ * parking on the first idle frame would toggle the loop on and off continuously — burning the+ * park/unpark bookkeeping at input rate and putting a scheduling hop in front of every character.+ * Half a second is long enough that only a genuinely still canvas reaches it, and short enough+ * that the idle case (the one being paid for) is reached almost immediately.+ */+export const IDLE_FRAMES_BEFORE_PARK = 30++/** How often a parked loop re-checks for damage. See `beat` — this is a NET, not the mechanism. */+export const HEARTBEAT_MS = 1000++/** The park decision, pulled out so the threshold is asserted rather than assumed. */+export function shouldPark(consecutiveIdleFrames: number): boolean {+ return consecutiveIdleFrames >= IDLE_FRAMES_BEFORE_PARK+}++export interface FrameLoopHost {+ /** `GlyphGridEngine.frame()`: draws if dirty, returns whether it drew, rethrows on GL error+ * having restored its own damage. */+ frame(): boolean+ /** False once the shared context has been torn down. Checked before every `frame()` — the+ * context can die synchronously between a schedule and its callback. */+ alive(): boolean+ /** Terminal error policy (the layer fails the whole shared session back to the DOM renderer).+ * The loop has already stopped itself by the time this is called. */+ onError(err: unknown): void+ requestFrame(cb: () => void): number+ cancelFrame(handle: number): void+ setTimer(cb: () => void, ms: number): number+ clearTimer(handle: number): void+}++export interface FrameLoop {+ /** Begin drawing. Idempotent. */+ start(): void+ /** "There is damage" — resume immediately if parked, otherwise just reset the idle streak.+ * Never draws inline: it runs inside the mutator that caused the damage. Inert after `stop`. */+ wake(): void+ /** Cancel everything: the pending frame, the heartbeat, and any future wake. Idempotent. */+ stop(): void+}++export function createFrameLoop(host: FrameLoopHost): FrameLoop {+ let raf = 0+ let heartbeat = 0+ let idleFrames = 0+ let stopped = false++ const stop = (): void => {+ stopped = true+ if (raf) host.cancelFrame(raf)+ if (heartbeat) host.clearTimer(heartbeat)+ raf = 0+ heartbeat = 0+ }++ /** Everything that runs a frame shares this: liveness first, error policy second. Returns+ * whether the loop is still alive afterwards. */+ const drawOnce = (): { alive: boolean; drew: boolean } => {+ if (!host.alive()) {+ // The context was torn down between the schedule and this callback (font change, mode+ // switched off). Stop rather than reschedule — including the heartbeat, which must never+ // outlive the context it was checking.+ stop()+ return { alive: false, drew: false }+ }+ try {+ return { alive: true, drew: host.frame() }+ } catch (err) {+ stop()+ host.onError(err)+ return { alive: false, drew: false }+ }+ }++ const park = (): void => {+ raf = 0+ heartbeat = host.setTimer(beat, HEARTBEAT_MS)+ }++ const runLoop = (): void => {+ if (heartbeat) {+ host.clearTimer(heartbeat)+ heartbeat = 0+ }+ idleFrames = 0+ if (!raf) raf = host.requestFrame(tick)+ }++ const tick = (): void => {+ raf = 0+ const { alive, drew } = drawOnce()+ if (!alive) return+ idleFrames = drew ? 0 : idleFrames + 1+ if (shouldPark(idleFrames)) park()+ else raf = host.requestFrame(tick)+ }++ /**+ * The safety NET, not the mechanism — the mechanism is the `onDamage` wake, and this exists for+ * the case where that wake never arrives (a damage path that somehow bypasses `markDirty`, a+ * listener lost to a teardown race, a pending atlas upload that is damage without being a dirty+ * flag). One no-op frame per second draws nothing when there is nothing to draw, and it turns+ * "frozen until the user drags a node" into "at most a second stale".+ */+ const beat = (): void => {+ heartbeat = 0+ const { alive, drew } = drawOnce()+ if (!alive) return+ if (drew) runLoop()+ else heartbeat = host.setTimer(beat, HEARTBEAT_MS)+ }++ return {+ start(): void {+ if (stopped || raf) return+ idleFrames = 0+ raf = host.requestFrame(tick)+ },+ wake(): void {+ // Inert after teardown: a late `onDamage` (or a focus event racing the cleanup) must not+ // resurrect a loop whose context is gone.+ if (stopped) return+ runLoop()+ },+ stop+ }+}