Skip to content

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.

fix(webgl): explicit context loss on release, desktop cap raise + reload action

enesb9096e8b1b32
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 60a5fd6b6..773c3e8ff 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -275,24 +275,24 @@ const PRIMARY_VIEWER: ViewerId = ''
* sizing, pausing and detaching on its own. A `null` client (the relay host's detached sink) is
* NOT a composite subscriber; it keys the `sizes`/flow ledgers by literal `null`, exactly as before.
*
- * Encoding: `<clientId><viewerId>`. clientId is always a number (no space), so
+ * Encoding: `<clientId>\x00<viewerId>` (a literal NUL byte). clientId is always a number (no space), so
* `subClient` recovers the client from the FIRST space regardless of what the viewerId
- * (which arrives off the wire) contains. Absent viewerId ⇒ PRIMARY ⇒ `<clientId>`, i.e. one
+ * (which arrives off the wire) contains. Absent viewerId ⇒ PRIMARY ⇒ `<clientId>\x00`, i.e. one
* entry per client — bit-for-bit the pre-viewer ledger for every existing caller.
*/
type SubKey = string
function subKey(clientId: ClientId, viewerId: ViewerId): SubKey {
- return `${clientId}${viewerId}`
+ return `${clientId}\x00${viewerId}`
}
/** The ClientId behind a composite subscriber key — the collapse to "which person", for the
* per-ClientId data/exit/size channels and the closed-by/recycled fan-out (viewers are invisible
* to peers). */
function subClient(sub: SubKey): ClientId {
- return Number(sub.slice(0, sub.indexOf('')))
+ return Number(sub.slice(0, sub.indexOf('\x00')))
}
/** The viewer id within a composite subscriber key (PRIMARY for a default view). */
function subViewer(sub: SubKey): ViewerId {
- return sub.slice(sub.indexOf('') + 1)
+ return sub.slice(sub.indexOf('\x00') + 1)
}
/**
diff --git a/src/main/index.ts b/src/main/index.ts
index 88ed96d3a..452b9a2a4 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -118,6 +118,7 @@ import {
import { initPlatform } from '../core/platform'
import { electronPlatform } from './platform-electron'
import { wirePeerRegistry } from './peer-registry'
+import { WEBGL_CONTEXT_CAP_DESKTOP } from '../shared/webgl'
// Dev-only: NT_MULTI lets a SECOND instance run (host + client testing on one machine) with an
// isolated userData via NT_USER_DATA — its own device-id/session/license/workspace. Never active
@@ -125,6 +126,12 @@ import { wirePeerRegistry } from './peer-registry'
const NT_MULTI = !app.isPackaged && !!process.env.NT_MULTI
if (NT_MULTI && process.env.NT_USER_DATA) app.setPath('userData', process.env.NT_USER_DATA)
+// Raise Chromium's per-page WebGL context cap (default ~16) — a busy canvas wants more
+// GPU-rendered terminals than that. The renderer raises its own budget to match at boot
+// (main.tsx → setWebglBudget); see src/shared/webgl.ts for the invariant. Must be appended
+// before app 'ready' or the switch is silently ignored.
+app.commandLine.appendSwitch('max-active-webgl-contexts', String(WEBGL_CONTEXT_CAP_DESKTOP))
+
// First thing in bootstrap: install the Electron CorePlatform so anything in src/core
// (wired in later tasks) can resolve platform() at boot. Placed after the NT_MULTI
// userData override so userDataDir reads the final path; nothing consumes it yet.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index bc63de91f..5d227c7b6 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -57,6 +57,7 @@ import {
IconCanvasView,
IconLock,
IconMarkdown,
+ IconReload,
IconNote,
IconPhone,
IconProject,
@@ -3539,6 +3540,28 @@ export function Canvas() {
[setNodes, markDirty]
)
+ // Reload a terminal in place: bump `respawnNonce`, which re-runs TerminalNode's lifecycle
+ // effect — the old PTY client + xterm are torn down and a fresh attach is made to the SAME
+ // tmux session (persistKey = node id), so the session and anything running in it survive.
+ // Manual recovery for a terminal that never painted or lost its renderer (dead ssh attach,
+ // GPU context loss, stale screen after a long sleep). The transient nonce is never persisted.
+ const reloadTerminals = useCallback(
+ (ids: string[]) => {
+ const set = new Set(ids)
+ setNodes((ns) =>
+ ns.map((n) =>
+ set.has(n.id) && n.type === 'terminal'
+ ? {
+ ...n,
+ data: { ...n.data, respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1 }
+ }
+ : n
+ )
+ )
+ },
+ [setNodes]
+ )
+
// Run Claude's /branch in this node, then open a new node that resumes the original
// conversation (claude -r <ORIGINAL_ID>). The source node stays on the new branch.
// We already know the current session id from the hooks; only fall back to parsing the
@@ -3858,7 +3881,8 @@ export function Canvas() {
{ label: 'Collapse / Expand', icon: <IconCollapse />, onClick: () => toggleCollapseNodes(ids) },
...(ids.some((nid) => nodesRef.current.find((n) => n.id === nid)?.type === 'terminal')
? ([
- { label: 'Markdown view', icon: <IconMarkdown />, onClick: () => toggleMarkdown(ids) }
+ { label: 'Markdown view', icon: <IconMarkdown />, onClick: () => toggleMarkdown(ids) },
+ { label: 'Reload terminal', icon: <IconReload />, onClick: () => reloadTerminals(ids) }
] as MenuItem[])
: []),
{ type: 'separator' },
@@ -3875,6 +3899,7 @@ export function Canvas() {
alignToGrid,
toggleCollapseNodes,
toggleMarkdown,
+ reloadTerminals,
deleteNodes
]
)
diff --git a/src/renderer/components/icons.tsx b/src/renderer/components/icons.tsx
index 879c5aacf..7965eef5f 100644
--- a/src/renderer/components/icons.tsx
+++ b/src/renderer/components/icons.tsx
@@ -151,6 +151,13 @@ export const IconSettings = () => (
</svg>
)
+export const IconReload = () => (
+ <svg {...S}>
+ <path d="M20 12a8 8 0 1 1-2.34-5.66" />
+ <path d="M20 4v4h-4" />
+ </svg>
+)
+
export const IconBranch = () => (
<svg {...S}>
<circle cx="6" cy="6" r="2.5" />
diff --git a/src/renderer/main.tsx b/src/renderer/main.tsx
index bbb75c8dd..b8f299539 100644
--- a/src/renderer/main.tsx
+++ b/src/renderer/main.tsx
@@ -6,6 +6,15 @@ async function bootstrap(): Promise<void> {
const { installWsBridge } = await import('./bridge/ws-bridge')
const connected = await installWsBridge()
if (!connected) return // overlay is up; startReconnect reloads on the first reopen
+ } else {
+ // Electron desktop: main raised Chromium's WebGL context cap (--max-active-webgl-contexts),
+ // so the terminal GPU-renderer budget can rise to match. A browser tab (Server Edition)
+ // cannot raise its cap and stays on the default budget. See src/shared/webgl.ts.
+ const [{ setWebglBudget }, { WEBGL_BUDGET_DESKTOP }] = await Promise.all([
+ import('./terminal/webgl-budget'),
+ import('../shared/webgl')
+ ])
+ setWebglBudget(WEBGL_BUDGET_DESKTOP)
}
await import('./boot')
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 5806456f2..03a2f52bb 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -48,7 +48,7 @@ import {
xtermScrollback,
type SessionLife
} from '../terminal/terminal-config'
-import { registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'
+import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'
import { deliverCommand } from '../terminal/command-delivery'
import { FindBar } from '../components/FindBar'
import { IconSearch, IconChat, IconMic } from '../components/icons'
@@ -584,8 +584,9 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
cursorBlink: s.cursorBlink,
theme: { background: '#1e1e1e', foreground: '#e6e6e6' },
allowProposedApi: true,
- // Scrolling is xterm's job now (tmux's mouse is off), so it needs a real scrollback —
- // the default is 1000 lines. Capped: the cost is per node and a canvas holds many.
+ // NOT what the user scrolls in a tmux session — tmux's mouse is ON and the wheel scrolls
+ // tmux's own history (see pty-manager's tmuxConf). This buffer backs the plain-shell
+ // fallback (tmux unavailable) and the cold-snapshot replay. Capped: per node, many nodes.
scrollback: xtermScrollback(s.tmuxScrollback),
// Inside an app that requested mouse tracking (vim, htop) a plain drag goes to the app;
// Option/Alt forces a selection instead (Shift does the same via xterm's own bypass).
@@ -637,12 +638,20 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
}
const releaseWebgl = () => {
if (!webgl) return
+ // Capture the element BEFORE dispose (dispose detaches the addon's canvases). After the
+ // addon is gone, explicitly lose its context: addon dispose() alone leaves the context
+ // alive until GC, and Chromium counts un-GC'd contexts against its per-page cap — enough
+ // churn (fast pans cycling grants) and the zombies push the page past the cap, which is
+ // the "Too many active WebGL contexts" warning + force-evictions the budget exists to
+ // prevent. Not needed on the onContextLoss path: that context is already lost.
+ const canvases = term.element ? Array.from(term.element.querySelectorAll('canvas')) : null
try {
webgl.dispose()
} catch {
// already disposed via context loss
}
webgl = null
+ loseWebglContexts(canvases)
}
let sessionId: string | null = parked ? parked.sessionId : null
diff --git a/src/renderer/terminal/webgl-budget.test.ts b/src/renderer/terminal/webgl-budget.test.ts
index f86943de7..48c130765 100644
--- a/src/renderer/terminal/webgl-budget.test.ts
+++ b/src/renderer/terminal/webgl-budget.test.ts
@@ -2,6 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
registerWebglClient,
__resetWebglBudgetForTests,
+ getWebglBudget,
+ loseWebglContexts,
+ setWebglBudget,
WEBGL_ACQUIRE_DEBOUNCE_MS,
WEBGL_BUDGET,
WEBGL_LOSS_STREAK_MAX,
@@ -241,4 +244,57 @@ describe('webgl-budget coordinator', () => {
expect(b.rec.acquires).toBe(1)
b.handle.dispose()
})
+
+ it('setWebglBudget raises the grant ceiling (desktop, where the browser cap is raised too)', () => {
+ setWebglBudget(WEBGL_BUDGET + 4)
+ expect(getWebglBudget()).toBe(WEBGL_BUDGET + 4)
+ const clients = Array.from({ length: WEBGL_BUDGET + 4 }, (_, i) => fakeClient(`c${i}`))
+ clients.forEach(grant)
+ expect(clients.every((c) => c.rec.held)).toBe(true)
+ // The raised ceiling is still a ceiling: one more all-visible client is not granted.
+ const extra = fakeClient('extra')
+ grant(extra)
+ expect(extra.rec.held).toBe(false)
+ })
+
+ it('setWebglBudget ignores nonsense values and reset restores the default', () => {
+ setWebglBudget(0)
+ expect(getWebglBudget()).toBe(WEBGL_BUDGET)
+ setWebglBudget(NaN)
+ expect(getWebglBudget()).toBe(WEBGL_BUDGET)
+ setWebglBudget(20)
+ expect(getWebglBudget()).toBe(20)
+ __resetWebglBudgetForTests()
+ expect(getWebglBudget()).toBe(WEBGL_BUDGET)
+ })
+})
+
+describe('loseWebglContexts', () => {
+ /** Canvas-like fake: getContext('webgl2') returns `gl` (or throws), anything else null. */
+ function fakeCanvas(gl: unknown, opts: { throws?: boolean } = {}) {
+ return {
+ getContext(type: string) {
+ if (opts.throws) throw new Error('boom')
+ return type === 'webgl2' ? gl : null
+ }
+ }
+ }
+
+ it('explicitly loses the webgl2 context of every captured canvas', () => {
+ const lose = vi.fn()
+ const webglCanvas = fakeCanvas({ getExtension: (n: string) => (n === 'WEBGL_lose_context' ? { loseContext: lose } : null) })
+ const linkCanvas = fakeCanvas(null) // 2d-only layer: getContext('webgl2') → null
+ expect(loseWebglContexts([webglCanvas, linkCanvas] as never)).toBe(1)
+ expect(lose).toHaveBeenCalledTimes(1)
+ })
+
+ it('fails open on a throwing canvas and a missing extension', () => {
+ const bad = fakeCanvas(null, { throws: true })
+ const noExt = fakeCanvas({ getExtension: () => null })
+ expect(loseWebglContexts([bad, noExt] as never)).toBe(0)
+ })
+
+ it('returns 0 for a null canvas list', () => {
+ expect(loseWebglContexts(null)).toBe(0)
+ })
})
diff --git a/src/renderer/terminal/webgl-budget.ts b/src/renderer/terminal/webgl-budget.ts
index bf6a7c960..fbe58b54f 100644
--- a/src/renderer/terminal/webgl-budget.ts
+++ b/src/renderer/terminal/webgl-budget.ts
@@ -42,9 +42,66 @@
* a genuinely unstable GPU degrades to the DOM renderer exactly as before.
*/
-/** Ceiling on WebGL contexts we hold at once. Comfortably under Chromium's ~16-per-process cap. */
+/**
+ * DEFAULT ceiling on WebGL contexts we hold at once. Comfortably under Chromium's default
+ * ~16-per-page cap — which is what a BROWSER tab (Server Edition) gets. The desktop shell raises
+ * the browser cap itself (`--max-active-webgl-contexts` in src/main/index.ts), and the renderer
+ * raises the matching budget via `setWebglBudget` at boot (main.tsx). The invariant is the same
+ * everywhere: our budget stays comfortably under whatever the platform cap actually is.
+ */
export const WEBGL_BUDGET = 12
+/** Live ceiling — `WEBGL_BUDGET` unless the shell raised it (see `setWebglBudget`). */
+let budget = WEBGL_BUDGET
+
+/**
+ * Raise (or lower) the live budget. Called once at boot by the shell that knows its platform cap
+ * (desktop raises the Chromium cap to `WEBGL_CONTEXT_CAP_DESKTOP`, so it can afford a higher
+ * budget). Non-finite or < 1 values are ignored — a bad caller must not zero the ceiling.
+ */
+export function setWebglBudget(n: number): void {
+ if (!Number.isFinite(n) || n < 1) return
+ budget = Math.floor(n)
+}
+
+/** The live budget (test/introspection seam). */
+export function getWebglBudget(): number {
+ return budget
+}
+
+/**
+ * Explicitly lose the WebGL context of every canvas under `root` (a terminal's element), via
+ * `WEBGL_lose_context`. Chromium counts a context against its per-page cap until it is GC'd OR
+ * explicitly lost — and `@xterm/addon-webgl`'s dispose() does neither (verified on 0.18.0: zero
+ * `loseContext` calls). Without this, every release leaves a zombie context that still occupies
+ * a cap slot until some later GC, so real context count = granted + zombies could exceed the cap
+ * under churn (fast pan) even though the coordinator never exceeded its budget — surfacing as
+ * Chromium's "Too many active WebGL contexts" warning and force-evictions.
+ *
+ * Takes the CANVAS ELEMENTS, captured before the addon is disposed — dispose detaches them from
+ * the DOM, so a root query afterwards would find nothing, while held element references (and
+ * their contexts) stay valid. Safe on non-WebGL canvases: `getContext('webgl2')` on a canvas
+ * that already holds a 2d context returns null without creating anything. Returns how many
+ * contexts were lost.
+ */
+export function loseWebglContexts(canvases: ArrayLike<HTMLCanvasElement> | null): number {
+ if (!canvases) return 0
+ let lost = 0
+ for (const canvas of Array.from(canvases)) {
+ try {
+ const gl = canvas.getContext('webgl2') as WebGL2RenderingContext | null
+ const ext = gl?.getExtension('WEBGL_lose_context')
+ if (ext) {
+ ext.loseContext()
+ lost++
+ }
+ } catch {
+ // fail open — losing a context is an optimization, never worth breaking release for.
+ }
+ }
+ return lost
+}
+
/**
* How long a client must stay continuously visible before it is granted a context. Absorbs fast
* pans that sweep a node across the viewport for only a frame or two (which must not acquire).
@@ -166,7 +223,7 @@ function tryGrant(c: Client): void {
cancelAcquire(c)
// Guard: the client may have gone hidden or been disposed between debounce start and fire.
if (!clients.has(c.id) || !c.visible || c.granted) return
- if (grantCount() < WEBGL_BUDGET) {
+ if (grantCount() < budget) {
doGrant(c)
return
}
@@ -303,4 +360,5 @@ export function __resetWebglBudgetForTests(): void {
}
clients.clear()
visibilityClock = 0
+ budget = WEBGL_BUDGET
}
diff --git a/src/shared/webgl.ts b/src/shared/webgl.ts
new file mode 100644
index 000000000..bd6fef142
--- /dev/null
+++ b/src/shared/webgl.ts
@@ -0,0 +1,22 @@
+/**
+ * WebGL context-cap coordination between the desktop shell and the renderer.
+ *
+ * Chromium caps live WebGL contexts per page (default ~16); past it the browser force-evicts the
+ * least-recently-used context, which is what flashes a dead canvas on a visible terminal. The
+ * renderer's budget coordinator (`renderer/terminal/webgl-budget.ts`) keeps our own count under a
+ * budget so the cap is never hit — but the default cap leaves room for only ~12 GPU-rendered
+ * terminals on a busy canvas.
+ *
+ * On DESKTOP we control the browser too: main raises Chromium's cap via the
+ * `--max-active-webgl-contexts` switch (added for exactly this in crbug.com/771792), and the
+ * renderer raises the budget to match at boot (`main.tsx` → `setWebglBudget`). The two constants
+ * live together here so the "budget comfortably under the cap" invariant is visible in one place.
+ * A BROWSER tab (Server Edition) cannot raise its cap, so it stays on the default budget.
+ */
+
+/** Chromium's per-page WebGL context cap on desktop (`--max-active-webgl-contexts`). */
+export const WEBGL_CONTEXT_CAP_DESKTOP = 32
+
+/** Renderer budget on desktop — comfortably under `WEBGL_CONTEXT_CAP_DESKTOP`, same margin
+ * philosophy as the default 12-under-16. */
+export const WEBGL_BUDGET_DESKTOP = 24