Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

perf(terminal): skip DOM work for rows whose markup did not change (#2239)

Bruno Bellonic5c5930a7509
diff --git a/src/features/terminal/domRowCache.test.ts b/src/features/terminal/domRowCache.test.ts
new file mode 100644
index 000000000..41acac5f0
--- /dev/null
+++ b/src/features/terminal/domRowCache.test.ts
@@ -0,0 +1,120 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import type { Terminal } from "@xterm/xterm";
+import { installDomRowCache } from "./domRowCache";
+
+/** Mirrors the shape of xterm 6's private DomRenderer closely enough for the cache. */
+function fakeRendererClass() {
+ return class FakeDomRenderer {
+ lines: string[];
+ _rowElements: HTMLElement[];
+ underlines = 0;
+ _bufferService = {
+ cols: 10,
+ buffer: { x: 0, y: 0, ybase: 0, ydisp: 0, lines: { get: (i: number) => this.lines[i] } },
+ };
+ _coreService = { decPrivateModes: {} };
+ _optionsService = { rawOptions: { cursorBlink: false, cursorStyle: "block", cursorInactiveStyle: "outline" } };
+ dimensions = { css: { cell: { width: 8 } } };
+ _widthCache = {};
+ _rowFactory = {
+ createRow: (line: string) =>
+ line.split(" ").map((word) => {
+ const span = document.createElement("span");
+ span.textContent = word;
+ return span;
+ }),
+ };
+
+ constructor(lines: string[]) {
+ this.lines = lines;
+ this._rowElements = lines.map(() => document.createElement("div"));
+ }
+
+ renderRows(start: number, end: number) {
+ for (let y = start; y <= end; y++) {
+ this._rowElements[y]?.replaceChildren(...this._rowFactory.createRow(this.lines[y] ?? ""));
+ }
+ }
+
+ clear() {
+ for (const row of this._rowElements) row.replaceChildren();
+ }
+
+ _setCellUnderline() {
+ this.underlines++;
+ for (const [y, row] of this._rowElements.entries()) {
+ row.replaceChildren(...this._rowFactory.createRow((this.lines[y] ?? "").toUpperCase()));
+ }
+ }
+ };
+}
+
+function rowAt(renderer: { _rowElements: HTMLElement[] }, y: number): HTMLElement {
+ const row = renderer._rowElements[y];
+ if (!row) throw new Error(`no row ${y}`);
+ return row;
+}
+
+function terminalWith(renderer: object | undefined): Terminal {
+ return { _core: { _renderService: { _renderer: { value: renderer } } } } as unknown as Terminal;
+}
+
+describe("installDomRowCache", () => {
+ it("leaves unchanged rows in place and replaces changed ones", () => {
+ const Renderer = fakeRendererClass();
+ const renderer = new Renderer(["a b", "c d"]);
+ installDomRowCache(terminalWith(renderer));
+
+ renderer.renderRows(0, 1);
+ const [first, second] = renderer._rowElements.map((row) => row.firstChild);
+ renderer.lines[1] = "c e";
+ renderer.renderRows(0, 1);
+
+ expect(rowAt(renderer, 0).firstChild).toBe(first);
+ expect(rowAt(renderer, 1).firstChild).not.toBe(second);
+ expect(rowAt(renderer, 1).textContent).toBe("ce");
+ });
+
+ it("re-renders rows after clear() and link underlines rebuilt them", () => {
+ const Renderer = fakeRendererClass();
+ const renderer = new Renderer(["a b"]);
+ installDomRowCache(terminalWith(renderer));
+ renderer.renderRows(0, 0);
+
+ renderer.clear();
+ renderer.renderRows(0, 0);
+ expect(rowAt(renderer, 0).textContent).toBe("ab");
+
+ renderer._setCellUnderline();
+ expect(renderer.underlines).toBe(1);
+ expect(rowAt(renderer, 0).textContent).toBe("AB");
+ renderer.renderRows(0, 0);
+ expect(rowAt(renderer, 0).textContent).toBe("ab");
+ });
+
+ it("installs once per renderer class", () => {
+ const Renderer = fakeRendererClass();
+ const a = new Renderer(["x"]);
+ installDomRowCache(terminalWith(a));
+ const patched = Renderer.prototype.renderRows;
+ installDomRowCache(terminalWith(new Renderer(["y"])));
+
+ expect(Renderer.prototype.renderRows).toBe(patched);
+ a._setCellUnderline();
+ expect(a.underlines).toBe(1);
+ });
+
+ it("does nothing before open() or when xterm's renderer no longer matches", () => {
+ expect(() => installDomRowCache(terminalWith(undefined))).not.toThrow();
+
+ class OtherRenderer {
+ renderRows() {}
+ clear() {}
+ _setCellUnderline() {}
+ }
+ const original = OtherRenderer.prototype.renderRows;
+ installDomRowCache(terminalWith(new OtherRenderer()));
+ expect(OtherRenderer.prototype.renderRows).toBe(original);
+ });
+});
diff --git a/src/features/terminal/domRowCache.ts b/src/features/terminal/domRowCache.ts
new file mode 100644
index 000000000..306358bc4
--- /dev/null
+++ b/src/features/terminal/domRowCache.ts
@@ -0,0 +1,124 @@
+/**
+ * Skips DOM work for terminal rows whose markup did not change.
+ *
+ * xterm's DOM renderer rebuilds every dirty row with `replaceChildren`, even when the
+ * new spans are identical. Full-screen TUIs (Grok, Claude Code, htop…) redraw the whole
+ * screen for each spinner tick, so WebKitGTK restyles, lays out and paints every row
+ * several times a second while only one or two actually changed; the window then falls
+ * behind on keystrokes. Rows are still built (cheap); only identical ones are left in place.
+ *
+ * Remove once xterm's DomRenderer does this itself (xterm 6.0.0 does not).
+ */
+import type { Terminal } from "@xterm/xterm";
+
+const MARKUP = Symbol("rowMarkup");
+
+type RowElement = HTMLElement & { [MARKUP]?: string };
+
+type BufferLine = unknown;
+
+/** The parts of xterm 6's private DomRenderer this relies on. */
+interface DomRenderer {
+ _rowElements: RowElement[];
+ _rowFactory: {
+ createRow(
+ line: BufferLine,
+ row: number,
+ isCursorRow: boolean,
+ cursorStyle: unknown,
+ cursorInactiveStyle: unknown,
+ cursorX: number,
+ cursorBlink: unknown,
+ cellWidth: number,
+ widthCache: unknown,
+ linkStart: number,
+ linkEnd: number,
+ ): HTMLElement[];
+ };
+ _bufferService: {
+ cols: number;
+ buffer: { x: number; y: number; ybase: number; ydisp: number; lines: { get(i: number): BufferLine | undefined } };
+ };
+ _coreService: { decPrivateModes: { cursorBlink?: boolean; cursorStyle?: unknown } };
+ _optionsService: { rawOptions: { cursorBlink?: boolean; cursorStyle?: unknown; cursorInactiveStyle?: unknown } };
+ dimensions: { css: { cell: { width: number } } };
+ _widthCache: unknown;
+ renderRows(start: number, end: number): void;
+ clear(): void;
+ _setCellUnderline(...args: unknown[]): void;
+}
+
+const installed = new WeakSet<object>();
+
+function forget(renderer: DomRenderer) {
+ for (const row of renderer._rowElements) row[MARKUP] = undefined;
+}
+
+/** True when `proto` still looks like the xterm 6.0.0 renderer this was written against. */
+function supported(proto: Partial<DomRenderer>): proto is DomRenderer {
+ const { renderRows, clear, _setCellUnderline } = proto;
+ if (typeof renderRows !== "function" || typeof clear !== "function" || typeof _setCellUnderline !== "function") {
+ return false;
+ }
+ const source = Function.prototype.toString.call(renderRows);
+ return source.includes("_rowFactory.createRow(") && source.includes("replaceChildren(");
+}
+
+/** Renders `start..end` like xterm's own `renderRows`, leaving unchanged rows alone. */
+function renderRows(this: DomRenderer, start: number, end: number) {
+ const buffer = this._bufferService.buffer;
+ const cursorY = buffer.ybase + buffer.y;
+ const cursorX = Math.min(buffer.x, this._bufferService.cols - 1);
+ const modes = this._coreService.decPrivateModes;
+ const options = this._optionsService.rawOptions;
+ const cursorBlink = modes.cursorBlink ?? options.cursorBlink;
+ const cursorStyle = modes.cursorStyle ?? options.cursorStyle;
+ for (let y = start; y <= end; y++) {
+ const row = y + buffer.ydisp;
+ const element = this._rowElements[y];
+ const line = buffer.lines.get(row);
+ if (!element || !line) break;
+ const spans = this._rowFactory.createRow(
+ line,
+ row,
+ row === cursorY,
+ cursorStyle,
+ options.cursorInactiveStyle,
+ cursorX,
+ cursorBlink,
+ this.dimensions.css.cell.width,
+ this._widthCache,
+ -1,
+ -1,
+ );
+ let markup = "";
+ for (const span of spans) markup += span.outerHTML;
+ if (element[MARKUP] === markup) continue;
+ element[MARKUP] = markup;
+ element.replaceChildren(...spans);
+ }
+}
+
+/**
+ * Installs the row cache on the renderer `term` uses. Idempotent; a no-op for the WebGL
+ * or canvas renderers, before `open()`, and on an xterm whose internals have changed.
+ */
+export function installDomRowCache(term: Terminal) {
+ const renderer = (term as unknown as { _core?: { _renderService?: { _renderer?: { value?: object } } } })._core
+ ?._renderService?._renderer?.value;
+ if (!renderer) return;
+ const proto = Object.getPrototypeOf(renderer) as Partial<DomRenderer>;
+ if (installed.has(proto) || !supported(proto)) return;
+ installed.add(proto);
+ const { clear, _setCellUnderline } = proto;
+ proto.renderRows = renderRows;
+ // Both rebuild rows without going through renderRows.
+ proto.clear = function (this: DomRenderer) {
+ forget(this);
+ clear.call(this);
+ };
+ proto._setCellUnderline = function (this: DomRenderer, ...args: unknown[]) {
+ forget(this);
+ _setCellUnderline.apply(this, args);
+ };
+}
diff --git a/src/features/terminal/embedded.ts b/src/features/terminal/embedded.ts
index 120dcddc4..3a841cb0a 100644
--- a/src/features/terminal/embedded.ts
+++ b/src/features/terminal/embedded.ts
@@ -5,6 +5,7 @@
* a terminal feeds its process).
*/
import { installTerminalDrop } from "./drop";
+import { installDomRowCache } from "./domRowCache";
import { installTerminalPaste } from "./paste";
import { ownTerminalInput } from "./imeInput";
import { Terminal, type IDisposable } from "@xterm/xterm";
@@ -104,6 +105,7 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal
const removePaste = installTerminalPaste(host, (text) => term.paste(text));
const removeDrop = installTerminalDrop(host, (text) => term.paste(text));
term.open(host);
+ installDomRowCache(term);
if (opts["aria-label"]) term.textarea?.setAttribute("aria-label", opts["aria-label"]);
// The same WKWebView input-method fixes as the terminal sessions.
if (term.textarea && usePlatform.getState().os === "macos") {
diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts
index ef334e5be..c98d2b9d0 100644
--- a/src/features/terminal/session.ts
+++ b/src/features/terminal/session.ts
@@ -14,6 +14,7 @@ import { editorService, notifications, registerFontZoomSurface } from "@/workben
import { fitScheduler, settledResize } from "./fit";
import { watchWindowsPty, windowsPty } from "./windowsPty";
import { installTerminalDrop } from "./drop";
+import { installDomRowCache } from "./domRowCache";
import { installTerminalPaste, pasteTerminalClipboard } from "./paste";
import { ImeCommitGate } from "./imeCommit";
import { ownTerminalInput } from "./imeInput";
@@ -451,6 +452,7 @@ export class TerminalSession {
// xterm's DOM renderer: the WebGL one rasterizes glyphs per background, so
// selected text rendered at a visibly different weight than the rest.
this.term.open(this.host);
+ installDomRowCache(this.term);
this.opened = true;
remeasureWhenFontsLoad(
this.term,