Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(glyphgrid): watch matchMedia for the dpr change, like xterm does
enes66611beda685
diff --git a/src/renderer/canvas/SharedGlyphLayer.test.ts b/src/renderer/canvas/SharedGlyphLayer.test.tsindex 3e24b4ff7..38d1cf40a 100644--- a/src/renderer/canvas/SharedGlyphLayer.test.ts+++ b/src/renderer/canvas/SharedGlyphLayer.test.ts@@ -15,6 +15,7 @@ import {createBoardFrameGate,createContextLossPolicy,createCursorBlinkClock,+ createPixelRatioWatcher,cursorBlinkTarget,setCursorBlinkTarget,subscribeCursorBlinkRestart,@@ -50,6 +51,7 @@ import {type AtlasResetSource,type CursorBlinkClock,type CursorBlinkTarget,+ type PixelRatioWatchHost,type StackedNode,type StackOrderNode} from './SharedGlyphLayer'@@ -1060,9 +1062,10 @@ describe('syncAtlasPixelRatio', () => {it('a SECOND observer firing on the same display change does not bump again', () => {// The guard above only means something because of two facts this asserts together, and which a- // pre-disposed literal cannot show. (1) `pushViewport` runs from the ResizeObserver AND the- // window `resize` listener, and both close over the SAME context object — so the second call- // sees what the first one did. (2) `disposeContext()` flips `disposed` on that live object,+ // pre-disposed literal cannot show. (1) `pushViewport` runs from the ResizeObserver, the window+ // `resize` listener AND the resolution media query, and all three close over the SAME context+ // object — so the second call sees what the first one did. (2) `disposeContext()` flips+ // `disposed` on that live object,// which is what the guard reads; here that write is stood in for explicitly, since this// environment can build no real context to dispose.const same = ctx(2)@@ -1079,6 +1082,151 @@ describe('syncAtlasPixelRatio', () => {})})+/**+ * The dpr watcher — the TRIGGER the rebuild above depends on.+ *+ * `syncAtlasPixelRatio` is only ever reached from `pushViewport`, and the move it exists for (a+ * window dragged between a retina and a 1x display at the SAME point size) leaves the host's CSS+ * box identical, so the ResizeObserver stays silent and the whole fix rests on whatever else fires.+ * xterm does not trust `resize` for this — `CoreBrowserService` watches+ * `matchMedia('screen and (resolution: Xdppx)')` — and this suite is what makes the same watch+ * testable here, since the component itself has no DOM in this environment.+ *+ * The part most likely to be got wrong is the RE-ARM: the query string embeds the ratio it was+ * built at, so a query armed at 2dppx says nothing once the window is at 1dppx.+ */+describe('createPixelRatioWatcher', () => {+ /** A media query list with the two methods we use, and a way to deliver a change. */+ class FakeMql {+ readonly listeners = new Set<() => void>()+ constructor(readonly query: string) {}+ addEventListener(_type: 'change', fn: () => void): void {+ this.listeners.add(fn)+ }+ removeEventListener(_type: 'change', fn: () => void): void {+ this.listeners.delete(fn)+ }+ fire(): void {+ for (const fn of [...this.listeners]) fn()+ }+ }++ /** A fake display whose ratio can be moved, recording every query the watcher arms. */+ const fakeDisplay = (+ startDpr: number+ ): { host: PixelRatioWatchHost; built: FakeMql[]; move(to: number): void } => {+ let dpr = startDpr+ const built: FakeMql[] = []+ return {+ host: {+ dpr: () => dpr,+ match: (query) => {+ const mql = new FakeMql(query)+ built.push(mql)+ return mql+ }+ },+ built,+ // The browser order: `devicePixelRatio` is ALREADY the new value when the query that no+ // longer matches delivers its change.+ move(to: number): void {+ dpr = to+ }+ }+ }++ it('arms on the ratio it is constructed at, in xterm’s own query form', () => {+ const display = fakeDisplay(2)+ createPixelRatioWatcher(display.host, () => {})+ expect(display.built).toHaveLength(1)+ expect(display.built[0]?.query).toBe('screen and (resolution: 2dppx)')+ })++ it('calls back EXACTLY once for one display change', () => {+ const display = fakeDisplay(2)+ const onChange = vi.fn()+ createPixelRatioWatcher(display.host, onChange)+ display.move(1)+ display.built[0]?.fire()+ expect(onChange).toHaveBeenCalledTimes(1)+ })++ it('RE-ARMS at the new ratio — a second change still fires', () => {+ // The whole reason this is a watcher rather than one `addEventListener` call. The 2dppx query+ // is answered once and then never again; without the re-arm the move BACK is silent, and the+ // canvas keeps an atlas rasterized for the display it is no longer on.+ const display = fakeDisplay(2)+ const onChange = vi.fn()+ createPixelRatioWatcher(display.host, onChange)++ display.move(1)+ display.built[0]?.fire()+ expect(display.built).toHaveLength(2)+ expect(display.built[1]?.query).toBe('screen and (resolution: 1dppx)')+ // The spent query is released, so the move back cannot be answered twice.+ expect(display.built[0]?.listeners.size).toBe(0)++ display.move(2)+ display.built[1]?.fire()+ expect(onChange).toHaveBeenCalledTimes(2)+ expect(display.built[2]?.query).toBe('screen and (resolution: 2dppx)')+ })++ it('bumps the generation exactly once per change, through the real rebuild funnel', () => {+ // End to end for the thing the trigger exists to reach: the watcher's callback is+ // `pushViewport`, whose first act is `syncAtlasPixelRatio`. One display change, ONE+ // re-registration of every grid on the canvas — and the SECOND change gets its own.+ const display = fakeDisplay(2)+ let ctx = { dpr: 2, disposed: false }+ createPixelRatioWatcher(display.host, () => {+ if (syncAtlasPixelRatio(display.host.dpr(), ctx)) {+ // What `disposeContext()` + the re-run effect do: the closure meets a FRESH context built+ // at the ratio we are now on.+ ctx.disposed = true+ ctx = { dpr: display.host.dpr(), disposed: false }+ }+ })++ display.move(1)+ display.built[0]?.fire()+ expect(useSharedGlyph.getState().generation).toBe(1)++ display.move(2)+ display.built[1]?.fire()+ expect(useSharedGlyph.getState().generation).toBe(2)+ })++ it('stops: the listener is released and a later change reaches nobody', () => {+ const display = fakeDisplay(2)+ const onChange = vi.fn()+ const watcher = createPixelRatioWatcher(display.host, onChange)+ watcher.stop()+ expect(display.built[0]?.listeners.size).toBe(0)+ display.move(1)+ display.built[0]?.fire()+ expect(onChange).not.toHaveBeenCalled()+ })++ it('is inert where the environment has no matchMedia at all', () => {+ // The node test environment and any hardened shell. Nothing to watch is a correct outcome —+ // the `resize` listener is still there — and it must not cost a throw at mount.+ const watcher = createPixelRatioWatcher({ dpr: () => 2, match: () => null }, () => {+ throw new Error('unreachable')+ })+ expect(() => watcher.stop()).not.toThrow()+ })++ it('is inert on a query list that cannot be listened to', () => {+ // An ancient shim exposing only the deprecated `addListener` pair. We do not carry a fallback+ // for it (nothing else in the repo does), so it degrades to the `resize` trigger alone rather+ // than throwing on every mount.+ const watcher = createPixelRatioWatcher({ dpr: () => 2, match: () => ({}) }, () => {+ throw new Error('unreachable')+ })+ expect(() => watcher.stop()).not.toThrow()+ })+})+/*** The board gate. The kanban board is a fully opaque overlay over the whole canvas, so every frame* drawn under it is invisible work — and the idle park cannot help, because a canvas of STREAMINGdiff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsxindex 0e8f62895..3b7da4094 100644--- a/src/renderer/canvas/SharedGlyphLayer.tsx+++ b/src/renderer/canvas/SharedGlyphLayer.tsx@@ -994,16 +994,95 @@ export interface PixelRatioContext {* disposed.*/export function syncAtlasPixelRatio(current: number, ctx: PixelRatioContext): boolean {- // Re-entry guard. `pushViewport` runs from the ResizeObserver AND the window `resize` listener,- // and a display change fires both; `disposeContext()` flips this flag on the context the closure- // still holds, so the second call is a no-op instead of a second epoch bump — which would run- // teardown/setup twice on every terminal for one display change.+ // Re-entry guard. `pushViewport` runs from the ResizeObserver, the window `resize` listener AND+ // the resolution media query, and a display change can fire more than one of them;+ // `disposeContext()` flips this flag on the context the closure still holds, so the second call+ // is a no-op instead of a second epoch bump — which would run teardown/setup twice on every+ // terminal for one display change.if (ctx.disposed) return falseif (!pixelRatioChanged(ctx.dpr, current)) return falserebuildSharedContext()return true}+/** The query xterm's own `CoreBrowserService` watches for a device-pixel-ratio change, verbatim.+ * Exported so the test can assert the form rather than only the behaviour: the ratio is embedded+ * in the STRING, which is the whole reason the watcher below has to re-arm. */+export function pixelRatioQuery(dpr: number): string {+ return `screen and (resolution: ${dpr}dppx)`+}++/** The two methods of a `MediaQueryList` the watcher uses, both optional: an environment can expose+ * only the deprecated `addListener` pair, and that degrades to "not watched" rather than a throw. */+export interface PixelRatioMediaQuery {+ addEventListener?(type: 'change', fn: () => void): void+ removeEventListener?(type: 'change', fn: () => void): void+}++/** The browser surface the dpr watcher needs, injected — the component itself has no DOM under the+ * unit tests, and the re-arm is precisely what needs testing. */+export interface PixelRatioWatchHost {+ /** Read AFRESH at every arm: the query embeds the ratio, so it must be the ratio we are on now. */+ dpr(): number+ /** `window.matchMedia`, or null where the environment has none. */+ match(query: string): PixelRatioMediaQuery | null+}++/**+ * Watch for a device-pixel-ratio change and call back once per change.+ *+ * WHY THIS EXISTS ALONGSIDE `resize`. The move it answers — a window dragged between a retina and a+ * 1x display at the same point size — leaves the host's CSS box identical, so the ResizeObserver is+ * silent, and whether Blink dispatches `resize` for a scale-factor change with an unchanged CSS+ * viewport is not something to bet the atlas on. xterm does not bet on it: `CoreBrowserService`+ * watches exactly this media query. Both triggers run, funnelled through the same `pushViewport`,+ * and `syncAtlasPixelRatio`'s re-entry guard makes the double fire free.+ *+ * THE RE-ARM IS THE WHOLE JOB. `screen and (resolution: 2dppx)` answers the move OFF 2dppx and then+ * never again, so each change disarms the spent query and arms one at the ratio we have just landed+ * on — otherwise the move BACK is silent and the canvas keeps an atlas rasterized for a display it+ * is no longer on. Re-arming happens BEFORE the callback: `onChange` may dispose the context, and+ * the next display change must be watched for either way.+ *+ * No `addListener` fallback: nothing else in this repo carries one, and a query list we cannot+ * subscribe to leaves the `resize` trigger in place.+ */+export function createPixelRatioWatcher(+ host: PixelRatioWatchHost,+ onChange: () => void+): { stop(): void } {+ let mql: PixelRatioMediaQuery | null = null+ let stopped = false++ const disarm = (): void => {+ mql?.removeEventListener?.('change', handler)+ mql = null+ }++ const arm = (): void => {+ disarm()+ if (stopped) return+ const next = host.match(pixelRatioQuery(host.dpr()))+ if (!next || typeof next.addEventListener !== 'function') return+ next.addEventListener('change', handler)+ mql = next+ }++ function handler(): void {+ if (stopped) return+ arm()+ onChange()+ }++ arm()+ return {+ stop(): void {+ stopped = true+ disarm()+ }+ }+}+/** Fires when a context has just been BUILT. The component listens so it can mount the fresh* canvas: creation is now driven by the first terminal that offers a device cell, which can* happen after the layer's own effect has already run and found nothing. Deliberately NOT a@@ -1703,10 +1782,10 @@ export function SharedGlyphLayer(): JSX.Element {const pushViewport = (): void => {const dpr = currentDpr()// A display change (the window dragged onto a monitor with a different pixel ratio) arrives- // HERE — it fires `resize` with the CSS box unchanged — and it is the one viewport input the- // engine cannot absorb, because the ATLAS was rasterized for the old ratio. So it is checked- // before the push: on a rebuild the context this closure holds is already gone, and the fresh- // one gets its viewport from the re-run effect's own `pushViewport()`.+ // HERE, from whichever of the triggers below sees it first, and it is the one viewport input+ // the engine cannot absorb, because the ATLAS was rasterized for the old ratio. So it is+ // checked before the push: on a rebuild the context this closure holds is already gone, and+ // the fresh one gets its viewport from the re-run effect's own `pushViewport()`.if (syncAtlasPixelRatio(dpr, ctx) || ctx.disposed) return// The engine change-gates all three inputs, so calling this from every observer tick is// free when nothing actually moved.@@ -1718,13 +1797,31 @@ export function SharedGlyphLayer(): JSX.Element {// sessions sidebar opens, and a stale viewport culls the wrong grids.const ro = new ResizeObserver(pushViewport)ro.observe(host)- // ...and window resize on top of it, because a DPR change (dragging the window to a second- // monitor) leaves the CSS box identical while the backing store must change.+ // ...and window `resize` on top of it, for the ordinary window-size changes that move the CSS+ // box without moving the host's (and as ONE of the two triggers for a dpr change).window.addEventListener('resize', pushViewport)+ // THE OTHER dpr trigger, and DO NOT DELETE EITHER AS REDUNDANT. Dragging the window to a+ // display with a different pixel ratio leaves the CSS box identical, so the ResizeObserver is+ // silent and only `resize` — if Blink dispatches one for a scale-factor change with an+ // unchanged CSS viewport — would carry it. xterm does not rely on that: its `CoreBrowserService`+ // watches this media query, and this atlas latches xterm's own device cell, so it watches the+ // same thing. Both land in `pushViewport`, whose `syncAtlasPixelRatio` re-entry guard makes a+ // double fire free.+ const dprWatch = createPixelRatioWatcher(+ {+ dpr: currentDpr,+ match: (query) =>+ typeof window !== 'undefined' && typeof window.matchMedia === 'function'+ ? window.matchMedia(query)+ : null+ },+ pushViewport+ )/**- * 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.)+ * EVERYTHING THAT CAN DRAW OR SCHEDULE A FRAME, as one startable/stoppable unit. (The three+ * viewport triggers above are the deliberate exception — they schedule nothing; see their+ * comments.)** 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@@ -1899,6 +1996,7 @@ export function SharedGlyphLayer(): JSX.Element {policy.stop()ro.disconnect()window.removeEventListener('resize', pushViewport)+ dprWatch.stop()canvas.removeEventListener('webglcontextlost', onLost)canvas.removeEventListener('webglcontextrestored', onRestored)// The canvas leaves the DOM with the host div; the CONTEXT stays alive for the next mount