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
Merge branch 'p2/ctxloss' into feat/glyphgrid-phase2
enesd068487022cc
diff --cc src/renderer/canvas/SharedGlyphLayer.tsxindex 9f604100e,9a1fb7bbf..0e8f62895--- a/src/renderer/canvas/SharedGlyphLayer.tsx+++ b/src/renderer/canvas/SharedGlyphLayer.tsx@@@ -1523,117 -1641,171 +1722,181 @@@ export function SharedGlyphLayer(): JSX// monitor) leaves the CSS box identical while the backing store must change.window.addEventListener('resize', pushViewport)- // 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.- //- // The gate around it answers the case the park cannot: the kanban board covering the canvas.- // It owns starting and stopping (including the "mounted while the board is already up" case),- // which is why there is no `loop.start()` here — see `createBoardFrameGate`.- const gate = createBoardFrameGate(boardCoversCanvas, () =>- createFrameLoop({- // The context can be torn down synchronously between a schedule and its callback (font- // change, dpr 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)+ /**+ * 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+ * damage subscription and the four store/window subscriptions that can wake or rebuild any of+ * them. A single survivor is a frame submitted against GPU objects that no longer exist — which+ * the driver's catch reads as a GPU failure and answers by burning the session that is in the+ * middle of recovering. And a single thing started twice is two rAF chains on one canvas.+ *+ * The mount path and the restore path therefore run the same function, and the cleanup below+ * and the suspend path run the same `stop()`.+ */+ const startRuntime = (): { stop(): void } => {+ // 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+ // only supplies the seams and the wake signals.+ //+ // The gate around it answers the case the park cannot: the kanban board covering the canvas.+ // It owns starting and stopping (including the "mounted while the board is already up" case),+ // which is why there is no `loop.start()` here — see `createBoardFrameGate`.+ const gate = createBoardFrameGate(boardCoversCanvas, () =>+ createFrameLoop({+ // The context can be torn down synchronously between a schedule and its callback (font+ // change, dpr 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. A throw is a GL error+ // rather than a lost context (that arrives as an EVENT, handled below), and there is no+ // recovery from it: 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)+ })+ )+ // ONE blink clock for the whole canvas — not one per terminal — because at most one terminal+ // has focus. It reaches the loop through `gate.loop()` for the same reason the damage+ // subscription does, and its own repaints take `pulse()` rather than `wake()`; see+ // `createCursorBlinkClock` for why that distinction is the whole task.+ const clock = createCursorBlinkClock({+ enabled: () => useSettings.getState().settings.cursorBlink,+ covered: boardCoversCanvas,+ target: cursorBlinkTarget,+ loop: () => gate.loop(),+ setInterval: (cb, ms) => window.setInterval(cb, ms),+ clearInterval: (h) => window.clearInterval(h)})- )- // ONE blink clock for the whole canvas — not one per terminal — because at most one terminal- // has focus. It reaches the loop through `gate.loop()` for the same reason the damage- // subscription does, and its own repaints take `pulse()` rather than `wake()`; see- // `createCursorBlinkClock` for why that distinction is the whole task.- const clock = createCursorBlinkClock({- enabled: () => useSettings.getState().settings.cursorBlink,- covered: boardCoversCanvas,- target: cursorBlinkTarget,- loop: () => gate.loop(),- setInterval: (cb, ms) => window.setInterval(cb, ms),- clearInterval: (h) => window.clearInterval(h)- })- // Mounted with a terminal already focused (a remount, a project switch back) must start the- // clock, exactly as the gate reads the board flag at construction rather than assuming.- clock.sync()- // 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. Reached- // through `gate.loop()` and never captured — leaving the board builds a fresh loop, and a- // subscription pinned to the stopped one would freeze the canvas for the rest of the session.- //- // Routed through the clock, which is the only thing that can tell the blink's own repaint from- // everybody else's damage: its repaint is isolated in time and takes `pulse()` (one frame, still- // parked), while ordinary damage keeps the `wake()` it has always had.- const damage = ctx.engine.onDamage(() => clock.routeDamage())- // The two gates that can move without the board moving: the blink SETTING and which terminal- // holds focus. Both are change-gated inside `sync`.- const unsubBlinkTarget = subscribeCursorBlinkTarget(() => clock.sync())- const unsubBlinkSetting = useSettings.subscribe(() => clock.sync())- // ...and the cursor MOVING, which is not a gate at all: it holds the cursor solid and starts- // the period over, exactly as xterm does while you type. Its own channel, because `sync` is- // deliberately a no-op while the interval is already running.- const unsubBlinkRestart = subscribeCursorBlinkRestart(() => clock.restart())- // 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, and it is inert while the board is up.- const onVisible = (): void => {- if (!document.hidden) gate.loop().wake()- }- const onFocus = (): void => gate.loop().wake()- window.addEventListener('focus', onFocus)- document.addEventListener('visibilitychange', onVisible)- // Both stores, because either can move the board over this canvas: the view toggle, and a- // switch to a project that is already on it. `sync` is change-gated, so the projects store's- // chattier notifications (it is rewritten on every node serialization) cost a comparison.- // The board is the blink clock's third gate as well (a stopped loop cannot draw the phase), so- // the two are synced together — and the gate goes FIRST, so the clock reads the board through- // an already-updated loop.- const syncBoard = (): void => {- gate.sync()+ // Mounted with a terminal already focused (a remount, a project switch back, a restore that+ // never took focus away) must start the clock, exactly as the gate reads the board flag at+ // construction rather than assuming.clock.sync()+ // 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. Reached+ // through `gate.loop()` and never captured — leaving the board builds a fresh loop, and a+ // subscription pinned to the stopped one would freeze the canvas for the rest of the session.+ //+ // Routed through the clock, which is the only thing that can tell the blink's own repaint from+ // everybody else's damage: its repaint is isolated in time and takes `pulse()` (one frame, still+ // parked), while ordinary damage keeps the `wake()` it has always had.+ const damage = ctx.engine.onDamage(() => clock.routeDamage())+ // The two gates that can move without the board moving: the blink SETTING and which terminal+ // holds focus. Both are change-gated inside `sync`.+ const unsubBlinkTarget = subscribeCursorBlinkTarget(() => clock.sync())+ const unsubBlinkSetting = useSettings.subscribe(() => clock.sync())++ // ...and the cursor MOVING, which is not a gate at all: it holds the cursor solid and starts++ // the period over, exactly as xterm does while you type. Its own channel, because `sync` is++ // deliberately a no-op while the interval is already running.++ const unsubBlinkRestart = subscribeCursorBlinkRestart(() => clock.restart())+ // 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, and it is inert while the board is up.+ const onVisible = (): void => {+ if (!document.hidden) gate.loop().wake()+ }+ const onFocus = (): void => gate.loop().wake()+ window.addEventListener('focus', onFocus)+ document.addEventListener('visibilitychange', onVisible)+ // Both stores, because either can move the board over this canvas: the view toggle, and a+ // switch to a project that is already on it. `sync` is change-gated, so the projects store's+ // chattier notifications (it is rewritten on every node serialization) cost a comparison.+ // The board is the blink clock's third gate as well (a stopped loop cannot draw the phase), so+ // the two are synced together — and the gate goes FIRST, so the clock reads the board through+ // an already-updated loop.+ const syncBoard = (): void => {+ gate.sync()+ clock.sync()+ }+ const unsubView = useViewMode.subscribe(syncBoard)+ const unsubProjects = useProjects.subscribe(syncBoard)+ let stopped = false+ return {+ stop(): void {+ // Idempotent: the suspend path and the effect cleanup can both reach the same runtime+ // (a lost context that is immediately followed by an unmount), and every member below+ // would be stopped twice otherwise.+ if (stopped) return+ stopped = true+ // Everything the loop owns goes at once — the pending frame, the heartbeat TIMER and the+ // damage subscription — plus the two store subscriptions that can hand it a new one. A+ // surviving timer would keep calling `frame()` on a context this run has let go of, a+ // surviving damage subscription would keep a dead loop reachable from the engine, and a+ // surviving board subscription would BUILD a loop against a disposed context.+ // `gate.stop()` is idempotent and also makes a `sync` still in flight inert, so the+ // `ctx.disposed` and `failSharedGlyph` paths (which stop the loop themselves) land here+ // safely too.- // The clock goes FIRST, and before `gate.stop()`: it hands the cursor back SHOWN, and- // that restoring repaint still wants a live loop to draw it.++ // The clock goes FIRST, and before the unsubscribes: it hands the cursor back SHOWN, and++ // it can only do that while it still HOLDS the target — `stop()` drops it. What that buys++ // is the packed ROW, not a drawn frame: the `pulse()` it schedules is cancelled moments++ // later by `gate.stop()`, and the point is that the grid's buffers no longer hold a hidden++ // cursor, so whatever draws them next (a remount, the board closing) draws a cursor. Its++ // restore is guarded inside `stopClock`, so a throwing repack cannot skip the teardown++ // below it.+ clock.stop()+ unsubBlinkTarget()++ unsubBlinkRestart()+ unsubBlinkSetting()+ gate.stop()+ unsubView()+ unsubProjects()+ damage.dispose()+ window.removeEventListener('focus', onFocus)+ document.removeEventListener('visibilitychange', onVisible)+ }+ }}- const unsubView = useViewMode.subscribe(syncBoard)- const unsubProjects = useProjects.subscribe(syncBoard)-- // 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- // "please fire webglcontextrestored" request, and we have nothing to restore into.- const onLost = (): void => failSharedGlyph('context lost')+ let runtime = startRuntime()++ /**+ * A lost context is now SURVIVABLE — see `createContextLossPolicy` for the once-only rule and+ * the cooldown that keeps it from becoming a retry loop.+ *+ * The two halves are ordered against each other on purpose. On the way DOWN the runtime stops+ * before the engine drops its GPU objects, so no frame can be submitted in between; on the way+ * UP the GPU objects are rebuilt before a fresh runtime exists to schedule anything, so the+ * first frame of the new context has something to draw with. `reviveGpu` throws if the rebuild+ * fails, and the policy answers that with the permanent fallback — the runtime stays stopped,+ * which is the correct state for a session that is going back to the DOM renderer.+ */+ const policy = createContextLossPolicy({+ now: () => Date.now(),+ suspend: () => {+ runtime.stop()+ ctx.engine.suspendGpu()+ },+ revive: () => {+ ctx.engine.reviveGpu()+ runtime = startRuntime()+ },+ 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.+ const onLost = (e: Event): void => {+ if (policy.onLost()) e.preventDefault()+ }+ const onRestored = (): void => policy.onRestored()canvas.addEventListener('webglcontextlost', onLost)+ canvas.addEventListener('webglcontextrestored', onRestored)return () => {- // Everything the loop owns goes at once — the pending frame, the heartbeat TIMER and the- // damage subscription — plus the two store subscriptions that can hand it a new one. A- // surviving timer would keep calling `frame()` on a context this effect run has let go of, a- // surviving damage subscription would keep a dead loop reachable from the engine, and a- // surviving board subscription would BUILD a loop against a disposed context. `gate.stop()`- // is idempotent and also makes a `sync` still in flight inert, so the `ctx.disposed` and- // `failSharedGlyph` paths (which stop the loop themselves) land here safely too.- // The clock goes FIRST, and before the unsubscribes: it hands the cursor back SHOWN, and it- // can only do that while it still HOLDS the target — `stop()` drops it. What that buys is the- // packed row, not a drawn frame: the `pulse()` it schedules is cancelled moments later by- // `gate.stop()`, and the point is that the grid's buffers no longer hold a hidden cursor, so- // whatever draws them next (a remount, the board closing) draws a cursor. Its restore is- // guarded inside `stopClock`, so a throwing repack cannot skip the teardown below it. Nothing- // may outlive the context — this is also the teardown for the `ctx.disposed` and- // `failSharedGlyph` paths, both of which re-run this effect.- clock.stop()- unsubBlinkTarget()- unsubBlinkRestart()- unsubBlinkSetting()- gate.stop()- unsubView()- unsubProjects()- damage.dispose()- window.removeEventListener('focus', onFocus)- document.removeEventListener('visibilitychange', onVisible)+ // 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. 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)