fix(terminal): mirror VS Code GPU rendering controls (#1344)

This commit is contained in:
Neil
2026-05-02 00:04:14 -07:00
committed by GitHub
parent 5dc7fbdabc
commit 9f2ab5ed0d
18 changed files with 232 additions and 108 deletions
@@ -43,6 +43,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
terminalFontFamily: 'JetBrains Mono',
terminalFontWeight: 500,
terminalLineHeight: 1,
terminalGpuAcceleration: 'auto',
terminalLigatures: 'auto',
terminalCursorStyle: 'block',
terminalCursorBlink: false,
+1
View File
@@ -37,6 +37,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
terminalFontFamily: 'JetBrains Mono',
terminalFontWeight: 500,
terminalLineHeight: 1,
terminalGpuAcceleration: 'auto',
terminalLigatures: 'auto',
terminalCursorStyle: 'block',
terminalCursorBlink: false,
+8 -73
View File
@@ -13,7 +13,8 @@ vi.mock('electron', () => {
exit: vi.fn(),
isPackaged: false,
commandLine: {
appendSwitch: vi.fn()
appendSwitch: vi.fn(),
getSwitchValue: vi.fn(() => '')
}
}
}
@@ -246,97 +247,31 @@ describe('installDevParentWatchdog', () => {
})
describe('enableMainProcessGpuFeatures', () => {
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
const originalWaylandDisplay = process.env.WAYLAND_DISPLAY
const originalXdgSessionType = process.env.XDG_SESSION_TYPE
function setPlatform(platform: NodeJS.Platform): void {
Object.defineProperty(process, 'platform', {
configurable: true,
value: platform
})
}
afterEach(() => {
if (originalPlatform) {
Object.defineProperty(process, 'platform', originalPlatform)
}
if (originalWaylandDisplay === undefined) {
delete process.env.WAYLAND_DISPLAY
} else {
process.env.WAYLAND_DISPLAY = originalWaylandDisplay
}
if (originalXdgSessionType === undefined) {
delete process.env.XDG_SESSION_TYPE
} else {
process.env.XDG_SESSION_TYPE = originalXdgSessionType
}
})
it('appends Orca GPU flags on darwin', async () => {
it('appends VS Code-style GPU channel flags without unsafe WebGPU/Vulkan opt-ins', async () => {
const { app } = await import('electron')
const { enableMainProcessGpuFeatures } = await import('./configure-process')
vi.mocked(app.commandLine.appendSwitch).mockClear()
setPlatform('darwin')
enableMainProcessGpuFeatures()
expect(app.commandLine.appendSwitch).toHaveBeenCalledWith(
'enable-features',
'Vulkan,UseSkiaGraphite'
'EarlyEstablishGpuChannel,EstablishGpuChannelAsync'
)
expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('enable-unsafe-webgpu')
expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('enable-unsafe-webgpu')
})
it('appends Orca GPU flags on linux X11 sessions', async () => {
// Why: Chromium's X11 Vulkan path works, so we keep Skia Graphite / WebGPU
// acceleration on X11. Only Wayland hits the wayland_surface_factory.cc
// incompatibility and needs the gate.
it('preserves existing enable-features switches', async () => {
const { app } = await import('electron')
const { enableMainProcessGpuFeatures } = await import('./configure-process')
vi.mocked(app.commandLine.appendSwitch).mockClear()
setPlatform('linux')
delete process.env.WAYLAND_DISPLAY
process.env.XDG_SESSION_TYPE = 'x11'
vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('ExistingFeature')
enableMainProcessGpuFeatures()
expect(app.commandLine.appendSwitch).toHaveBeenCalledWith(
'enable-features',
'Vulkan,UseSkiaGraphite'
'EarlyEstablishGpuChannel,EstablishGpuChannelAsync,ExistingFeature'
)
expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('enable-unsafe-webgpu')
})
it('skips Vulkan/SkiaGraphite/WebGPU switches when WAYLAND_DISPLAY is set', async () => {
// Why: Chromium's Ozone/Wayland surface factory hard-aborts with Vulkan
// enabled (wayland_surface_factory.cc:251), producing a blank/transparent
// window on Wayland-default distros (Arch/Omarchy/Hyprland, GNOME-Wayland).
const { app } = await import('electron')
const { enableMainProcessGpuFeatures } = await import('./configure-process')
vi.mocked(app.commandLine.appendSwitch).mockClear()
setPlatform('linux')
process.env.WAYLAND_DISPLAY = 'wayland-0'
delete process.env.XDG_SESSION_TYPE
enableMainProcessGpuFeatures()
expect(app.commandLine.appendSwitch).not.toHaveBeenCalled()
})
it('skips switches when XDG_SESSION_TYPE=wayland without WAYLAND_DISPLAY', async () => {
// Why: belt-and-suspenders — some nested/manually-started Wayland sessions
// advertise XDG_SESSION_TYPE=wayland without yet having WAYLAND_DISPLAY
// set in the process's environment at launch time.
const { app } = await import('electron')
const { enableMainProcessGpuFeatures } = await import('./configure-process')
vi.mocked(app.commandLine.appendSwitch).mockClear()
setPlatform('linux')
delete process.env.WAYLAND_DISPLAY
process.env.XDG_SESSION_TYPE = 'wayland'
enableMainProcessGpuFeatures()
expect(app.commandLine.appendSwitch).not.toHaveBeenCalled()
})
})
+12 -28
View File
@@ -169,33 +169,17 @@ export function installDevParentWatchdog(isDev: boolean): void {
timer.unref()
}
function isLinuxWaylandSession(): boolean {
// Why: WAYLAND_DISPLAY is set directly by the Wayland compositor and is the
// same signal Electron's own ELECTRON_OZONE_PLATFORM_HINT=auto logic uses.
// XDG_SESSION_TYPE is the login-manager/PAM signal and is the belt-and-
// suspenders check for sessions where WAYLAND_DISPLAY isn't set at process
// start (nested Wayland, manual session startup). Both are inherited from
// the parent process, so they're available before app.whenReady where the
// GPU command-line switches must be appended.
return (
process.platform === 'linux' &&
(Boolean(process.env.WAYLAND_DISPLAY) || process.env.XDG_SESSION_TYPE === 'wayland')
)
}
export function enableMainProcessGpuFeatures(): void {
// Why: Chromium's Ozone/Wayland surface factory hard-aborts when Vulkan is
// enabled (see wayland_surface_factory.cc:251 — "--ozone-platform=wayland is
// not compatible with Vulkan"), leaving the renderer unable to compose and
// showing a blank/transparent window on Wayland-default distros like
// Arch/Omarchy/Hyprland and GNOME-Wayland. Skia Graphite is Vulkan-only on
// Linux (no OpenGL backend), so enabling it with Vulkan off would silently
// fall back to software rendering — gate it on the same Wayland signal.
// The X11 Vulkan path works, so we keep the acceleration there and on
// macOS/Windows.
if (isLinuxWaylandSession()) {
return
}
app.commandLine.appendSwitch('enable-features', 'Vulkan,UseSkiaGraphite')
app.commandLine.appendSwitch('enable-unsafe-webgpu')
const existingFeatures = app.commandLine.getSwitchValue('enable-features')
const features = [
// Why: mirror VS Code's conservative Electron GPU-channel startup flags
// instead of opting into Vulkan/SkiaGraphite/unsafe WebGPU globally.
// Terminal acceleration is controlled by xterm WebGL in the renderer.
'EarlyEstablishGpuChannel',
'EstablishGpuChannelAsync',
existingFeatures
]
.filter(Boolean)
.join(',')
app.commandLine.appendSwitch('enable-features', features)
}
@@ -38,6 +38,7 @@ import {
TERMINAL_LIGHT_THEME_SEARCH_ENTRIES,
TERMINAL_MAC_OPTION_SEARCH_ENTRIES,
TERMINAL_PANE_STYLE_SEARCH_ENTRIES,
TERMINAL_RENDERING_SEARCH_ENTRIES,
TERMINAL_RIGHT_CLICK_TO_PASTE_SEARCH_ENTRY,
TERMINAL_SETUP_SCRIPT_SEARCH_ENTRIES,
TERMINAL_TYPOGRAPHY_SEARCH_ENTRIES,
@@ -322,6 +323,58 @@ export function TerminalPane({
</SearchableSetting>
</section>
) : null,
matchesSettingsSearch(searchQuery, TERMINAL_RENDERING_SEARCH_ENTRIES) ? (
<section key="rendering" className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-semibold">Rendering</h3>
<p className="text-xs text-muted-foreground">
Terminal renderer behavior for live panes and new panes.
</p>
</div>
<SearchableSetting
title="GPU Acceleration"
description="Controls whether the terminal uses xterm.js WebGL rendering. Auto mirrors VS Code: try GPU and fall back to DOM if WebGL fails."
keywords={[
'terminal',
'gpu',
'acceleration',
'webgl',
'renderer',
'rendering',
'graphics',
'linux',
'vscode'
]}
className="space-y-2"
>
<Label>GPU Acceleration</Label>
<div className="flex w-fit gap-1 rounded-md border border-border/50 p-1">
{(['auto', 'on', 'off'] as const).map((option) => (
<button
key={option}
type="button"
onClick={() => updateSettings({ terminalGpuAcceleration: option })}
className={`rounded-sm px-3 py-1 text-sm capitalize transition-colors ${
(settings.terminalGpuAcceleration ?? 'auto') === option
? 'bg-accent font-medium text-accent-foreground'
: 'text-muted-foreground hover:text-foreground'
}`}
>
{option === 'auto' ? 'Auto' : option === 'on' ? 'On' : 'Off'}
</button>
))}
</div>
<p className="text-xs text-muted-foreground">
{settings.terminalGpuAcceleration === 'off'
? 'WebGL is disabled; xterm uses the DOM renderer for maximum compatibility.'
: settings.terminalGpuAcceleration === 'on'
? 'WebGL is always attempted for terminal panes.'
: 'Auto tries WebGL for performance and falls back to the DOM renderer if WebGL fails, matching VS Code.'}
</p>
</SearchableSetting>
</section>
) : null,
matchesSettingsSearch(searchQuery, TERMINAL_CURSOR_SEARCH_ENTRIES) ? (
<section key="cursor" className="space-y-4">
<div className="space-y-1">
@@ -40,6 +40,25 @@ export const TERMINAL_TYPOGRAPHY_SEARCH_ENTRIES: SettingsSearchEntry[] = [
}
]
export const TERMINAL_RENDERING_SEARCH_ENTRIES: SettingsSearchEntry[] = [
{
title: 'GPU Acceleration',
description:
'Controls whether the terminal uses xterm.js WebGL rendering. Auto mirrors VS Code: try GPU and fall back to DOM if WebGL fails.',
keywords: [
'terminal',
'gpu',
'acceleration',
'webgl',
'renderer',
'rendering',
'graphics',
'linux',
'vscode'
]
}
]
export const TERMINAL_CURSOR_SEARCH_ENTRIES: SettingsSearchEntry[] = [
{
title: 'Cursor Shape',
@@ -270,6 +289,7 @@ export function getTerminalPaneSearchEntries(platform: {
// users from landing on an option the UI intentionally hides.
return [
...TERMINAL_TYPOGRAPHY_SEARCH_ENTRIES,
...TERMINAL_RENDERING_SEARCH_ENTRIES,
...TERMINAL_CURSOR_SEARCH_ENTRIES,
...TERMINAL_PANE_STYLE_SEARCH_ENTRIES,
...(platform.isWindows ? TERMINAL_WINDOWS_SEARCH_ENTRIES : []),
@@ -10,6 +10,7 @@ const baseSettings: GlobalSettings = {
terminalFontSize: 12,
terminalFontWeight: 400,
terminalLineHeight: 1,
terminalGpuAcceleration: 'auto',
terminalCursorStyle: 'bar',
terminalCursorBlink: true,
terminalScrollbackBytes: 10_000_000,
@@ -664,6 +664,7 @@ export function useTerminalPaneLifecycle({
// so PTYs survive navigation. Creating WebGL for those offscreen panes
// still consumes Chromium's context budget and can blank visible panes.
initialRenderingSuspended: !isVisibleRef.current,
terminalGpuAcceleration: settingsRef.current?.terminalGpuAcceleration ?? 'auto',
debugLabel: `tab:${tabId}/wt:${worktreeId}`
})
@@ -907,6 +908,10 @@ export function useTerminalPaneLifecycle({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [settings, systemPrefersDark, effectiveMacOptionAsAlt])
useEffect(() => {
managerRef.current?.setTerminalGpuAcceleration(settings?.terminalGpuAcceleration ?? 'auto')
}, [settings?.terminalGpuAcceleration, managerRef])
useEffect(() => {
const manager = managerRef.current
if (!manager) {
@@ -42,6 +42,7 @@ function createPane(): ManagedPaneInternal {
container: {} as never,
xtermContainer: {} as never,
linkTooltip: {} as never,
terminalGpuAcceleration: 'auto',
gpuRenderingEnabled: true,
webglAttachmentDeferred: false,
webglDisabledAfterContextLoss: false,
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { WebglAddon } from '@xterm/addon-webgl'
import type { ManagedPaneInternal } from './pane-manager-types'
import { attachWebgl } from './pane-lifecycle'
import { attachWebgl, resetTerminalWebglSuggestion } from './pane-lifecycle'
import { buildDefaultTerminalOptions } from './pane-terminal-options'
const webglMock = vi.hoisted(() => ({
@@ -30,6 +31,7 @@ function createPane(): ManagedPaneInternal {
container: {} as never,
xtermContainer: {} as never,
linkTooltip: {} as never,
terminalGpuAcceleration: 'auto',
gpuRenderingEnabled: true,
webglAttachmentDeferred: false,
webglDisabledAfterContextLoss: false,
@@ -70,6 +72,8 @@ describe('attachWebgl', () => {
beforeEach(() => {
webglMock.contextLossHandler = null
webglMock.dispose.mockClear()
vi.mocked(WebglAddon).mockClear()
resetTerminalWebglSuggestion()
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
callback(16)
return 1
@@ -106,4 +110,51 @@ describe('attachWebgl', () => {
expect(pane.webglAddon).toBeNull()
expect(pane.terminal.loadAddon).not.toHaveBeenCalled()
})
it('does not attach WebGL when terminal GPU acceleration is off', () => {
const pane = createPane()
pane.terminalGpuAcceleration = 'off'
attachWebgl(pane)
expect(pane.webglAddon).toBeNull()
expect(pane.terminal.loadAddon).not.toHaveBeenCalled()
})
it('uses DOM for later auto panes after WebGL attach fails until the suggestion resets', () => {
const firstPane = createPane()
vi.mocked(WebglAddon).mockImplementationOnce(() => {
throw new Error('webgl unavailable')
})
attachWebgl(firstPane)
expect(firstPane.webglAddon).toBeNull()
const laterAutoPane = createPane()
attachWebgl(laterAutoPane)
expect(laterAutoPane.terminal.loadAddon).not.toHaveBeenCalled()
resetTerminalWebglSuggestion()
const retriedAutoPane = createPane()
attachWebgl(retriedAutoPane)
expect(retriedAutoPane.terminal.loadAddon).toHaveBeenCalledTimes(1)
})
it('still attempts WebGL in on mode after auto mode suggests DOM', () => {
const autoPane = createPane()
vi.mocked(WebglAddon).mockImplementationOnce(() => {
throw new Error('webgl unavailable')
})
attachWebgl(autoPane)
const forcedPane = createPane()
forcedPane.terminalGpuAcceleration = 'on'
attachWebgl(forcedPane)
expect(forcedPane.terminal.loadAddon).toHaveBeenCalledTimes(1)
})
})
@@ -23,12 +23,24 @@ import {
detachPaneFitResizeObserver
} from './pane-fit-resize-observer'
import { buildDefaultTerminalOptions } from './pane-terminal-options'
import type { GlobalSettings } from '../../../../shared/types'
// ---------------------------------------------------------------------------
// Pane creation, terminal open/close, addon management
// ---------------------------------------------------------------------------
const ENABLE_WEBGL_RENDERER = true
let suggestedRendererType: 'dom' | undefined
export function resetTerminalWebglSuggestion(): void {
// Why: VS Code clears its suggested renderer when gpuAcceleration changes,
// letting "auto" retry WebGL after a user toggles the setting.
suggestedRendererType = undefined
}
function shouldUseWebgl(mode: GlobalSettings['terminalGpuAcceleration']): boolean {
return mode === 'on' || (mode === 'auto' && suggestedRendererType === undefined)
}
function getTerminalUrlOpenHint(): string {
return navigator.userAgent.includes('Mac')
@@ -108,6 +120,7 @@ export function createPaneDOM(
container,
xtermContainer,
linkTooltip,
terminalGpuAcceleration: options.terminalGpuAcceleration ?? 'auto',
gpuRenderingEnabled: ENABLE_WEBGL_RENDERER,
webglAttachmentDeferred: false,
webglDisabledAfterContextLoss: false,
@@ -284,6 +297,7 @@ export function attachWebgl(pane: ManagedPaneInternal): void {
if (
!ENABLE_WEBGL_RENDERER ||
!pane.gpuRenderingEnabled ||
!shouldUseWebgl(pane.terminalGpuAcceleration) ||
pane.webglAttachmentDeferred ||
pane.webglDisabledAfterContextLoss
) {
@@ -326,6 +340,12 @@ export function attachWebgl(pane: ManagedPaneInternal): void {
pane.terminal.loadAddon(webglAddon)
pane.webglAddon = webglAddon
} catch (err) {
if (pane.terminalGpuAcceleration === 'auto') {
// Why: mirrors VS Code's `terminal.integrated.gpuAcceleration=auto`
// behavior: once WebGL fails, keep subsequent auto panes on DOM until
// the setting changes and resets the suggestion.
suggestedRendererType = 'dom'
}
// WebGL not available — default DOM renderer is fine, but log it for debugging
console.warn('[terminal] WebGL unavailable for pane', pane.id, '— using DOM renderer:', err)
pane.webglAddon = null
@@ -7,6 +7,7 @@ import type { Unicode11Addon } from '@xterm/addon-unicode11'
import type { WebLinksAddon } from '@xterm/addon-web-links'
import type { WebglAddon } from '@xterm/addon-webgl'
import type { SerializeAddon } from '@xterm/addon-serialize'
import type { GlobalSettings } from '../../../../shared/types'
// ---------------------------------------------------------------------------
// Public interfaces
@@ -28,6 +29,7 @@ export type PaneManagerOptions = {
terminalOptions?: (paneId: number) => Partial<ITerminalOptions>
onLinkClick?: (event: MouseEvent | undefined, url: string) => void
initialRenderingSuspended?: boolean
terminalGpuAcceleration?: GlobalSettings['terminalGpuAcceleration']
// Why: diagnostic label for log correlation. safeFit and other internal
// helpers log warnings that are hard to correlate without knowing which
// tab/worktree the PaneManager belongs to.
@@ -74,6 +76,7 @@ export type ScrollState = {
export type ManagedPaneInternal = {
xtermContainer: HTMLElement
linkTooltip: HTMLElement
terminalGpuAcceleration: GlobalSettings['terminalGpuAcceleration']
gpuRenderingEnabled: boolean
webglAttachmentDeferred: boolean
webglDisabledAfterContextLoss: boolean
@@ -38,15 +38,11 @@ import {
} from './pane-tree-ops'
import { scheduleSplitScrollRestore } from './pane-split-scroll'
import { toPublicPane } from './pane-public-view'
import { applyTerminalGpuAcceleration } from './pane-terminal-gpu-acceleration'
import { reattachWebglIfNeeded } from './pane-webgl-reattach'
export type { PaneManagerOptions, PaneStyleOptions, ManagedPane, DropZone }
function reattachWebglIfNeeded(pane: ManagedPaneInternal): void {
if (pane.gpuRenderingEnabled && !pane.webglAddon && !pane.webglDisabledAfterContextLoss) {
attachWebgl(pane)
}
}
export class PaneManager {
private root: HTMLElement
private panes: Map<number, ManagedPaneInternal> = new Map()
@@ -246,6 +242,10 @@ export class PaneManager {
}
}
setTerminalGpuAcceleration(mode: PaneManagerOptions['terminalGpuAcceleration']): void {
applyTerminalGpuAcceleration(this.panes.values(), this.options, mode)
}
suspendRendering(): void {
this.renderingSuspended = true
for (const pane of this.panes.values()) {
@@ -0,0 +1,32 @@
import type { ManagedPaneInternal, PaneManagerOptions } from './pane-manager-types'
import { attachWebgl, disposeWebgl, resetTerminalWebglSuggestion } from './pane-lifecycle'
import { safeFit } from './pane-tree-ops'
export function applyTerminalGpuAcceleration(
panes: Iterable<ManagedPaneInternal>,
options: PaneManagerOptions,
mode: PaneManagerOptions['terminalGpuAcceleration']
): void {
const nextMode = mode ?? 'auto'
const previousMode = options.terminalGpuAcceleration ?? 'auto'
options.terminalGpuAcceleration = nextMode
if (previousMode !== nextMode) {
resetTerminalWebglSuggestion()
}
for (const pane of panes) {
pane.terminalGpuAcceleration = nextMode
if (nextMode === 'off') {
disposeWebgl(pane)
continue
}
if (
pane.gpuRenderingEnabled &&
!pane.webglAddon &&
!pane.webglAttachmentDeferred &&
!pane.webglDisabledAfterContextLoss
) {
attachWebgl(pane)
safeFit(pane)
}
}
}
@@ -36,6 +36,7 @@ function createPane({
container: {} as never,
xtermContainer: {} as never,
linkTooltip: {} as never,
terminalGpuAcceleration: 'auto',
gpuRenderingEnabled: true,
webglAttachmentDeferred: false,
webglDisabledAfterContextLoss: false,
@@ -0,0 +1,8 @@
import type { ManagedPaneInternal } from './pane-manager-types'
import { attachWebgl } from './pane-lifecycle'
export function reattachWebglIfNeeded(pane: ManagedPaneInternal): void {
if (pane.gpuRenderingEnabled && !pane.webglAddon && !pane.webglDisabledAfterContextLoss) {
attachWebgl(pane)
}
}
+3
View File
@@ -125,6 +125,9 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
terminalFontFamily: defaultTerminalFontFamily(),
terminalFontWeight: DEFAULT_TERMINAL_FONT_WEIGHT,
terminalLineHeight: 1,
// Why: VS Code defaults terminal GPU acceleration to "auto": prefer
// xterm WebGL for performance, but allow renderer failure to choose DOM.
terminalGpuAcceleration: 'auto',
// Why 'auto': when the user has picked a known ligature font we want the
// feature enabled by default, but we never force it if they pick a font
// that lacks ligatures or if they've explicitly opted out. The resolver
+5
View File
@@ -954,6 +954,11 @@ export type GlobalSettings = {
terminalFontFamily: string
terminalFontWeight: number
terminalLineHeight: number
/** Mirrors VS Code's terminal.integrated.gpuAcceleration shape.
* - 'auto': try xterm WebGL and fall back to DOM if the renderer fails.
* - 'on': always try xterm WebGL.
* - 'off': keep terminal rendering on xterm's DOM renderer. */
terminalGpuAcceleration: 'auto' | 'on' | 'off'
/** Whether to enable programming-ligatures rendering via
* `@xterm/addon-ligatures`.
* - `'auto'` (default): enabled only when the configured font is known to