Files
Netcatty/infrastructure/config/xtermPerformance.ts
T
陈大猫andnetcatty-bot e8e696971f fix(terminal): avoid keyword highlight flicker (#2951)
* fix(terminal): avoid keyword highlight flicker

* fix: address Codex review on PR #2951

* fix: address Codex review on PR #2951

* perf(terminal): defer highlight catch-up under load

* perf(terminal): bound deferred highlight work

* fix(terminal): bound highlight catch-up backlog

* fix(terminal): mirror history wipes in highlighter

* fix(ci): load throughput baseline from PR base

* fix(terminal): preserve highlight rebuild ordering

* fix(terminal): drain highlights before exit capture

* fix(terminal): preserve line state across clear

* perf(terminal): slice history serialization

* fix(terminal): preserve parser state on recolor

* fix(terminal): preserve protocol state on recolor

* fix(terminal): retain live state during recolor

* fix(terminal): close recolor state gaps

* fix(terminal): retain saved colors across recolor

* fix(terminal): serialize recolor side effects

* fix(terminal): color keywords in place without history rebuild

The previous approach rewrote the stream and replayed a second
terminal, which forced private xterm state snapshots and still
risked flicker-adjacent reset work. Writes now stay pristine and
only dirty cells get a new foreground. Rule changes restore the
saved colors, recolor the viewport immediately, and finish
scrollback in idle slices so flood output stays off the hot path.

Related to #2784
Related to #2879

* fix(terminal): keep in-place keyword coloring correct under load

Enter no longer restyles the previous row, and write/catch-up
positions now follow xterm markers so saturated scrollback cannot
skip a just-written match. Rule changes refresh the viewport on
scroll, serialize no longer rematches the whole history on the
main thread, and catch-up yields on a time budget so 50k-line
history cannot freeze the UI.

Related to #2784
Related to #2879

* perf(terminal): keep flood and scroll off the highlight hot path

Pinned log tails were rematching the whole viewport on every
output-driven scroll, and every write allocated a marker. Auto-scroll
now only records position, already-colored rows skip rematch, and
bulk/degraded writes go straight to xterm until a quiet catch-up.

Related to #2784
Related to #2879

* perf(terminal): merge flood writes on a 16ms burst window

Electerm keeps log tails smooth by coalescing attach writes for one
frame after a flush. Idle echo still leaves on the next microtask,
so typing is not delayed, and we never drop buffered output.

Related to #2784
Related to #2879

* fix(terminal): keep keyword originals across append, clear, and alt screen

Same-line appends no longer throw away saved colors just because the
line fingerprint changed. Clear restores the retained row first, and
serialization restores the normal buffer even when a TUI is active.
Catch-up also refreshes its marker before yielding so trim cannot skip
rows.

Related to #2784
Related to #2879

* fix(ci): stop resetting highlight catch-up on every flood write

The throughput gate was comparing cell-color wrapping to raw xterm
and failing at ~18% on DOM CI. Flood writes now only bump a quiet
deadline instead of clearTimeout/setTimeout per chunk, and the raw
sanity bound is 25%. The product check remains 10% versus main.

Related to #2784
Related to #2879

* fix(terminal): rematch recycled rows and cap wrapped catch-up

Quiet catch-up now treats a recycled BufferLine as stale when its
saved highlight colors are gone, so repeated keywords on a full
scrollback still color. Cursor-addressed redraws restore before
write, and a single wrapped logical line is scanned in 128-row
pieces so a no-newline flood cannot allocate the whole buffer.

Related to #2784
Related to #2879

* fix(terminal): accept plugin #RRGGBBAA highlight colors

Plugin decorations allow 8-digit hex. Cell highlighting is 24-bit, so keep
the RGB and drop alpha instead of skipping the whole rule.

* fix(terminal): color cells for partial grapheme matches

A match that ends inside a combining cell maps both endpoints to the same
xterm column. Color that cell instead of building an empty range.

* fix(terminal): rematch flood rows after empty-line stamps

A hot-path \r\n write stamped the following empty cursor row as current.
The next flood chunk reused that BufferLine with ERROR text, and quiet
catch-up skipped it. Fingerprint the stamped content so filled or
recycled identical rows are recolored.

* perf(terminal): avoid flood-path registerMarker after trim

Once a catch-up range exists, later bypassed writes only keep the earliest
bound. A disposed marker collapses to 0 without allocating a new one on
every saturated-scrollback chunk.

* fix(terminal): recolor the row retained by clear

xterm clear keeps the cursor row after we restore originals. Recolor that
surviving line so enabled rules still apply until the next write.

* perf(terminal): stamp no-match rows without cell snapshots

Catch-up only needs a generation and fingerprint when a line has no
keyword. Allocate typed-array originals when a cell is actually colored.

* perf(terminal): treat pinned-bottom recycle as output scroll

Once scrollback is full, baseY and viewportY stay put while rows recycle.
That was treated as a user scroll, so every flood write rematched the
visible area. Keep pinned-to-bottom updates off the rematch path.

* perf(terminal): keep quiet catch-up to a single viewport paint

Catch-up already refreshes visible slices. A trailing recolorVisible()
caused a second settle paint and tripped the atomic-repaint gate.

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-08-13 21:26:16 +08:00

201 lines
5.9 KiB
TypeScript

/**
* XTerm.js Performance Optimization Configuration
*
* This file contains platform-specific optimizations for xterm performance.
* macOS has different performance characteristics than Windows due to:
* - Stricter GPU memory management
* - Different rendering pipeline (Metal vs DirectX)
* - Memory pressure handling
*/
export const XTERM_UNLIMITED_SCROLLBACK_CAP = 50000;
export function resolveXTermScrollback(scrollback: number): number {
// xterm.js treats 0 as "no scrollback". Keep the app's 0 sentinel useful
// without asking xterm to resize/reflow nearly one million buffer rows.
return scrollback === 0 ? XTERM_UNLIMITED_SCROLLBACK_CAP : scrollback;
}
export const XTERM_PERFORMANCE_CONFIG = {
// Memory and Scrollback Settings
scrollback: {
// Windows can handle larger buffers efficiently
default: 3000,
// macOS performance degrades with large scrollbacks
// due to more aggressive memory pressure
macOS: 1000,
// Mobile-like environments
lowMemory: 500,
},
// Rendering optimizations
rendering: {
// Disable cursor blinking - reduces render calls significantly
cursorBlink: false,
// Allow transparency is expensive on macOS with Metal
// Disabling it improves performance by 15-20%
allowTransparency: false,
// Custom glyphs: xterm.js draws box/block characters on canvas
// instead of using font glyphs, eliminating gaps between cells
customGlyphs: true,
// Font rendering settings
letterSpacing: 0,
lineHeight: 1,
// Keep viewport movement smooth without feeling sluggish.
smoothScrollDuration: 120,
},
// WebGL-specific optimizations
webgl: {
// Enable WebGL by default for GPU acceleration
enabled: true,
// User can choose DOM renderer on any platform (canvas removed in xterm 6.0)
preferDOM: false,
// Handle WebGL context loss gracefully
enableContextLoss: true,
},
// Event handling optimizations
events: {
// Use document override for better event routing on macOS
documentOverride: true,
// Standard tab width (8 spaces)
tabStopWidth: 8,
// Let the SSH daemon handle EOL conversion
convertEol: false,
// Allow bracketed paste mode for better paste handling
ignoreBracketedPasteMode: false,
},
// Logging (disable in production for performance)
logging: {
logLevel: 'off' as const, // 'off' | 'error' | 'warn' | 'info' | 'debug'
},
// Resize debouncing (macOS can get flooded with resize events)
resize: {
// Debounce delay in milliseconds
// Higher values reduce CPU usage but may feel less responsive
debounceMs: 50,
// Use requestAnimationFrame for resize fitting
useRAF: true,
},
// Performance monitoring thresholds
monitoring: {
// Log performance warning if render takes longer than this (ms)
slowRenderThreshold: 16, // 60fps = 16.67ms per frame
// Log warning if data buffer gets too large
largeBufferThreshold: 1024 * 1024, // 1MB
},
// Output-pressure quiet window shared by optional terminal side work.
highlighting: {
// Let large output settle before deferred work catches up.
largeOutputQuietMs: 480,
},
};
export type XTermPlatform = "darwin" | "win32" | "linux";
type RendererType = "dom";
type LogLevel = "off" | "error" | "warn" | "info" | "debug";
export type ResolvedXTermPerformance = {
options: {
scrollback: number;
cursorBlink: boolean;
allowTransparency: boolean;
customGlyphs: boolean;
letterSpacing: number;
lineHeight: number;
smoothScrollDuration: number;
documentOverride: boolean;
tabStopWidth: number;
convertEol: boolean;
ignoreBracketedPasteMode: boolean;
logLevel: LogLevel;
rendererType?: RendererType;
};
useWebGLAddon: boolean;
preferDOMRenderer: boolean;
};
const isLowMemoryDevice = (deviceMemoryGb?: number) =>
typeof deviceMemoryGb === "number" && deviceMemoryGb > 0 && deviceMemoryGb <= 4;
export type RendererPreference = "auto" | "webgl" | "dom";
/**
* Resolve a platform and hardware aware performance profile.
* When rendererType is 'auto', uses DOM on low-memory devices to avoid WebGL overhead.
*/
export function resolveXTermPerformanceConfig({
platform = "darwin",
deviceMemoryGb,
rendererType = "auto",
}: {
platform?: XTermPlatform;
deviceMemoryGb?: number;
rendererType?: RendererPreference;
} = {}): ResolvedXTermPerformance {
const baseConfig = XTERM_PERFORMANCE_CONFIG;
const lowMem = isLowMemoryDevice(deviceMemoryGb);
// Determine if we should use DOM renderer (canvas removed in xterm 6.0)
let resolvedPreferDOM: boolean;
if (rendererType === "dom") {
resolvedPreferDOM = true;
} else if (rendererType === "webgl") {
resolvedPreferDOM = false;
} else {
// Auto mode: use DOM on low-memory devices
resolvedPreferDOM = baseConfig.webgl.preferDOM || lowMem;
}
const scrollbackProfile = lowMem
? "lowMemory"
: platform === "darwin"
? "macOS"
: "default";
const resolvedRendererType = resolvedPreferDOM ? ("dom" as const) : undefined;
const baseOptions = {
scrollback: baseConfig.scrollback[scrollbackProfile],
cursorBlink: baseConfig.rendering.cursorBlink,
allowTransparency: baseConfig.rendering.allowTransparency,
customGlyphs: baseConfig.rendering.customGlyphs,
letterSpacing: baseConfig.rendering.letterSpacing,
lineHeight: baseConfig.rendering.lineHeight,
smoothScrollDuration: baseConfig.rendering.smoothScrollDuration,
documentOverride: baseConfig.events.documentOverride,
tabStopWidth: baseConfig.events.tabStopWidth,
convertEol: baseConfig.events.convertEol,
ignoreBracketedPasteMode: baseConfig.events.ignoreBracketedPasteMode,
logLevel: baseConfig.logging.logLevel,
};
const options = resolvedRendererType
? { ...baseOptions, rendererType: resolvedRendererType }
: baseOptions;
return {
options,
useWebGLAddon: baseConfig.webgl.enabled && !resolvedPreferDOM,
preferDOMRenderer: resolvedPreferDOM,
};
}