Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions apps/desktop/docs/TERMINAL_WEBGL_RENDERING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Terminal WebGL Rendering

This note covers the terminal rendering fixes in this PR. These are renderer
fixes only; they do not change PTY lifetime, replay, serialized terminal
buffers, pane ownership, or terminal parking.

## Implemented Fixes

- Terminal WebGL addon setup is centralized in
`apps/desktop/src/renderer/lib/terminal/terminal-webgl-addon.ts`, so both
terminal creation paths use the same lifecycle.
- WebGL loading remains optional and delayed by one animation frame.
- If `WebglAddon` fails to load, later terminals in the same renderer process
skip WebGL and use xterm's non-WebGL renderer.
- If WebGL reports context loss, the current terminal disposes its WebGL addon,
refreshes visible rows immediately, refreshes again on the next animation
frame, and marks future terminals in that renderer process for DOM fallback.
- If xterm's WebGL atlas reaches pressure, the code calls the public
`WebglAddon.clearTextureAtlas()` API and refreshes visible rows. Detection is
limited to xterm renderer state: `_charAtlas._requestClearModel === true` or
an atlas page at least `2048px`.

## Why This Fix Is Local

Glyph corruption can happen while the copied terminal text and backend session
are still correct. That points at stale WebGL glyph atlas pixels rather than a
PTY stream or replay bug. Clearing the texture atlas forces xterm to rasterize
the visible glyphs again without rebuilding the terminal runtime or touching
the session.

## Related Upstream Issue

