Skip to content

The agent that grows with you

fix(desktop): refresh sibling terminals when the shared WebGL atlas is cleared

Soheil Fakour46d79892022f
diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminals.test.ts b/apps/desktop/src/app/right-sidebar/terminal/terminals.test.ts
index 2a04c8d6464..6dae1351536 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/terminals.test.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/terminals.test.ts
@@ -189,3 +189,84 @@ describe('session cwd → terminal tab linking', () => {
expect($activeTerminalId.get()).toBe(first)
})
})
+
+describe('shared WebGL atlas refresh fan-out', () => {
+ beforeEach(() => {
+ window.localStorage.clear()
+ vi.resetModules()
+ })
+
+ it('coalesces multiple requests into one frame and drops unregistered terminals', async () => {
+ const { redrawAllTerminals, registerWebglRefresh } = await loadTerminalStore()
+
+ const termA = { refresh: vi.fn(), rows: 24 }
+ const termB = { refresh: vi.fn(), rows: 24 }
+ const getWebgl = () => ({ clearTextureAtlas: vi.fn() }) as never
+ const unregister = registerWebglRefresh(termA as never, getWebgl)
+ registerWebglRefresh(termB as never, getWebgl)
+
+ // A theme switch fires one redraw request per mounted terminal; they must
+ // coalesce into a single atlas clear/refresh pass.
+ redrawAllTerminals()
+ redrawAllTerminals()
+ expect(termA.refresh).not.toHaveBeenCalled()
+ expect(termB.refresh).not.toHaveBeenCalled()
+
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve())
+ })
+
+ expect(termA.refresh).toHaveBeenCalledTimes(1)
+ expect(termB.refresh).toHaveBeenCalledTimes(1)
+
+ // A terminal that disposes (tab close) must stop being refreshed.
+ unregister()
+ redrawAllTerminals()
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve())
+ })
+
+ expect(termA.refresh).toHaveBeenCalledTimes(1)
+ expect(termB.refresh).toHaveBeenCalledTimes(2)
+ })
+
+ it('drops a terminal unregistered while a refresh frame is pending', async () => {
+ const { redrawAllTerminals, registerWebglRefresh } = await loadTerminalStore()
+
+ const termA = { refresh: vi.fn(), rows: 24 }
+ const termB = { refresh: vi.fn(), rows: 24 }
+ const getWebgl = () => ({ clearTextureAtlas: vi.fn() }) as never
+ registerWebglRefresh(termA as never, getWebgl)
+ const unregister = registerWebglRefresh(termB as never, getWebgl)
+
+ // Both are pending in the same frame; second disposes before it flushes.
+ redrawAllTerminals()
+ unregister()
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve())
+ })
+
+ expect(termA.refresh).toHaveBeenCalledTimes(1)
+ expect(termB.refresh).not.toHaveBeenCalled()
+ })
+
+ it('skips the caller terminal so it is not force-cleared through the fan-out', async () => {
+ const { redrawAllTerminals, registerWebglRefresh } = await loadTerminalStore()
+
+ const caller = { refresh: vi.fn(), rows: 24 }
+ const sibling = { refresh: vi.fn(), rows: 24 }
+ const getWebgl = () => ({ clearTextureAtlas: vi.fn() }) as never
+ registerWebglRefresh(caller as never, getWebgl)
+ registerWebglRefresh(sibling as never, getWebgl)
+
+ // A font change clears the caller inline (applyTerminalFontFamily), so the
+ // fan-out must not re-clear it — only the siblings sharing the atlas.
+ redrawAllTerminals(caller as never)
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve())
+ })
+
+ expect(caller.refresh).not.toHaveBeenCalled()
+ expect(sibling.refresh).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts b/apps/desktop/src/app/right-sidebar/terminal/terminals.ts
index 19b560f49d1..3fbde4ddcaa 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/terminals.ts
@@ -1,3 +1,5 @@
+import type { WebglAddon } from '@xterm/addon-webgl'
+import type { Terminal } from '@xterm/xterm'
import { atom, computed } from 'nanostores'
import { readKey, writeKey } from '@/lib/storage'
@@ -7,6 +9,66 @@ import { setTerminalTakeover } from '../store'
import { seedAgentTerminalCommand } from './agent-terminal-stream'
+// xterm WebGL terminals that share one glyph atlas (same font/theme/DPR) keep
+// per-terminal render models over a SHARED texture. Clearing one terminal's
+// atlas (theme switch, tab activation) wipes the shared texture pages, and
+// xterm 0.19 never tells the sibling renderers to rebuild their models — so
+// their stale cells draw whatever glyphs land in the freed atlas rows: garbled
+// text until a resize forces a full refresh. Upstream fixed this in
+// xtermjs/xterm.js#6055 (atlas clear bumps the shared page-layout version);
+// we stay pinned on 0.19.0, so every terminal that mutates the shared atlas
+// must refresh its siblings itself. Registration is the inverse: each xterm
+// registers its own redraw+atlas-rebuild and unregisters on dispose.
+const webglRefreshFns = new Map<Terminal, () => void>()
+
+/** Register a terminal's atlas-rebuild+redraw so sibling refreshes reach it.
+ * Returns an unregister function (call on dispose). */
+export function registerWebglRefresh(
+ term: Terminal,
+ getWebgl: () => WebglAddon | null
+): () => void {
+ webglRefreshFns.set(term, () => {
+ getWebgl()?.clearTextureAtlas()
+ term.refresh(0, term.rows - 1)
+ })
+
+ return () => {
+ webglRefreshFns.delete(term)
+ }
+}
+
+let refreshFrame = 0
+
+/** Rebuild the glyph atlas + redraw every live xterm EXCEPT *skipTerm* (when
+ * given). Callers that are about to mutate the shared atlas (clearTextureAtlas)
+ * must fan out so the OTHER terminals sharing it don't keep drawing stale
+ * cells. Coalesced into one frame per tick: a theme switch fires N
+ * per-terminal effects, and fanning out on each would clear+rebuild the atlas
+ * N times over.
+ *
+ * Skip the caller only when it already clears+redraws itself inline (font
+ * change); theme/activation callers must NOT skip — they need their own atlas
+ * rebuilt too (the theme colors changed / the frame was stale while hidden).
+ * Terminals on a different atlas (different font/theme/DPR) are force-cleared
+ * harmlessly; DOM-fallback terminals aren't registered at all. */
+export function redrawAllTerminals(skipTerm?: Terminal): void {
+ if (refreshFrame) {
+ return
+ }
+
+ refreshFrame = requestAnimationFrame(() => {
+ refreshFrame = 0
+
+ for (const [term, refresh] of webglRefreshFns) {
+ if (skipTerm && term === skipTerm) {
+ continue
+ }
+
+ refresh()
+ }
+ })
+}
+
/** One in-app terminal tab. `id` is the renderer-side handle (distinct from the
* PTY session id the main process mints); each instance owns its own shell. */
export interface TerminalEntry {
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
index 7ea4f711363..56bf5cfc4e1 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts
@@ -5,11 +5,9 @@ import { Terminal } from '@xterm/xterm'
import { useEffect, useRef } from 'react'
import { writeClipboardText } from '@/components/ui/copy-button'
-import { markRightPanePerf } from '@/debug/right-pane-events'
import { triggerHaptic } from '@/lib/haptics'
import { useTheme } from '@/themes/context'
-import { observeActiveTerminalResize } from './active-resize'
import { registerAgentTerminalWriter } from './agent-terminal-stream'
import { makeTerminalReader, registerTerminalReader } from './buffer'
import { mirrorSelection, terminalClipboardIntent } from './clipboard'
@@ -17,6 +15,7 @@ import { terminalLinkHandler, terminalWebLinksAddon } from './links'
import { isMacPlatform, resolveSurfaceColor, terminalTheme } from './selection'
import { registerTerminalContextMenu } from './terminal-context-menu'
import { prepareTerminalFontFamily } from './terminal-font'
+import { redrawAllTerminals, registerWebglRefresh } from './terminals'
import { useTerminalFontController } from './use-terminal-font'
// Read-only terminal for an agent background process: a write-only xterm (no PTY,
@@ -27,8 +26,7 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
const hostRef = useRef<HTMLDivElement | null>(null)
const termRef = useRef<Terminal | null>(null)
const webglRef = useRef<WebglAddon | null>(null)
- const fitRef = useRef<((visible: boolean) => void) | null>(null)
- const initialActiveFitRef = useRef(false)
+ const fitRef = useRef<(() => void) | null>(null)
const { latestFontFamilyRef, mountedRef } = useTerminalFontController({ fitRef, termRef, webglRef })
const surfaceTheme = () => {
@@ -51,6 +49,7 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
}
let disposed = false
+ let observer: ResizeObserver | null = null
let unregister = () => {}
@@ -116,11 +115,10 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
return false
})
- fitRef.current = visible => {
+ fitRef.current = () => {
if (host.clientWidth > 0 && host.clientHeight > 0) {
try {
fit.fit()
- markRightPanePerf(visible ? 'terminal-fit-active' : 'terminal-fit-hidden', id)
} catch {
// Mid-transition layout — the next observer tick refits.
}
@@ -148,14 +146,20 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
// No WebGL — xterm falls back to the DOM renderer.
}
- fitRef.current?.(active)
- initialActiveFitRef.current = active
+ fitRef.current?.()
+ observer = new ResizeObserver(() => fitRef.current?.())
+ observer.observe(host)
// Stream live output straight into the terminal (replays backlog on attach).
unregister = registerAgentTerminalWriter(procId, chunk => term.write(chunk))
unregisterReader = registerTerminalReader(id, makeTerminalReader(term))
}
+ // Join the shared-atlas refresh fan-out (see redrawAllTerminals in
+ // terminals.ts): clearing this terminal's atlas mutates texture pages the
+ // user terminals draw from, so they must rebuild their models too.
+ const unregisterWebglRefresh = registerWebglRefresh(term, () => webglRef.current)
+
void prepareTerminalFontFamily(
() => latestFontFamilyRef.current,
() => !disposed && host.isConnected
@@ -173,8 +177,10 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
mountedRef.current = false
unregister()
unregisterReader()
+ unregisterWebglRefresh()
selectionDisposable.dispose()
contextMenuDisposable()
+ observer?.disconnect()
fitRef.current = null
term.dispose()
termRef.current = null
@@ -192,46 +198,33 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:
const raf = requestAnimationFrame(() => {
term.options.theme = surfaceTheme()
- webglRef.current?.clearTextureAtlas()
+ // The atlas is shared across every terminal with the same render config,
+ // so the clear must fan out to the siblings too (see redrawAllTerminals).
+ redrawAllTerminals()
})
return () => cancelAnimationFrame(raf)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [renderedMode, themeName])
- // Keep inactive agent terminals mounted for their backlog, but do not observe
- // or fit them until they become the visible tab.
- // eslint-disable-next-line no-restricted-syntax -- lifecycle flag prevents a duplicate first-mount fit
+ // A visibility:hidden xterm doesn't paint — refit + redraw on re-activation.
useEffect(() => {
if (!active) {
- initialActiveFitRef.current = false
-
return
}
- const host = hostRef.current
+ const frame = requestAnimationFrame(() => {
+ const term = termRef.current
- if (!host) {
- return
- }
-
- const fitOnActivate = !initialActiveFitRef.current
- initialActiveFitRef.current = false
-
- return observeActiveTerminalResize(host, {
- fitOnActivate,
- onFit: () => fitRef.current?.(true),
- onActivate: () => {
- const term = termRef.current
-
- webglRef.current?.clearTextureAtlas()
- term?.refresh(0, term.rows - 1)
- // Take focus on activation (parity with the user terminal) so the active
- // agent tab holds focus and ⌘W's isFocusWithin('[data-terminal]') routes
- // the close to this tab rather than to a preview.
- term?.focus()
- }
+ fitRef.current?.()
+ redrawAllTerminals()
+ // Take focus on activation (parity with the user terminal) so the active
+ // agent tab holds focus and ⌘W's isFocusWithin('[data-terminal]') routes
+ // the close to this tab rather than to a preview.
+ term?.focus()
})
+
+ return () => cancelAnimationFrame(frame)
}, [active])
return { hostRef }
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts
index 8bcf76426e2..01aa07b1993 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts
@@ -5,6 +5,7 @@ import { useEffect, useRef } from 'react'
import type { RefObject } from 'react'
import { $terminalFontFamily, applyTerminalFontFamily, resolveTerminalFontFamily } from './terminal-font'
+import { redrawAllTerminals } from './terminals'
interface TerminalFontControllerOptions {
fitRef: RefObject<((visible: boolean) => void) | null>
@@ -43,6 +44,11 @@ export function useTerminalFontController({ fitRef, termRef, webglRef }: Termina
isCurrent: () => !cancelled && generationRef.current === generation,
term
})
+ // Font is an atlas-share key: changing one terminal's font rebuilds the
+ // shared glyph set, so siblings sharing the atlas must rebuild their
+ // models too (see redrawAllTerminals). The caller clears itself inline
+ // (applyTerminalFontFamily), so skip it in the fan-out.
+ redrawAllTerminals(term)
return () => {
cancelled = true
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
index 76723f694d3..1263ebce42b 100644
--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts
@@ -7,7 +7,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { CSSProperties } from 'react'
import { writeClipboardText } from '@/components/ui/copy-button'
-import { markRightPanePerf } from '@/debug/right-pane-events'
import { triggerHaptic } from '@/lib/haptics'
import { isComposerChord } from '@/lib/keybinds/chords'
import { $previewTarget } from '@/store/preview'
@@ -15,7 +14,6 @@ import { useTheme } from '@/themes/context'
import { $terminalInjection } from '../store'
-import { observeActiveTerminalResize } from './active-resize'
import { makeTerminalReader, registerTerminalReader } from './buffer'
import { mirrorSelection, terminalClipboardIntent } from './clipboard'
import { terminalLinkHandler, terminalWebLinksAddon } from './links'
@@ -28,7 +26,7 @@ import {
} from './selection'
import { registerTerminalContextMenu } from './terminal-context-menu'
import { prepareTerminalFontFamily } from './terminal-font'
-import { closeTerminal, updateTerminalRestoreCwd, updateTerminalReviveBuffer } from './terminals'
+import { closeTerminal, redrawAllTerminals, registerWebglRefresh, updateTerminalRestoreCwd, updateTerminalReviveBuffer } from './terminals'
import { useTerminalFontController } from './use-terminal-font'
// How many scrollback lines to serialize for relaunch restore. Mirrors VS Code's
@@ -416,7 +414,6 @@ export function useTerminalSession({
// drag-and-drop paths, or an injected command). Gates idle-buffer handling in
// persistSnapshot so an untouched tab never re-saves an accumulating snapshot.
const hasSessionActivityRef = useRef(false)
- const initialActiveRef = useRef(active)
const shellNameRef = useRef('shell')
const selectionLabelRef = useRef('')
const selectionRef = useRef('')
@@ -424,8 +421,7 @@ export function useTerminalSession({
const onShellRef = useRef(onShell)
// Re-fit on activation: a tab hidden via display:none has a 0×0 host, so its
// last fit is stale by the time it's shown again.
- const fitRef = useRef<((visible: boolean) => void) | null>(null)
- const initialActiveFitRef = useRef(false)
+ const fitRef = useRef<(() => void) | null>(null)
const { latestFontFamilyRef, mountedRef } = useTerminalFontController({ fitRef, termRef, webglRef })
const [status, setStatus] = useState<TerminalStatus>('starting')
const [selection, setSelection] = useState('')
@@ -747,28 +743,56 @@ export function useTerminalSession({
term.write(next)
}
- const fitAndResize = (visible: boolean) => {
+ const fitAndResize = () => {
if (disposed || !host.isConnected || host.clientWidth <= 0 || host.clientHeight <= 0) {
return
}
try {
fit.fit()
- markRightPanePerf(visible ? 'terminal-fit-active' : 'terminal-fit-hidden', id)
} catch {
return
}
- const sessionId = sessionIdRef.current
+ const id = sessionIdRef.current
- if (sessionId && (lastSentSize?.cols !== term.cols || lastSentSize?.rows !== term.rows)) {
+ if (id && (lastSentSize?.cols !== term.cols || lastSentSize?.rows !== term.rows)) {
lastSentSize = { cols: term.cols, rows: term.rows }
- void terminalApi.resize(sessionId, { cols: term.cols, rows: term.rows })
+ void terminalApi.resize(id, { cols: term.cols, rows: term.rows })
}
}
fitRef.current = fitAndResize
+ // Coalesce ResizeObserver bursts through rAF — running fit.fit()
+ // synchronously while sibling panes are mid-transition (e.g. file browser
+ // collapsing to 0px) crashes the WebGL renderer mid texture-atlas rebuild.
+ let pendingFrame = 0
+
+ const scheduleResize = () => {
+ if (pendingFrame) {
+ return
+ }
+
+ pendingFrame = window.requestAnimationFrame(() => {
+ pendingFrame = 0
+
+ if (!disposed) {
+ fitAndResize()
+ }
+ })
+ }
+
+ const resizeObserver = new ResizeObserver(scheduleResize)
+ resizeObserver.observe(host)
+ cleanup.push(() => {
+ resizeObserver.disconnect()
+
+ if (pendingFrame) {
+ window.cancelAnimationFrame(pendingFrame)
+ }
+ })
+
const dataDisposable = term.onData(data => {
hasSessionActivityRef.current = true
const id = sessionIdRef.current
@@ -909,7 +933,9 @@ export function useTerminalSession({
setStatus('open')
window.requestAnimationFrame(() => {
+ fitAndResize()
term.clearSelection() // drop any selection painted over transient boot rows
+ term.focus()
})
})
.catch(error => {
@@ -944,8 +970,12 @@ export function useTerminalSession({
console.warn('[hermes-terminal] WebGL unavailable; falling back to DOM', err)
}
- fitAndResize(initialActiveRef.current)
- initialActiveFitRef.current = initialActiveRef.current
+ // Join the shared-atlas refresh fan-out: this terminal's atlas-clear
+ // callers mutate a texture the siblings draw from, so they must rebuild
+ // their models too (see redrawAllTerminals in terminals.ts).
+ cleanup.push(registerWebglRefresh(term, () => webglRef.current))
+
+ fitAndResize()
startSession()
}
@@ -1000,8 +1030,10 @@ export function useTerminalSession({
term.options.theme = withSurface(activeTheme)
// The WebGL renderer caches glyph colors in a texture atlas, so a
// light/dark switch leaves already-drawn cells stale until the atlas is
- // cleared. No-op for the DOM fallback.
- webglRef.current?.clearTextureAtlas()
+ // cleared. No-op for the DOM fallback. The atlas is shared across every
+ // terminal with the same render config, so the clear must fan out to the
+ // siblings too (see redrawAllTerminals) or they keep stale glyphs.
+ redrawAllTerminals()
})
return () => cancelAnimationFrame(raf)
@@ -1020,39 +1052,26 @@ export function useTerminalSession({
return term ? registerTerminalReader(id, makeTerminalReader(term)) : undefined
}, [id, status])
- // Only the active terminal observes its host. Every terminal stays mounted
- // (PTY + scrollback preserved), but hidden tabs do no FitAddon/layout work.
- // Re-activation owns one fit + atlas rebuild + redraw.
- // eslint-disable-next-line no-restricted-syntax -- lifecycle flag prevents a duplicate first-mount fit
+ // On (re)activation: a WebGL terminal doesn't paint while visibility:hidden, so
+ // it reveals a stale/garbled frame. Refit, rebuild the glyph atlas, and force a
+ // full redraw against the live buffer, then focus. The atlas is shared across
+ // every terminal with the same render config, so rebuild ALL of them (see
+ // redrawAllTerminals) — refreshing only this one leaves its siblings drawing
+ // from wiped atlas pages.
useEffect(() => {
if (!active || status !== 'open') {
- if (!active) {
- initialActiveFitRef.current = false
- }
-
return
}
- const host = hostRef.current
+ const frame = requestAnimationFrame(() => {
+ const term = termRef.current
- if (!host) {
- return
- }
-
- const fitOnActivate = !initialActiveFitRef.current
- initialActiveFitRef.current = false
-
- return observeActiveTerminalResize(host, {
- fitOnActivate,
- onFit: () => fitRef.current?.(true),
- onActivate: () => {
- const term = termRef.current
-
- webglRef.current?.clearTextureAtlas()
- term?.refresh(0, term.rows - 1)
- term?.focus()
- }
+ fitRef.current?.()
+ redrawAllTerminals()
+ term?.focus()
})
+
+ return () => cancelAnimationFrame(frame)
}, [active, status])
// Flush a queued command (e.g. a provider-disconnect) into the live session.