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
feat(glyphgrid): experimental 'shared' renderer mode + device acceptance checklist
enesc59331722625
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.mdnew file mode 100644index 000000000..2435fca13--- /dev/null+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md@@ -0,0 +1,232 @@+# GlyphGrid Phase 1b — device acceptance checklist++**This document is the acceptance gate for the experimental shared terminal renderer.** Phase 1b+is code-complete and unit-tested, but the parts that matter most — WebGL2, xterm's internals,+layout, fonts, IME, the macOS compositor — have no coverage in the (node-environment) test suite+by design. Nothing here can be verified in CI; everything here has to be seen on a real machine.++Run it on the Mac, on a project with **at least a dozen terminals** (agent CLIs streaming output,+not idle shells). Tick each box only when the stated observation is what actually happened; note+anything else inline. Items marked **[1a]** re-run the Phase 1a acceptance so a regression in the+engine is caught before the integration is judged.++Branch: `feat/glyphgrid-engine`. Setting: **Settings → Terminal → Terminal rendering**+(`Auto (default)` / `GPU per terminal` / `Shared GPU (experimental)` / `Off (DOM renderer)`).++---++## 1. Setup and baseline++- [ ] **1.1 Default is untouched.** Fresh launch on this branch with an existing `settings.json`:+ the row reads **Auto (default)**, terminals look and behave exactly as they do on `main`.+ (Auto is the only mode most users will ever be on; a difference here is a release blocker.)+- [ ] **1.2 The row is a select, not a switch.** Four options in this order: Auto (default) /+ GPU per terminal / Shared GPU (experimental) / Off (DOM renderer). The description mentions+ that Shared GPU is experimental, "may render incorrectly", and "falls back to DOM on+ failure". Settings search for "gpu", "webgl", "shared" and "experimental" all find the row.+- [ ] **1.3 Baseline screenshots on Auto.** One busy terminal (agent CLI mid-run, colors, a box-+ drawing TUI) and one `ls --color` / `htop` screen, at 100% canvas zoom. These are the+ side-by-side reference for §2.+- [ ] **1.4 Context baseline.** DevTools → Rendering/Performance (or `about:gpu`): with+ **GPU per terminal** on a canvas of ~12 visible terminals, several WebGL contexts exist+ (budget-capped: 10 on macOS).+- [ ] **1.5 Flip to Shared.** No reload, no restart: the setting alone. **Exactly ONE** WebGL2+ context exists for the whole page afterwards, and the per-terminal ones are gone.+- [ ] **1.6 [1a] Harness green.** The Phase 1a harness still reports **43/43** on this machine.+- [ ] **1.7 [1a] Throughput.** The harness's rows-up/s figure is at or above the Phase 1a number+ recorded for this Mac.+- [ ] **1.8 [1a] Overlap trio.** The harness's three overlap cases (above / below / equal z) still+ paint in the stated order.++## 2. Visual parity (shared vs DOM)++- [ ] **2.1 Text, not a rectangle.** Every visible terminal shows its TEXT immediately after the+ flip — not a dark/blank body. (The node body is transparent in shared mode; what you see is+ the grid's own opaque plate plus glyphs.)+- [ ] **2.2 Side-by-side parity.** Same screens as 1.3, now in Shared: glyph shapes, spacing,+ baseline and line height match the DOM screenshots. No clipped descenders, no overlap+ between adjacent cells, no visible atlas seams.+- [ ] **2.3 Colors.** `ls --color` and `htop`: foreground/background colors, bold and dim, and the+ 256-color/truecolor ramps match the DOM rendering. Reverse-video cells (selected row in+ `htop`, `vim` visual mode) are inverted, not blank.+- [ ] **2.4 Plate is the body background.** The terminal body's background is the theme background,+ not the canvas dot grid — including the strip under the last row and around the padding.+- [ ] **2.5 Wide chars.** CJK (`日本語`) and emoji occupy two columns each, with the following text+ still on the same column grid as the DOM rendering. A wide glyph is not clipped in half.+- [ ] **2.6 Combining sequences.** A decomposed grapheme (e.g. `e` + U+0301) renders the BASE+ character — the accent may be missing, but never a lone accent mark on a blank cell.+- [ ] **2.7 Atlas fidelity at dpr 1 and 2.** On the retina display and on an external 1x display,+ with a non-default font family and size (e.g. Menlo 11, JetBrains Mono 16): text is crisp,+ not soft or doubled.+- [ ] **2.8 Selection visual.** Drag-select inside a terminal: the selection band covers exactly+ the selected cells, with correct fg/bg inversion, and matches what the DOM renderer draws.+- [ ] **2.9 Cursor.** A focused terminal shows a solid block cursor at the right cell. It is+ **static** — it does not blink even with "Cursor blink" on (known limitation L1).+- [ ] **2.10 Cursor at end of line.** Type until the cursor sits past the last column (deferred+ wrap): the cursor is drawn on the LAST column, not off-screen or on the next row.+- [ ] **2.11 Cursor hidden by a TUI.** Open a fullscreen CLI that hides the cursor (any agent CLI,+ `less`, `htop`): no stray block cursor is painted anywhere on the grid.+- [ ] **2.12 Blur.** Click away from a terminal: the cursor DISAPPEARS (the DOM renderer draws a+ hollow outline — known limitation L2), and the selection stays visible in the same color as+ when focused (known limitation L3). Judge whether either is acceptable to ship.+- [ ] **2.13 Plate geometry.** Look at the four corners and the right/bottom edges of a terminal+ body: the plate is a SQUARE rect under a node with rounded corners (L4), and up to one cell+ of fit slack at the right/bottom may show canvas rather than terminal background (L5). Judge+ how visible these are at normal zoom, and whether any padding seam shows on the left/top.+- [ ] **2.14 Scroll area after a font change.** Change the font size while shared is on, then look+ at the scrollbar/scroll area geometry: the thumb matches the content, no phantom region.++## 3. Interactions++- [ ] **3.1 Wheel scrolls tmux history.** Wheel over a terminal scrolls tmux's own scrollback, the+ text repaints correctly at every step, and there are no blank or duplicated rows.+- [ ] **3.2 Selection alignment, tall terminal.** In a tall terminal (fractional character height),+ select near the BOTTOM: the highlighted cells are the ones under the pointer — no vertical+ drift accumulating down the node.+- [ ] **3.3 Rectangular selection.** Alt/Option-drag a column block: the selected rectangle matches+ the drag, and the copied text is the column block.+- [ ] **3.4 Copy.** A selection made in shared mode copies the right text (OSC 52 path unchanged).+- [ ] **3.5 IME.** Turkish dead keys and (if available) a CJK IME: the composition popup appears+ over the right cell, composed text lands correctly, and the composition view is not hidden by+ the shared-mode CSS.+- [ ] **3.6 Accessibility.** With screen-reader mode / the a11y tree open, the terminal's text is+ still exposed (the `.xterm-rows` are `visibility: hidden` in shared mode — confirm the a11y+ layer is not).+- [ ] **3.7 Pan/zoom under load.** With ~12 terminals streaming, pan and zoom the canvas: text+ tracks the nodes with no lag, tearing or drift, and the frame rate stays comfortable.+- [ ] **3.8 Overlap occlusion.** Drag two terminals until they overlap: the one on top hides the+ one below — its text does not bleed through, and the lower one's text does not paint over+ the upper node's chrome.+- [ ] **3.9 Selecting the LOWER of two overlapping terminals.** Click the partially-covered one:+ React Flow elevates it, and its TEXT comes up with it — it must not stay occluded by the+ other node's plate.+- [ ] **3.10 Group-parented terminal.** A terminal inside a group frame: its text sits exactly in+ its body (offset chain resolves through the parent), and its paint order relative to+ ungrouped terminals is sane (known limitation L7).+- [ ] **3.11 Letterboxed / oddly-sized node.** Resize a node so the fit leaves slack: the text+ stays inside the body, aligned with the mouse.+- [ ] **3.12 Programmatic camera.** ⌘K jump to a node, a notification click, and a fitView: the+ text lands with the node — no frame where glyphs sit at the old position or at the origin.+- [ ] **3.13 Stacking.** The canvas is ABOVE the dot grid and BELOW node chrome; the bottom-left+ Controls, the minimap and the drawers are all still clickable over a terminal's body.++## 4. Lifecycle++- [ ] **4.1 Enable with terminals already mounted.** (The T6 decision.) With Shared off and a+ canvas full of live terminals, switch to Shared: **every visible terminal joins immediately**+ — no project switch, no refresh, no blank bodies.+- [ ] **4.2 Disable with terminals mounted.** Switch back to Auto/GPU per terminal: every terminal+ returns to normal TEXT immediately (never blank), the shared context is released (DevTools:+ zero glyph contexts), and per-terminal contexts are granted again for the visible ones.+- [ ] **4.3 Off → Shared → Off → Shared** twice in a row: no accumulation of contexts, no warning+ spam, terminals readable in every state.+- [ ] **4.4 Font size change, no remount.** With shared on, change the font size: the text rescales,+ the grid stays aligned with the mouse (click at a known cell and check the cursor lands+ there), and the selection still matches the drag.+- [ ] **4.5 Font family change.** Same, with a different family; glyphs are re-rasterized (no+ leftovers from the previous font).+- [ ] **4.6 Ten font changes in a row.** Repeat 4.4/4.5 ~10 times: the shared renderer never+ permanently fails, and DevTools still shows exactly one WebGL context.+- [ ] **4.7 dims.css.cell on a fresh mount.** Open a NEW terminal node while shared is on: it joins+ the shared canvas at the right cell size (no warn in the console about "cell size+ unavailable", no half-size text).+- [ ] **4.8 Park and adopt.** Switch to another project and back within 5 minutes: the adopted+ terminal shows its text at the correct size and position, and the swap-heal did not leave a+ stray black canvas over it.+- [ ] **4.9 Park beyond 5 minutes.** Same, after the park window expires (cold re-attach): the+ terminal re-registers and paints.+- [ ] **4.10 Adopt after a font change.** Change the font while a project is parked, then switch+ back: check the adopted terminal's cell size against the mouse (known limitation L6 — a+ stale cell would show as text/mouse drift healed only by refreshing the node).+- [ ] **4.11 Collapse / expand.** Collapse a terminal: its glyphs disappear with the body (nothing+ is left painted on the canvas). Expand: the text comes back.+- [ ] **4.12 ⌘M markdown view.** Toggle it on: the glyphs are gone behind the panel. Off: back.+- [ ] **4.13 Respawn (Refresh terminal).** The node's ↻ action: fresh attach, text paints, no+ duplicate grid, no transparent-but-empty body.+- [ ] **4.14 Alt-screen transitions.** Enter and leave a fullscreen TUI (`htop`, an agent CLI) a+ few times: no flicker of a doubled screen, no leftover rows from the previous screen.+- [ ] **4.15 dpr change.** Drag the window between the retina display and an external 1x monitor+ (both directions): geometry stays correct (the drawing buffer follows), text may soften+ slightly (atlas is not rebuilt — Phase 2), and nothing re-registers or fails.+- [ ] **4.16 Kanban board.** Open the board over a shared-mode project: the board is fully opaque+ (no glyphs showing through), and the idle rAF cost is not noticeable (check CPU/GPU while+ the board is up with terminals idle).+- [ ] **4.17 Card modal.** Open a session's card modal while the canvas terminal is on the shared+ canvas: the modal's own terminal renders through xterm's DOM renderer (known limitation L8)+ and both views stay live and correctly sized.++## 5. Failure paths++- [ ] **5.1 Forced context loss.** Force `WEBGL_lose_context` on the shared canvas: exactly ONE+ warning in the console, the rAF loop stops, EVERY terminal returns to readable DOM text, and+ nothing is blank. The mode stays failed for the rest of the session (by design — no retry+ loop), and the Settings row still reads Shared.+- [ ] **5.2 Recover from a failure.** After 5.1, switch to Auto and back: terminals render normally+ on Auto. (A relaunch is what re-arms shared mode.)+- [ ] **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, no+ blank terminals.+- [ ] **5.4 Unrecognised internals.** If any terminal warns `stays on the DOM renderer: xterm+ internals not recognised`, note it: that node keeps working (DOM), but it means the addon's+ assumptions broke on this xterm version.+- [ ] **5.5 No console noise.** Over a full session in shared mode, the console shows no repeated+ glyphgrid warnings (each warn is once-per-node-per-reason by design).++## 6. Regressions (the modes everyone else is on)++- [ ] **6.1 Auto.** Everything in §2/§3 that applies, on Auto: unchanged from `main`.+- [ ] **6.2 GPU per terminal.** Contexts are granted/reclaimed on pan and zoom exactly as before+ (zoom out past the suspend threshold → no contexts; zoom in → re-granted).+- [ ] **6.3 Off.** Every terminal on the DOM renderer, no WebGL contexts at all.+- [ ] **6.4 Settings round-trip.** Pick each of the four options, quit and relaunch: the choice is+ still there (`settings.json` holds `"terminalGpuRendering": "shared"` etc.).+- [ ] **6.5 Hand-edited garbage.** Set `"terminalGpuRendering": "warp-speed"` in `settings.json`+ and relaunch: the app comes up on **Auto**, not on an experimental mode.+- [ ] **6.6 Server Edition sanity.** (Optional, Linux/browser.) The Terminal rendering row exists+ and Auto/On/Off behave as before; Shared is expected to work but is not part of this gate.++---++## Known limitations (accepted for Phase 1b — verify they are what you see, not that they are absent)++- **L1 — The cursor does not blink.** The shared renderer paints a static block cursor regardless+ of the "Cursor blink" setting. Decide on device whether this ships as-is or the setting should be+ gated in shared mode.+- **L2 — A blurred terminal paints no cursor.** xterm's DOM renderer draws a hollow outline for an+ unfocused terminal; the engine has no outline flag, so the cursor simply disappears on blur.+- **L3 — Selection does not dim on blur.** The theme lanes carry no *inactive* selection color, so+ an unfocused terminal's selection keeps the active color.+- **L4 — Square plate corners.** The grid's plate is a rectangle; the node has `border-radius: 10px`+ and cannot clip the canvas (it is not a DOM child), so the body's corners read square in shared+ mode. Phase 2: rounded/stencilled plate.+- **L5 — Fit slack at the right/bottom edge.** The plate covers the grid plus the host padding; a+ fit can leave up to one cell of slack, which shows the canvas instead of the terminal background.+ Same Phase-2 fix as L4 (plate sized to the body rect rather than the grid rect).+- **L6 — Adopting a parked terminal after a font change may keep a stale cell size.** The grid is+ registered from the cell xterm reports at adopt time; a font change applied in the same commit+ can land after it. Refreshing the node re-registers at the correct size.+- **L7 — Group-parented z is an approximation.** The paint order is the node array order with+ selected nodes elevated (mirroring React Flow's `elevateNodesOnSelect`); React Flow additionally+ gives a grouped node `parentZ + 1`, which the order signature does not model. Overlaps that mix+ grouped and ungrouped terminals can therefore order differently from the DOM.+- **L8 — The kanban card modal stays on xterm's DOM renderer, by design in v1.** The modal is a+ second, co-attached view of the same tmux session living outside the canvas' coordinate space;+ it has no grid, no camera and no z in the shared canvas. Board parity here is a Phase-2 question.+- **L9 — A failure is permanent for the session.** A GL error or a lost context disables the shared+ renderer until the app is relaunched; there is no restore path in Phase 1b (deliberate — a retry+ loop on a bad driver is how you turn one failure into a flicker).+- **L10 — The atlas is not rebuilt on a dpr change.** Moving the window to a display with a+ different dpr leaves the glyphs rasterized for the old one (slightly soft or over-sampled).+ Geometry is unaffected — the drawing buffer follows the dpr on every resize.+- **L11 — Grids keep drawing while the kanban board covers the canvas.** The board overlay is+ opaque, so nothing is visible; it is wasted work, measured by item 4.16 and closed in Phase 2 if+ it shows up.++---++## Result++- Date / machine / OS / display setup:+- Blocking findings:+- Non-blocking findings (with the item number):+- Verdict: ship experimental / holddiff --git a/src/core/settings-store.test.ts b/src/core/settings-store.test.tsindex b6e442e0e..4504c121c 100644--- a/src/core/settings-store.test.ts+++ b/src/core/settings-store.test.ts@@ -95,8 +95,17 @@ describe('SettingsStore nested-default merge', () => {expect(load('auto').get().terminalGpuRendering).toBe('auto')})+ it("round-trips the experimental 'shared' mode", () => {+ // The shared-canvas renderer is a real stored choice, not garbage: normalizing it away would+ // silently put the user back on the per-terminal renderer at every launch.+ expect(load('shared').get().terminalGpuRendering).toBe('shared')+ })+it("normalizes garbage to 'auto'", () => {expect(load('warp-speed').get().terminalGpuRendering).toBe('auto')+ expect(load(42).get().terminalGpuRendering).toBe('auto')+ expect(load(null).get().terminalGpuRendering).toBe('auto')+ expect(load({ mode: 'shared' }).get().terminalGpuRendering).toBe('auto')})})})diff --git a/src/core/settings-store.ts b/src/core/settings-store.tsindex a0f8e1557..6969e802f 100644--- a/src/core/settings-store.ts+++ b/src/core/settings-store.ts@@ -19,10 +19,15 @@ function mergeSettings(saved: Partial<Settings> | null | undefined): Settings {// file — so a stored `true` is indistinguishable from "never touched" and maps to the new// 'auto' (platform-aware) default, while a stored `false` was always an explicit escape-hatch// choice and stays 'off'. See the field's doc in shared/types.ts.+ //+ // Every value that is not one of the four known modes ('auto' | 'on' | 'off' | 'shared')+ // normalizes to the DEFAULT: settings.json is hand-editable, and an unrecognised mode must not+ // be handed to the renderer's resolver to interpret.const gpu = (saved as { terminalGpuRendering?: unknown } | null | undefined)?.terminalGpuRenderingif (gpu === false) merged.terminalGpuRendering = 'off'- else if (gpu !== 'on' && gpu !== 'off' && gpu !== 'auto') merged.terminalGpuRendering = 'auto'+ else if (gpu !== 'on' && gpu !== 'off' && gpu !== 'auto' && gpu !== 'shared')+ merged.terminalGpuRendering = 'auto'return merged}diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex 6562c30f7..ad485ac83 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -7,18 +7,25 @@ import { localSession } from './session/localSession'import { useSettings } from './state/settings'import { useViewMode } from './state/viewMode'import { setWebglEnabled } from './terminal/webgl-budget'-import { resolveGpuRendering } from '../shared/webgl'+import { applyRendererMode } from './terminal/renderer-mode'+import { useSharedGlyph } from './canvas/SharedGlyphLayer'+import { resolveTerminalRenderer } from '../shared/webgl'import { isMacPlatform } from '../shared/platform-utils'export default function App() {- // Apply the GPU-terminal-rendering setting to the WebGL budget coordinator, live. 'auto'- // resolves per platform (macOS → DOM renderer: the compositor-level black/flicker failures- // have only ever been observed there, and a public default must be the field-proven-clean- // configuration; WebGL on a Mac is a deliberate 'on'). Off reclaims every context.+ // Apply the terminal-rendering setting to the two GPU coordinators, live. 'auto' resolves per+ // platform (macOS → DOM renderer: the compositor-level black/flicker failures have only ever+ // been observed there, and a public default must be the field-proven-clean configuration; WebGL+ // on a Mac is a deliberate 'on'). 'off' reclaims every context; the experimental 'shared' takes+ // the per-terminal budget down entirely and brings up the one canvas-wide glyph context+ // instead. `applyRendererMode` owns the ordering contract between the two (and its test).// Subscribed at the root so it holds whatever view is showing.const gpu = useSettings((s) => s.settings.terminalGpuRendering)useEffect(() => {- setWebglEnabled(resolveGpuRendering(gpu, isMacPlatform()))+ applyRendererMode(resolveTerminalRenderer(gpu, isMacPlatform()), {+ setWebglEnabled,+ setSharedEnabled: (on) => useSharedGlyph.getState().setEnabled(on)+ })}, [gpu])// Keep the view-mode store's default in sync with the Settings choice, so projects the userdiff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.tsindex 6083c59f3..f4ae95a88 100644--- a/src/renderer/canvas/SharedGlyphLayer.test.ts+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts@@ -143,11 +143,40 @@ describe('useSharedGlyph store', () => {// setEnabled(false) drops the context; every registered grid is now holding an inert handle// and would stay blank until it remounted without this signal.useSharedGlyph.getState().setEnabled(true)- expect(useSharedGlyph.getState().generation).toBe(0)useSharedGlyph.getState().setEnabled(false)- expect(useSharedGlyph.getState().generation).toBe(1)+ expect(useSharedGlyph.getState().generation).toBe(2)// Change-gated: a repeated disable disposes nothing, so it announces nothing.useSharedGlyph.getState().setEnabled(false)+ expect(useSharedGlyph.getState().generation).toBe(2)+ })++ it('ENABLING the mode bumps the generation too — already-mounted terminals must join', () => {+ // The user flips the setting to Shared with a canvas full of live terminals. Each of them+ // subscribes to `generation` and re-evaluates its participation on a bump; without one here+ // they would keep painting through xterm's own renderer until they remounted (a project+ // switch), and the setting would look like it did nothing. The bump is the ONE signal in this+ // seam, so enabling rides it exactly like disposal does.+ expect(useSharedGlyph.getState().generation).toBe(0)+ useSharedGlyph.getState().setEnabled(true)+ expect(useSharedGlyph.getState()).toMatchObject({ enabled: true, generation: 1 })+ })++ it('an enable bump carries the NEW enabled flag in the SAME notification', () => {+ // A subscriber's first move is to ask `sharedGlyphActive()`. If `enabled` were written in a+ // separate set() from the generation, one of the two notifications would carry a state that+ // disagrees with the other and a node would decide on the stale half.+ const seen: { enabled: boolean; generation: number }[] = []+ const unsub = useSharedGlyph.subscribe((s) =>+ seen.push({ enabled: s.enabled, generation: s.generation })+ )+ useSharedGlyph.getState().setEnabled(true)+ unsub()+ expect(seen).toEqual([{ enabled: true, generation: 1 }])+ })++ it('a repeated enable is change-gated — no bump, no re-registration storm', () => {+ useSharedGlyph.getState().setEnabled(true)+ useSharedGlyph.getState().setEnabled(true)expect(useSharedGlyph.getState().generation).toBe(1)})diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsxindex a1c84b398..17750c171 100644--- a/src/renderer/canvas/SharedGlyphLayer.tsx+++ b/src/renderer/canvas/SharedGlyphLayer.tsx@@ -58,13 +58,14 @@ const MAX_CELL_PX = 256// ---------------------------------------------------------------------------------------------interface SharedGlyphState {- /** Resolved renderer mode is 'shared'. Set by App.tsx (T6); false for every user today, which- * is what keeps this whole module inert. */+ /** Resolved renderer mode is 'shared'. Written only by `applyRendererMode` (App.tsx), and false+ * unless the user opted into the experimental mode — which is what keeps this whole module+ * inert for everyone else. */enabled: boolean- /** Bumped whenever every registered grid must let go and re-evaluate: the context was rebuilt- * (font change), the mode was turned off, or the session failed. TerminalNode subscribes to- * exactly this number — the context it then asks for answers what to do next (a new engine, or- * null = back to the DOM renderer). */+ /** Bumped whenever every mounted terminal must re-evaluate its participation: the mode was+ * turned ON, the context was rebuilt (font change), the mode was turned off, or the session+ * failed. TerminalNode subscribes to exactly this number — the context it then asks for+ * answers what to do next (a new engine, or null = back to the DOM renderer). */generation: number/** Session-level "the shared renderer is off for good" — set by the rAF catch or a lost* context. Deliberately NOT auto-cleared: a GPU that just threw at us gets one chance per app@@ -81,12 +82,23 @@ export const useSharedGlyph = create<SharedGlyphState>((set, get) => ({failed: false,setEnabled(on) {if (get().enabled === on) return+ if (on) {+ // Turning the mode ON creates nothing — the first terminal that asks builds the context,+ // lazily — but it must still be ANNOUNCED, in the same single set() so the notification+ // carries the new `enabled` alongside the bump. Every mounted terminal re-evaluates its+ // participation on a generation change; without the bump here, flipping the setting with a+ // canvas full of live terminals would do nothing visible until each of them remounted (a+ // project switch), and the setting would look broken. Safe for a node that has never+ // registered a grid: its teardown is a no-op and its re-setup is the same gated+ // `setupGlyph()` a fresh mount runs.+ set({ enabled: true, generation: get().generation + 1 })+ return+ }set({ enabled: on })- if (on) return// Turning the mode OFF hands the GPU context back. The whole point of the shared renderer is// that contexts are scarce (see terminal/webgl-budget.ts), so leaving one — plus a 16 MB// atlas — parked for a mode the user just left would be the exact cost this feature exists to- // remove. Turning it ON creates nothing: the first terminal that asks does that, lazily.+ // remove.disposeContext()// ...and the disposal MUST be announced. Every registered grid is now holding an inert handle;// without the bump a terminal that subscribes to `generation` alone would keep writing rowsdiff --git a/src/renderer/components/settings/sections/TerminalSection.tsx b/src/renderer/components/settings/sections/TerminalSection.tsxindex 73d267e12..e085cab59 100644--- a/src/renderer/components/settings/sections/TerminalSection.tsx+++ b/src/renderer/components/settings/sections/TerminalSection.tsx@@ -4,17 +4,29 @@ import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'import { Input } from '@renderer/ui/Input'import { Switch } from '@renderer/ui/Switch'+import { Select } from '@renderer/ui/Select'import { NumberField } from '@renderer/ui/NumberField'-import { resolveGpuRendering } from '@shared/webgl'import { isMacPlatform } from '@shared/platform-utils'+import type { Settings } from '@shared/types'const ROWS = {fontSize: { title: 'Font size', keywords: ['font', 'size', 'text'] },fontFamily: { title: 'Font family', keywords: ['font', 'family', 'typeface', 'monospace'] },cursorBlink: { title: 'Cursor blink', keywords: ['cursor', 'blink'] },gpu: {- title: 'GPU terminal rendering',- keywords: ['gpu', 'webgl', 'renderer', 'flicker', 'performance', 'graphics', 'acceleration']+ title: 'Terminal rendering',+ keywords: [+ 'gpu',+ 'webgl',+ 'renderer',+ 'rendering',+ 'flicker',+ 'performance',+ 'graphics',+ 'acceleration',+ 'shared',+ 'experimental'+ ]}}const ENTRIES = Object.values(ROWS)@@ -63,18 +75,30 @@ export function TerminalSection({ isActive }: { isActive: boolean }): React.JSX.</SearchableRow><SearchableRow {...ROWS.gpu}><FieldRow- label="GPU terminal rendering"+ label="Terminal rendering"description={- isMacPlatform()- ? 'Off by default on macOS (WebGL terminals can flicker or composite black there). Turning it on is an explicit opt-in.'- : 'Turn off if the window flickers. Terminals then use the DOM renderer (no WebGL).'+ (isMacPlatform()+ ? 'Auto uses the DOM renderer on macOS (WebGL terminals can flicker or composite black there), so GPU per terminal is an explicit opt-in. '+ : 'Auto uses one GPU context per terminal; switch to Off if the window flickers. ') ++ 'Shared GPU is experimental — every terminal paints into a single canvas-wide context, ' ++ 'which lifts the per-terminal context limit but may render incorrectly; it falls back ' ++ 'to DOM on failure.'}control={- <Switch- checked={resolveGpuRendering(settings.terminalGpuRendering, isMacPlatform())}- onChange={(v) => update({ terminalGpuRendering: v ? 'on' : 'off' })}- ariaLabel="GPU terminal rendering"- />+ <Select+ aria-label="Terminal rendering"+ value={settings.terminalGpuRendering}+ onChange={(e) =>+ update({+ terminalGpuRendering: e.target.value as Settings['terminalGpuRendering']+ })+ }+ >+ <option value="auto">Auto (default)</option>+ <option value="on">GPU per terminal</option>+ <option value="shared">Shared GPU (experimental)</option>+ <option value="off">Off (DOM renderer)</option>+ </Select>}/></SearchableRow>diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 0ae4f73c6..b20adc396 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -1796,43 +1796,67 @@ export function TerminalNode({// there is no per-terminal context to budget, nothing to acquire on approach and no DOM-strand// heal to run — the whole webgl client is skipped rather than registered and left idle.//- // The decision is made ONCE per mount, on the mode and the context — NOT on whether the grid- // registration then succeeded. A node that is collapsed right now registers nothing yet but- // will on expand, and a terminal cannot be allowed to end up holding both renderers: the- // glyph addon's `setRenderer` silently disposes the webgl one, leaving the budget coordinator- // accounting for a context nobody paints with and `releaseWebgl` sweeping canvases out from- // under a live attachment. Failing the registration (unrecognised internals) leaves this- // terminal on xterm's own DOM renderer — correct, just unbudgeted, and warned once.+ // The decision is made on the MODE and the context — NOT on whether the grid registration then+ // succeeded. A node that is collapsed right now registers nothing yet but will on expand, and+ // a terminal cannot be allowed to end up holding both renderers: the glyph addon's+ // `setRenderer` silently disposes the webgl one, leaving the budget coordinator accounting for+ // a context nobody paints with and `releaseWebgl` sweeping canvases out from under a live+ // attachment. Failing the registration (unrecognised internals) leaves this terminal on+ // xterm's own DOM renderer — correct, just unbudgeted, and warned once. The mode itself is+ // re-read on every generation bump (the subscription below), never only at mount.const glyphMode = sharedGlyphActive() && getSharedGlyphContext() !== null- if (!glyphMode) {- webglHandle = registerWebglClient(id, { acquire: acquireWebgl, release: releaseWebgl })- } else {- setupGlyph()- // Only the ACTIVE path subscribes, and only once: a session that never turned the shared- // renderer on holds no store subscription at all. `generation` is bumped for every context- // disposal — font change, mode off, session failure.- //- // This handler TEARS DOWN ONLY. The re-setup is deferred to the participation effect via- // `glyphEpoch`, and the reason is the font-change case: this notification is SYNCHRONOUS- // inside `useSettings.setState` (settings change → the layer's settings subscription disposes- // the context and bumps the generation → we run), which is BEFORE React has committed the- // render that applies `term.options.fontSize` to xterm. Re-registering here would read a- // stale `dimensions.css.cell` and pin the grid to the OLD cell size while the rebuilt atlas- // rasterizes at the new one — and a grid's cell size cannot be changed afterwards, so the- // drift would be permanent until the node remounted. Tearing down early is always safe: the- // context these handles belong to is already gone.- let lastGen = useSharedGlyph.getState().generation- glyphGenUnsub = useSharedGlyph.subscribe((s) => {- if (disposed || s.generation === lastGen) return- lastGen = s.generation- if (!teardownGlyph()) {- escalateRespawn('glyphgrid could not restore the DOM renderer')- return- }- setGlyphEpoch((n) => n + 1)- })- }+ if (glyphMode) setupGlyph()+ else webglHandle = registerWebglClient(id, { acquire: acquireWebgl, release: releaseWebgl })++ // The IntersectionObserver's last verdict, read by the subscription below when it hands a+ // fresh budget client this terminal's visibility. Declared here (not with the observer) so it+ // exists before anything can close over it.let wasVisible = false++ // ...but the mode can also change UNDER a mounted terminal — the user flips the Settings row+ // with a canvas full of live sessions — so the subscription below is UNCONDITIONAL, not part+ // of the glyph branch. `generation` is bumped for every event that invalidates the decision+ // above: the mode turned on, a context disposal (font change, mode off), a session failure.+ // A node that never held a grid pays one store subscription and a comparison per bump, which+ // for a default-mode user is zero bumps.+ //+ // This handler TEARS DOWN ONLY. The re-setup is deferred to the participation effect via+ // `glyphEpoch`, and the reason is the font-change case: this notification is SYNCHRONOUS+ // inside `useSettings.setState` (settings change → the layer's settings subscription disposes+ // the context and bumps the generation → we run), which is BEFORE React has committed the+ // render that applies `term.options.fontSize` to xterm. Re-registering here would read a+ // stale `dimensions.css.cell` and pin the grid to the OLD cell size while the rebuilt atlas+ // rasterizes at the new one — and a grid's cell size cannot be changed afterwards, so the+ // drift would be permanent until the node remounted. Tearing down early is always safe: the+ // context these handles belong to is already gone.+ let lastGen = useSharedGlyph.getState().generation+ glyphGenUnsub = useSharedGlyph.subscribe((s) => {+ if (disposed || s.generation === lastGen) return+ lastGen = s.generation+ if (!teardownGlyph()) {+ escalateRespawn('glyphgrid could not restore the DOM renderer')+ return+ }+ // The budget client follows the mode, so this terminal never holds both renderers (the+ // hazard spelled out above). Order matters in both directions and is already right: xterm+ // is back on its own renderer by the line above before a budget client may grant it a+ // context, and the grid is only (re-)registered by the participation effect the epoch bump+ // below schedules — after this. `setVisible` re-states what the IntersectionObserver last+ // reported, because it will not fire again until visibility actually changes and a fresh+ // client starts out believing it is hidden.+ // The SAME test the mount above makes — mode AND a context that exists — so a machine+ // without WebGL2 (where `getSharedGlyphContext()` is null however the setting reads) keeps+ // its budget client instead of ending up with neither renderer coordinated.+ const shared = sharedGlyphActive() && getSharedGlyphContext() !== null+ if (shared && webglHandle) {+ webglHandle.dispose()+ webglHandle = null+ } else if (!shared && !webglHandle) {+ webglHandle = registerWebglClient(id, { acquire: acquireWebgl, release: releaseWebgl })+ webglHandle.setVisible(wasVisible)+ }+ setGlyphEpoch((n) => n + 1)+ })const visibilityObserver = new IntersectionObserver((entries) => {// disconnect() does not flush already-QUEUED notifications (Blink delivers them after),diff --git a/src/renderer/terminal/renderer-mode.test.ts b/src/renderer/terminal/renderer-mode.test.tsnew file mode 100644index 000000000..5d10a8bd9--- /dev/null+++ b/src/renderer/terminal/renderer-mode.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest'+import { applyRendererMode } from './renderer-mode'++function record(): { calls: string[]; sinks: Parameters<typeof applyRendererMode>[1] } {+ const calls: string[] = []+ return {+ calls,+ sinks: {+ setWebglEnabled: (on) => calls.push(`webgl:${on}`),+ setSharedEnabled: (on) => calls.push(`shared:${on}`)+ }+ }+}++describe('applyRendererMode', () => {+ it("'webgl' runs the per-terminal budget and nothing else", () => {+ const { calls, sinks } = record()+ applyRendererMode('webgl', sinks)+ expect(calls).toEqual(['shared:false', 'webgl:true'])+ })++ it("'dom' turns both renderers off", () => {+ const { calls, sinks } = record()+ applyRendererMode('dom', sinks)+ expect(calls).toEqual(['shared:false', 'webgl:false'])+ })++ it("'shared' takes the per-terminal budget down BEFORE the shared canvas comes up", () => {+ // Order is the contract, not an accident. Enabling the shared canvas is what makes every+ // mounted terminal hand its render service to the glyph addon; a terminal that still held a+ // budgeted WebGL context at that moment would end up with two renderers on one xterm (the+ // addon's setRenderer silently disposes the other one, leaving the coordinator accounting for+ // a context nobody paints with). Reclaiming first means every xterm is on its DOM renderer+ // when the swap happens.+ const { calls, sinks } = record()+ applyRendererMode('shared', sinks)+ expect(calls).toEqual(['webgl:false', 'shared:true'])+ })++ it('LEAVING shared tears the shared canvas down BEFORE the budget may grant again', () => {+ // The mirror image: the shared store's disable synchronously notifies every registered grid,+ // which detaches the addon and puts xterm back on its DOM renderer. Only then may the budget+ // start handing out per-terminal contexts.+ const { calls, sinks } = record()+ applyRendererMode('webgl', sinks)+ expect(calls.indexOf('shared:false')).toBeLessThan(calls.indexOf('webgl:true'))+ })+})diff --git a/src/renderer/terminal/renderer-mode.ts b/src/renderer/terminal/renderer-mode.tsnew file mode 100644index 000000000..a9d8fdf5f--- /dev/null+++ b/src/renderer/terminal/renderer-mode.ts@@ -0,0 +1,43 @@+import type { TerminalRenderer } from '@shared/webgl'++/**+ * Applying the resolved terminal renderer to the two coordinators that own GPU state: the+ * per-terminal WebGL budget (`terminal/webgl-budget.ts`) and the shared glyph canvas+ * (`canvas/SharedGlyphLayer.tsx`).+ *+ * It is its own function, with the sinks injected, for one reason: the ORDER of the two calls is+ * a correctness contract and nothing else in the codebase can express it. App.tsx is a component,+ * which the (node-environment) suite cannot render; here the contract is a three-line unit test.+ */+export interface RendererModeSinks {+ /** `terminal/webgl-budget.ts` → `setWebglEnabled`. */+ setWebglEnabled(on: boolean): void+ /** `canvas/SharedGlyphLayer.tsx` → `useSharedGlyph.getState().setEnabled`. */+ setSharedEnabled(on: boolean): void+}++/**+ * Put exactly one renderer in charge.+ *+ * **Never both.** Enabling the shared canvas makes every mounted terminal hand its render service+ * to the glyph addon, and the addon's `setRenderer` silently disposes whatever renderer xterm had+ * — including a budgeted WebGL one, which would leave the coordinator accounting for a context+ * nobody paints with while its release path sweeps a canvas out from under a live attachment.+ * So the outgoing renderer is always taken down BEFORE the incoming one comes up:+ *+ * - into 'shared': reclaim every per-terminal context first (each xterm falls back to its DOM+ * renderer synchronously), then enable the shared canvas;+ * - out of 'shared': disable the shared canvas first — that notification synchronously detaches+ * every grid and restores xterm's own renderer — and only then let the budget grant again.+ *+ * Both sinks are change-gated at the source, so the mode that did not change costs one comparison.+ */+export function applyRendererMode(mode: TerminalRenderer, sinks: RendererModeSinks): void {+ if (mode === 'shared') {+ sinks.setWebglEnabled(false)+ sinks.setSharedEnabled(true)+ return+ }+ sinks.setSharedEnabled(false)+ sinks.setWebglEnabled(mode === 'webgl')+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 57949ef17..fedddd845 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -714,8 +714,13 @@ export interface Settings {* configuration on those machines is the DOM renderer, so macOS gets it by default and WebGL* stays a deliberate opt-in ('on'). Legacy boolean values are migrated on load: `false` (an* explicit escape-hatch choice) → 'off'; `true` (indistinguishable from the old merged-in- * default) → 'auto'. */- terminalGpuRendering: 'auto' | 'on' | 'off'+ * default) → 'auto'.+ *+ * 'shared' is the EXPERIMENTAL glyphgrid renderer: instead of one WebGL context per terminal+ * (which is what the ~16-context cap and the whole budget coordinator exist to ration), every+ * terminal on the canvas paints into ONE canvas-wide context. Opt-in only, it may render+ * incorrectly, and any failure drops the session back to xterm's DOM renderer. */+ terminalGpuRendering: 'auto' | 'on' | 'off' | 'shared'tmuxScrollback: number/** AI commit message agent: a local coding-agent CLI run read-only. */commitAgent: 'claude' | 'codex' | 'custom'diff --git a/src/shared/webgl.test.ts b/src/shared/webgl.test.tsnew file mode 100644index 000000000..4e98eeccc--- /dev/null+++ b/src/shared/webgl.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest'+import { resolveTerminalRenderer } from './webgl'++// The renderer mode is the one thing every terminal on the canvas reads, and its DEFAULT ('auto')+// resolution must not move: every user who never touched the setting is on it.+describe('resolveTerminalRenderer', () => {+ it("'auto' is the DOM renderer on macOS and per-terminal WebGL everywhere else", () => {+ // The pre-existing platform rule, unchanged — see the doc comment for the macOS field reports.+ expect(resolveTerminalRenderer('auto', true)).toBe('dom')+ expect(resolveTerminalRenderer('auto', false)).toBe('webgl')+ })++ it("'on' is per-terminal WebGL on every platform (a deliberate opt-in on macOS)", () => {+ expect(resolveTerminalRenderer('on', true)).toBe('webgl')+ expect(resolveTerminalRenderer('on', false)).toBe('webgl')+ })++ it("'off' is the DOM renderer on every platform", () => {+ expect(resolveTerminalRenderer('off', true)).toBe('dom')+ expect(resolveTerminalRenderer('off', false)).toBe('dom')+ })++ it("'shared' is the shared canvas on every platform — it is the escape from the context cap", () => {+ // Platform-independent by design: the whole point of one context for the whole canvas is that+ // the per-terminal context pressure (the macOS failure mode) does not exist.+ expect(resolveTerminalRenderer('shared', true)).toBe('shared')+ expect(resolveTerminalRenderer('shared', false)).toBe('shared')+ })++ it('resolves legacy booleans and garbage the way the migration would', () => {+ // Settings arrive from a hand-editable JSON file and the store migrates them — but the+ // resolver is also called with whatever is in memory, so it must never answer 'shared' by+ // accident: an unknown value is the DEFAULT, i.e. 'auto'.+ expect(resolveTerminalRenderer(true, false)).toBe('webgl')+ expect(resolveTerminalRenderer(false, false)).toBe('dom')+ expect(resolveTerminalRenderer(undefined, true)).toBe('dom')+ expect(resolveTerminalRenderer(undefined, false)).toBe('webgl')+ expect(resolveTerminalRenderer('warp-speed' as 'auto', true)).toBe('dom')+ expect(resolveTerminalRenderer('warp-speed' as 'auto', false)).toBe('webgl')+ })+})diff --git a/src/shared/webgl.ts b/src/shared/webgl.tsindex efd8709f9..8bc356668 100644--- a/src/shared/webgl.ts+++ b/src/shared/webgl.ts@@ -34,19 +34,38 @@ export const WEBGL_BUDGET_DESKTOP = 24*/export const WEBGL_BUDGET_DESKTOP_MAC = 10+/** How a terminal actually paints: xterm's own DOM renderer, one budgeted WebGL context per+ * terminal (the coordinator described above), or the experimental glyphgrid — ONE context for+ * the whole canvas, into which every terminal paints. */+export type TerminalRenderer = 'dom' | 'webgl' | 'shared'+/**- * Resolve the `terminalGpuRendering` setting to an effective on/off. 'auto' (the default) is on- * everywhere EXCEPT macOS: the compositor-level failures above have only ever been observed- * there, the DOM renderer is the one field-proven-clean configuration on those machines, and a- * public default must be the proven one — WebGL on a Mac is a deliberate 'on'. Renderer-side- * only (platform detection is navigator-based). Legacy booleans still resolve sanely if one- * slips past the settings-store migration.+ * Resolve the `terminalGpuRendering` setting to the renderer the terminals should use. THE single+ * resolver: there is deliberately no second "is GPU rendering on?" boolean helper, because+ * 'shared' is a GPU mode whose PER-TERMINAL budget must be off, so a boolean answer is wrong for+ * one of its two callers no matter which way it goes. (The former `resolveGpuRendering` returned+ * `true` for every value it did not recognise on non-mac — which for 'shared' would have left the+ * budget handing out contexts to terminals that no longer paint their own pixels.)+ *+ * 'auto' (the default) is per-terminal WebGL everywhere EXCEPT macOS: the compositor-level+ * failures documented above have only ever been observed there, the DOM renderer is the one+ * field-proven-clean configuration on those machines, and a public default must be the proven+ * one — WebGL on a Mac is a deliberate 'on'. Renderer-side only (platform detection is+ * navigator-based).+ *+ * 'shared' is platform-independent: the per-terminal context pressure that makes 'auto' avoid+ * macOS is precisely what a single canvas-wide context does not create.+ *+ * Legacy booleans and anything unrecognised resolve exactly like 'auto' — the settings-store+ * migration normalizes the file, and a value that slipped past it must land on the DEFAULT, never+ * on an experimental mode.*/-export function resolveGpuRendering(- value: 'auto' | 'on' | 'off' | boolean | undefined,+export function resolveTerminalRenderer(+ value: 'auto' | 'on' | 'off' | 'shared' | boolean | undefined,isMac: boolean-): boolean {- if (value === 'on' || value === true) return true- if (value === 'off' || value === false) return false- return !isMac+): TerminalRenderer {+ if (value === 'shared') return 'shared'+ if (value === 'on' || value === true) return 'webgl'+ if (value === 'off' || value === false) return 'dom'+ return isMac ? 'dom' : 'webgl'}