`xtermjs/xterm.js#5847`
(https://github.com/xtermjs/xterm.js/issues/5847) reports WebGL row ghosting
and glyph substitution under heavy true-color output.
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,28 @@ export interface DiffStats {
deletions: number;
}

export function useDiffStats(workspaceId: string): DiffStats | null {
interface UseDiffStatsOptions {
enabled?: boolean;
}

export function useDiffStats(
workspaceId: string,
options: UseDiffStatsOptions = {},
): DiffStats | null {
const { enabled = true } = options;
const hostUrl = useWorkspaceHostUrl(workspaceId);
const queryClient = useQueryClient();
const queryKey = useMemo(
() => ["diff-stats", hostUrl, workspaceId] as const,
[hostUrl, workspaceId],
);

const { data: status } = useQuery({
const { data: stats } = useQuery({
queryKey,
enabled: Boolean(workspaceId) && Boolean(hostUrl),
enabled: enabled && Boolean(workspaceId) && Boolean(hostUrl),
queryFn: () => {
if (!hostUrl) return null;
return getHostServiceClientByUrl(hostUrl).git.getStatus.query({
return getHostServiceClientByUrl(hostUrl).git.getDiffStats.query({
workspaceId,
});
},
Expand All @@ -34,22 +42,7 @@ export function useDiffStats(workspaceId: string): DiffStats | null {
void queryClient.invalidateQueries({ queryKey });
}, [queryClient, queryKey]);

useWorkspaceEvent("git:changed", workspaceId, invalidate);

return useMemo<DiffStats | null>(() => {
if (!status) return null;

const byPath = new Map<string, { additions: number; deletions: number }>();
for (const file of status.againstBase) byPath.set(file.path, file);
for (const file of status.staged) byPath.set(file.path, file);
for (const file of status.unstaged) byPath.set(file.path, file);
useWorkspaceEvent("git:changed", workspaceId, invalidate, enabled);

let additions = 0;
let deletions = 0;
for (const file of byPath.values()) {
additions += file.additions;
deletions += file.deletions;
}
return { additions, deletions };
}, [status]);
return stats ?? null;
}
33 changes: 6 additions & 27 deletions apps/desktop/src/renderer/lib/terminal/terminal-addons.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,33 @@
import { ClipboardAddon } from "@xterm/addon-clipboard";
import { ImageAddon } from "@xterm/addon-image";
import { LigaturesAddon } from "@xterm/addon-ligatures";
import { ProgressAddon } from "@xterm/addon-progress";
import { SearchAddon } from "@xterm/addon-search";
import { Unicode11Addon } from "@xterm/addon-unicode11";
import { WebglAddon } from "@xterm/addon-webgl";
import type { Terminal as XTerm } from "@xterm/xterm";
import { createTerminalImageAddon } from "./terminal-image-addon";
import { scheduleWebglAddon } from "./terminal-webgl-addon";

export interface LoadAddonsResult {
searchAddon: SearchAddon;
progressAddon: ProgressAddon;
dispose: () => void;
}

// Once WebGL fails, skip it for all subsequent runtimes (VS Code pattern).
let suggestedRendererType: "webgl" | "dom" | undefined;

/**
* Load optional addons onto an already-opened terminal. Returns a cleanup
* function and addon instances. WebGL is deferred to rAF to avoid
* racing with xterm's post-open viewport sync.
*/
export function loadAddons(terminal: XTerm): LoadAddonsResult {
let disposed = false;
let webglAddon: WebglAddon | null = null;

terminal.loadAddon(new ClipboardAddon());

const unicode11 = new Unicode11Addon();
terminal.loadAddon(unicode11);
terminal.unicode.activeVersion = "11";

terminal.loadAddon(new ImageAddon());
terminal.loadAddon(createTerminalImageAddon());

const searchAddon = new SearchAddon();
terminal.loadAddon(searchAddon);
Expand All @@ -43,33 +39,16 @@ export function loadAddons(terminal: XTerm): LoadAddonsResult {
terminal.loadAddon(new LigaturesAddon());
} catch {}

const rafId = requestAnimationFrame(() => {
if (disposed || suggestedRendererType === "dom") return;

try {
webglAddon = new WebglAddon();
webglAddon.onContextLoss(() => {
webglAddon?.dispose();
webglAddon = null;
terminal.refresh(0, terminal.rows - 1);
});
terminal.loadAddon(webglAddon);
} catch {
suggestedRendererType = "dom";
webglAddon = null;
}
const disposeWebglAddon = scheduleWebglAddon(terminal, {
isDisposed: () => disposed,
});

return {
searchAddon,
progressAddon,
dispose: () => {
disposed = true;
cancelAnimationFrame(rafId);
try {
webglAddon?.dispose();
} catch {}
webglAddon = null;
disposeWebglAddon();
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, it, mock } from "bun:test";

const imageAddonOptions: unknown[] = [];

class FakeImageAddon {
constructor(options: unknown) {
imageAddonOptions.push(options);
}
}

mock.module("@xterm/addon-image", () => ({
ImageAddon: FakeImageAddon,
}));

const { createTerminalImageAddon, TERMINAL_IMAGE_ADDON_OPTIONS } = await import(
"./terminal-image-addon"
);

describe("createTerminalImageAddon", () => {
it("bounds per-terminal image decoder memory", () => {
imageAddonOptions.length = 0;

const addon = createTerminalImageAddon();

expect(addon).toBeInstanceOf(FakeImageAddon);
expect(imageAddonOptions).toEqual([TERMINAL_IMAGE_ADDON_OPTIONS]);
expect(TERMINAL_IMAGE_ADDON_OPTIONS).toMatchObject({
iipSupport: true,
kittySupport: true,
pixelLimit: 1_048_576,
sixelSupport: false,
storageLimit: 16,
});
});
});
17 changes: 17 additions & 0 deletions apps/desktop/src/renderer/lib/terminal/terminal-image-addon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { type IImageAddonOptions, ImageAddon } from "@xterm/addon-image";

export const TERMINAL_IMAGE_ADDON_OPTIONS = {
enableSizeReports: true,
iipSizeLimit: 8_000_000,
iipSupport: true,
kittySizeLimit: 8_000_000,
kittySupport: true,
pixelLimit: 1_048_576,
showPlaceholder: true,
sixelSupport: false,
storageLimit: 16,
} satisfies IImageAddonOptions;

export function createTerminalImageAddon(): ImageAddon {
return new ImageAddon(TERMINAL_IMAGE_ADDON_OPTIONS);
}
140 changes: 140 additions & 0 deletions apps/desktop/src/renderer/lib/terminal/terminal-webgl-addon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { WebglAddon } from "@xterm/addon-webgl";
import type { Terminal as XTerm } from "@xterm/xterm";

type Disposable = { dispose: () => void };

const ATLAS_GUARD_MIN_PAGE_SIZE = 2048;

// Once WebGL fails, skip it for all subsequent runtimes in this renderer.
let suggestedRendererType: "webgl" | "dom" | undefined;

function getObjectProperty(source: unknown, key: string): unknown {
if (!source || (typeof source !== "object" && typeof source !== "function")) {
return undefined;
}
return (source as Record<string, unknown>)[key];
}

function getNumberProperty(source: unknown, key: string): number | null {
const value = getObjectProperty(source, key);
return typeof value === "number" ? value : null;
}

function getBooleanProperty(source: unknown, key: string): boolean | null {
const value = getObjectProperty(source, key);
return typeof value === "boolean" ? value : null;
}

function getTerminalRenderer(terminal: XTerm): unknown {
const core = getObjectProperty(terminal, "_core");
const renderService = getObjectProperty(core, "_renderService");
const rendererHolder = getObjectProperty(renderService, "_renderer");
return getObjectProperty(rendererHolder, "value") ?? rendererHolder;
}

function shouldClearTextureAtlas(terminal: XTerm): boolean {
const renderer = getTerminalRenderer(terminal);
const charAtlas = getObjectProperty(renderer, "_charAtlas");
const pendingAtlasClear =
getBooleanProperty(charAtlas, "_requestClearModel") === true;
const rawPages = getObjectProperty(charAtlas, "pages");
if (!Array.isArray(rawPages)) return false;

const pageSizes = rawPages
.map((page) =>
getNumberProperty(getObjectProperty(page, "canvas"), "width"),
)
.filter((size): size is number => size !== null);

return (
pendingAtlasClear ||
pageSizes.some((size) => size >= ATLAS_GUARD_MIN_PAGE_SIZE)
);
}

function refreshTerminal(terminal: XTerm): void {
terminal.refresh(0, Math.max(0, terminal.rows - 1));
}

export function scheduleWebglAddon(
terminal: XTerm,
options: { isDisposed?: () => boolean } = {},
): () => void {
let disposed = false;
let webglAddon: WebglAddon | null = null;
let loadRafId: number | null = null;
let clearRafId: number | null = null;
const disposables: Disposable[] = [];

const isDisposed = () => disposed || (options.isDisposed?.() ?? false);

const cleanupWebgl = () => {
while (disposables.length > 0) {
try {
disposables.pop()?.dispose();
} catch {}
}
try {
webglAddon?.dispose();
} catch {}
webglAddon = null;
};

const clearAtlasIfNeeded = () => {
clearRafId = null;
if (isDisposed() || !webglAddon) return;
if (!shouldClearTextureAtlas(terminal)) return;

try {
webglAddon.clearTextureAtlas();
refreshTerminal(terminal);
requestAnimationFrame(() => {
if (!isDisposed()) refreshTerminal(terminal);
});
} catch {}
};

const scheduleAtlasClear = () => {
if (isDisposed() || clearRafId !== null) return;
clearRafId = requestAnimationFrame(clearAtlasIfNeeded);
};

loadRafId = requestAnimationFrame(() => {
loadRafId = null;
if (isDisposed() || suggestedRendererType === "dom") return;

try {
webglAddon = new WebglAddon();
disposables.push(
webglAddon.onContextLoss(() => {
suggestedRendererType = "dom";
cleanupWebgl();
refreshTerminal(terminal);
requestAnimationFrame(() => {
if (!isDisposed()) refreshTerminal(terminal);
});
}),
webglAddon.onAddTextureAtlasCanvas(scheduleAtlasClear),
webglAddon.onRemoveTextureAtlasCanvas(scheduleAtlasClear),
webglAddon.onChangeTextureAtlas(scheduleAtlasClear),
);
terminal.loadAddon(webglAddon);
} catch {
suggestedRendererType = "dom";
cleanupWebgl();
}
});

return () => {
disposed = true;
if (loadRafId !== null) {
cancelAnimationFrame(loadRafId);
loadRafId = null;
}
if (clearRafId !== null) {
cancelAnimationFrame(clearRafId);
clearRafId = null;
}
cleanupWebgl();
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function DashboardSidebarHoverCardOverlay({
virtualRef.current = anchorElement;

const open = hoveredId !== null && payload !== null && !contextMenuOpen;
const diffStats = useDiffStats(hoveredId ?? "");
const diffStats = useDiffStats(hoveredId ?? "", { enabled: open });
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Gating useDiffStats by open can leave hover-card diff stats stale after reopening, because updates are event-driven and the query cache is never considered stale.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarHoverCardOverlay/DashboardSidebarHoverCardOverlay.tsx, line 30:

<comment>Gating `useDiffStats` by `open` can leave hover-card diff stats stale after reopening, because updates are event-driven and the query cache is never considered stale.</comment>

<file context>
@@ -27,7 +27,7 @@ export function DashboardSidebarHoverCardOverlay({
 
 	const open = hoveredId !== null && payload !== null && !contextMenuOpen;
-	const diffStats = useDiffStats(hoveredId ?? "");
+	const diffStats = useDiffStats(hoveredId ?? "", { enabled: open });
 
 	// Suppress the transform transition until Radix has placed the popover at
</file context>


// Suppress the transform transition until Radix has placed the popover at
// its real anchor — otherwise the initial jump from the off-screen measuring
Expand Down
Loading
Loading