diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs
index 09db16700..e516b1f3d 100644
--- a/crates/ide-core/src/workflow_settings.rs
+++ b/crates/ide-core/src/workflow_settings.rs
@@ -460,6 +460,8 @@ pub struct TerminalSettings {
/// `block` | `underline` | `bar`.
pub cursor_shape: String,
pub cursor_blink: bool,
+ /// Cap PTY→xterm paint rate: `unlimited` | `60` | `30` | `15` | `10`.
+ pub max_fps: String,
pub use_editor_font: bool,
pub font_family: String,
pub font_size: f32,
@@ -491,6 +493,7 @@ impl Default for TerminalSettings {
escape_to_editor: false,
cursor_shape: "block".into(),
cursor_blink: true,
+ max_fps: "unlimited".into(),
use_editor_font: true,
font_family: "JetBrains Mono".into(),
font_size: 13.0,
diff --git a/src/bindings.ts b/src/bindings.ts
index b3d5ec696..b4671dec4 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -11422,6 +11422,8 @@ export type TerminalSettings = {
/** `block` | `underline` | `bar`. */
cursorShape?: string,
cursorBlink?: boolean,
+ /** Cap PTY→xterm paint rate: `unlimited` | `60` | `30` | `15` | `10`. */
+ maxFps?: string,
useEditorFont?: boolean,
fontFamily?: string,
fontSize?: number | null,
diff --git a/src/features/settings/pages/tools.tsx b/src/features/settings/pages/tools.tsx
index 2087b9b94..a0fd06474 100644
--- a/src/features/settings/pages/tools.tsx
+++ b/src/features/settings/pages/tools.tsx
@@ -16,7 +16,7 @@ import {
type ExternalToolValid,
} from "@/platform/workflowSettings";
import { Button, Checkbox, IconButton, Input, Menu, type SelectOption, T } from "@/ui";
-import { NumberInput, Row, SearchLabel, Section, Select } from "../components/Form";
+import { NumberInput, Row, SearchLabel, Section, Select, SettingSelect } from "../components/Form";
import { useLabelMatch, useSetting } from "../components/context";
import { selectPage, setQuery } from "../model/staging";
import { MCP_SERVER_PAGE } from "./mcpServer";
@@ -24,6 +24,7 @@ import type { PageSpec } from "./spec";
import { BoundToggle, Grid, Indented, PageLink, TableEditor } from "./workflowControls";
import styles from "./Workflow.module.css";
import { tx } from "@/platform/i18n";
+import { TERMINAL_MAX_FPS_OPTIONS } from "@/platform/workflowSettings";
export const TOOLS_GROUP = "Tools";
@@ -244,6 +245,12 @@ function TerminalOptions() {
{isMac && }
+
>
}
/>
@@ -607,6 +614,7 @@ export const TOOLS_PAGES: PageSpec[] = [
"Use Option as Meta key",
"Move focus to the Editor with Escape",
"Configure terminal keybindings",
+ "Maximum refresh rate",
],
component: TerminalOptions,
},
diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts
index daa5ef9d9..af5b90faf 100644
--- a/src/features/terminal/index.ts
+++ b/src/features/terminal/index.ts
@@ -21,6 +21,7 @@ import { CLI_KIND, CliDoneMark, cliData, moveTerminalToEditor } from "./cli";
import { installTerminalKeys } from "./keys";
import { loadTerminalRuntime, terminalRuntime } from "./loader";
import { SAMPLE_TUI_END, SAMPLE_TUI_START, sampleTuiFrame } from "./sampleTui";
+import { notifyTerminalVisibility } from "./outputGate";
import type { SessionOptions } from "./session";
const WINDOW = "terminal";
@@ -333,6 +334,12 @@ export function activate(): () => void {
const rt = terminalRuntime();
(rt?.sessionForTerminalId(e.terminal) ?? rt?.cliSessionForTerminalId(e.terminal))?.exited(e.code);
}),
+ (() => {
+ if (typeof document === "undefined") return () => {};
+ const onVisibility = () => notifyTerminalVisibility();
+ document.addEventListener("visibilitychange", onVisibility);
+ return () => document.removeEventListener("visibilitychange", onVisibility);
+ })(),
// Sessions belong to the project. Remember this project's tabs, then open the next one's.
useProject.subscribe((s, prev) => {
const rt = terminalRuntime();
diff --git a/src/features/terminal/outputGate.test.ts b/src/features/terminal/outputGate.test.ts
new file mode 100644
index 000000000..30295e4da
--- /dev/null
+++ b/src/features/terminal/outputGate.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from "vitest";
+import {
+ HIDDEN_FLUSH_MS,
+ OutputGate,
+ flushIntervalMs,
+ notifyTerminalVisibility,
+ type OutputGateClock,
+} from "./outputGate";
+
+function fakeClock() {
+ let now = 0;
+ const timers = new Map void; at: number }>();
+ let nextId = 1;
+ const clock: OutputGateClock = {
+ now: () => now,
+ setTimeout: (fn, ms) => {
+ const id = nextId++;
+ timers.set(id, { fn, at: now + ms });
+ return id;
+ },
+ clearTimeout: (id) => {
+ timers.delete(id);
+ },
+ };
+ return {
+ clock,
+ advance(ms: number) {
+ now += ms;
+ for (const [id, t] of [...timers.entries()]) {
+ if (t.at <= now) {
+ timers.delete(id);
+ t.fn();
+ }
+ }
+ },
+ };
+}
+
+describe("flushIntervalMs", () => {
+ it("maps presets and forces a floor while hidden", () => {
+ expect(flushIntervalMs("unlimited", false)).toBe(0);
+ expect(flushIntervalMs("60", false)).toBe(17);
+ expect(flushIntervalMs("30", false)).toBe(33);
+ expect(flushIntervalMs("10", false)).toBe(100);
+ expect(flushIntervalMs("unlimited", true)).toBe(HIDDEN_FLUSH_MS);
+ expect(flushIntervalMs("60", true)).toBe(HIDDEN_FLUSH_MS);
+ });
+});
+
+describe("OutputGate", () => {
+ it("writes immediately when unlimited and visible", () => {
+ const writes: string[] = [];
+ const { clock } = fakeClock();
+ const gate = new OutputGate({
+ maxFps: () => "unlimited",
+ hidden: () => false,
+ write: (d) => writes.push(d),
+ clock,
+ });
+ gate.push("a");
+ gate.push("b");
+ expect(writes).toEqual(["a", "b"]);
+ gate.dispose();
+ });
+
+ it("coalesces chunks until the interval elapses", () => {
+ const writes: string[] = [];
+ const { clock, advance } = fakeClock();
+ const gate = new OutputGate({
+ maxFps: () => "10",
+ hidden: () => false,
+ write: (d) => writes.push(d),
+ clock,
+ });
+ gate.push("a");
+ gate.push("b");
+ expect(writes).toEqual([]);
+ advance(100);
+ expect(writes).toEqual(["ab"]);
+ gate.push("c");
+ advance(50);
+ expect(writes).toEqual(["ab"]);
+ advance(50);
+ expect(writes).toEqual(["ab", "c"]);
+ gate.dispose();
+ });
+
+ it("uses the hidden interval and flushes when becoming visible", () => {
+ const writes: string[] = [];
+ let hidden = true;
+ const { clock, advance } = fakeClock();
+ const gate = new OutputGate({
+ maxFps: () => "60",
+ hidden: () => hidden,
+ write: (d) => writes.push(d),
+ clock,
+ });
+ gate.push("x");
+ expect(writes).toEqual([]);
+ advance(100);
+ expect(writes).toEqual([]);
+ advance(HIDDEN_FLUSH_MS - 100);
+ expect(writes).toEqual(["x"]);
+
+ gate.push("y");
+ hidden = false;
+ notifyTerminalVisibility();
+ expect(writes).toEqual(["x", "y"]);
+ gate.dispose();
+ });
+
+ it("clear drops buffered output without writing", () => {
+ const writes: string[] = [];
+ const { clock } = fakeClock();
+ const gate = new OutputGate({
+ maxFps: () => "10",
+ hidden: () => false,
+ write: (d) => writes.push(d),
+ clock,
+ });
+ gate.push("z");
+ gate.clear();
+ expect(writes).toEqual([]);
+ expect(gate.buffered).toBe("");
+ gate.dispose();
+ });
+});
diff --git a/src/features/terminal/outputGate.ts b/src/features/terminal/outputGate.ts
new file mode 100644
index 000000000..894efc16b
--- /dev/null
+++ b/src/features/terminal/outputGate.ts
@@ -0,0 +1,133 @@
+/**
+ * Coalesces PTY → xterm writes so fast output (btop, Claude animations) paints at a
+ * capped rate instead of every chunk. While the document is hidden the cap drops
+ * further — WebKitGTK still feeds IntersectionObserver-visible terminals on other
+ * virtual desktops, and unbounded `term.write` kept burning CPU there (#4216).
+ */
+
+import type { TerminalMaxFps } from "@/platform/workflowSettings";
+
+export type { TerminalMaxFps };
+
+/** When the page is hidden, paint at most this often (4 FPS). */
+export const HIDDEN_FLUSH_MS = 250;
+
+export function flushIntervalMs(maxFps: TerminalMaxFps, hidden: boolean): number {
+ if (hidden) return HIDDEN_FLUSH_MS;
+ if (maxFps === "unlimited") return 0;
+ const fps = Number(maxFps);
+ return fps > 0 ? Math.round(1000 / fps) : 0;
+}
+
+export type OutputGateClock = {
+ now: () => number;
+ setTimeout: (fn: () => void, ms: number) => number;
+ clearTimeout: (id: number) => void;
+};
+
+const browserClock: OutputGateClock = {
+ now: () => performance.now(),
+ setTimeout: (fn, ms) => window.setTimeout(fn, ms) as unknown as number,
+ clearTimeout: (id) => window.clearTimeout(id),
+};
+
+export type OutputGateOptions = {
+ /** Current max FPS setting. */
+ maxFps: () => TerminalMaxFps;
+ /** Whether the document is hidden. */
+ hidden: () => boolean;
+ /** Deliver coalesced output to xterm. */
+ write: (data: string) => void;
+ clock?: OutputGateClock;
+};
+
+const visibilityListeners = new Set<() => void>();
+
+/** Register a session's gate for `document.visibilitychange` (keeps index off the xterm path). */
+export function watchOutputVisibility(onChange: () => void): () => void {
+ visibilityListeners.add(onChange);
+ return () => {
+ visibilityListeners.delete(onChange);
+ };
+}
+
+/** `visibilitychange`: flush or reschedule every live terminal output gate. */
+export function notifyTerminalVisibility() {
+ for (const listener of visibilityListeners) listener();
+}
+
+/** Buffers chunks and flushes them at the configured interval. */
+export class OutputGate {
+ private pending = "";
+ private timer: number | null = null;
+ private lastFlush = 0;
+ private readonly clock: OutputGateClock;
+ private readonly unwatch: () => void;
+
+ constructor(private readonly opts: OutputGateOptions) {
+ this.clock = opts.clock ?? browserClock;
+ this.unwatch = watchOutputVisibility(() => this.onVisibilityChange());
+ }
+
+ push(chunk: string) {
+ if (!chunk) return;
+ this.pending += chunk;
+ this.schedule();
+ }
+
+ /** Force a flush (becoming visible again, dispose). */
+ flush() {
+ this.cancelTimer();
+ if (!this.pending) return;
+ const data = this.pending;
+ this.pending = "";
+ this.lastFlush = this.clock.now();
+ this.opts.write(data);
+ }
+
+ /** Drop buffered output without writing (restart / dispose after kill). */
+ clear() {
+ this.cancelTimer();
+ this.pending = "";
+ }
+
+ dispose() {
+ this.unwatch();
+ this.flush();
+ }
+
+ /** `visibilitychange`: cancel a long hidden wait and flush / reschedule. */
+ onVisibilityChange() {
+ if (this.timer === null && !this.pending) return;
+ this.cancelTimer();
+ if (!this.opts.hidden()) {
+ this.flush();
+ return;
+ }
+ if (this.pending) this.schedule();
+ }
+
+ get buffered(): string {
+ return this.pending;
+ }
+
+ private schedule() {
+ if (this.timer !== null) return;
+ const interval = flushIntervalMs(this.opts.maxFps(), this.opts.hidden());
+ if (interval === 0) {
+ this.flush();
+ return;
+ }
+ const wait = Math.max(0, interval - (this.clock.now() - this.lastFlush));
+ this.timer = this.clock.setTimeout(() => {
+ this.timer = null;
+ this.flush();
+ }, wait);
+ }
+
+ private cancelTimer() {
+ if (this.timer === null) return;
+ this.clock.clearTimeout(this.timer);
+ this.timer = null;
+ }
+}
diff --git a/src/features/terminal/session.test.ts b/src/features/terminal/session.test.ts
index 3db2c8837..be8405e22 100644
--- a/src/features/terminal/session.test.ts
+++ b/src/features/terminal/session.test.ts
@@ -39,7 +39,6 @@ vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
onmessage: ((chunk: string) => void) | null = null;
},
}));
-
const fileLink = (text: string): Extract => {
const [l] = findTerminalLinks(text);
if (!l || l.kind !== "file") throw new Error(`not a file link: ${text}`);
diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts
index 28acf50bb..48a98e32a 100644
--- a/src/features/terminal/session.ts
+++ b/src/features/terminal/session.ts
@@ -16,6 +16,7 @@ import { tx } from "@/platform/i18n";
import { editorService, notifications, registerFontZoomSurface } from "@/workbench/contributions";
import { OutputActivity } from "./activity";
import { fitScheduler, settledResize } from "./fit";
+import { OutputGate, type TerminalMaxFps } from "./outputGate";
import { watchWindowsPty, windowsPtyOptions } from "./windowsPty";
import { installTerminalDrop } from "./drop";
import { installDomRowCache } from "./domRowCache";
@@ -261,6 +262,11 @@ export class TerminalSession {
/** Keystrokes typed while the PTY is still starting; sent as soon as it exists. */
private pendingInput = "";
private outputTail = "";
+ private readonly outputGate = new OutputGate({
+ maxFps: () => workflowSettings().terminal.maxFps as TerminalMaxFps,
+ hidden: () => typeof document !== "undefined" && document.hidden,
+ write: (data) => this.term.write(data),
+ });
private lastSize = { cols: 0, rows: 0 };
/** Per-tab font size offset (px) relative to `workflowSettings().terminal.fontSize`. */
private fontZoom = 0;
@@ -745,7 +751,7 @@ export class TerminalSession {
}
this.outputTail = output.slice(output.length - held);
output = output.slice(0, output.length - held);
- if (output) this.term.write(output);
+ if (output) this.outputGate.push(output);
}
private doFit() {
@@ -785,6 +791,7 @@ export class TerminalSession {
if (this.disposed || this.snapshot.status === "starting" || this.snapshot.status === "running") return;
const generation = ++this.generation;
this.outputTail = "";
+ this.outputGate.clear();
this.resetActivity();
const custom = this.opts.command;
this.update({
@@ -1044,6 +1051,7 @@ export class TerminalSession {
this.opts.command?.onExit?.(null, true);
this.fitter.cancel();
this.ptyResize.cancel();
+ this.outputGate.dispose();
if (this.activityTimer !== null) clearTimeout(this.activityTimer);
this.pendingInput = "";
this.resizeObserver?.disconnect();
diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json
index 6ceeab583..42b5cbddd 100644
--- a/src/platform/locales/text/en.json
+++ b/src/platform/locales/text/en.json
@@ -2525,5 +2525,12 @@
"Remember size for each tool window": "Remember size for each tool window",
"Off, the tool windows of one side share its size": "Off, the tool windows of one side share its size",
"The scope {scope} has more than {SCOPE_FILES_LIMIT} files; the Project view shows the first ones": "The scope {scope} has more than {SCOPE_FILES_LIMIT} files; the Project view shows the first ones",
- "Cannot show the scope {scope}": "Cannot show the scope {scope}"
+ "Cannot show the scope {scope}": "Cannot show the scope {scope}",
+ "Maximum refresh rate": "Maximum refresh rate",
+ "Caps how often fast terminal output is painted. Hidden windows always paint more slowly.": "Caps how often fast terminal output is painted. Hidden windows always paint more slowly.",
+ "Unlimited": "Unlimited",
+ "60 FPS": "60 FPS",
+ "30 FPS": "30 FPS",
+ "15 FPS": "15 FPS",
+ "10 FPS": "10 FPS"
}
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index 37c175167..c51b3ba2f 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -8898,5 +8898,12 @@
"Remember size for each tool window": "记住每个工具窗口的大小",
"Off, the tool windows of one side share its size": "关闭时,同一侧的工具窗口共用一个大小",
"The scope {scope} has more than {SCOPE_FILES_LIMIT} files; the Project view shows the first ones": "作用域 {scope} 中的文件超过 {SCOPE_FILES_LIMIT} 个,项目视图只显示前面的部分",
- "Cannot show the scope {scope}": "无法显示作用域 {scope}"
+ "Cannot show the scope {scope}": "无法显示作用域 {scope}",
+ "Maximum refresh rate": "最大刷新率",
+ "Caps how often fast terminal output is painted. Hidden windows always paint more slowly.": "限制快速终端输出的绘制频率。隐藏的窗口总会更慢地绘制。",
+ "Unlimited": "不限制",
+ "60 FPS": "60 FPS",
+ "30 FPS": "30 FPS",
+ "15 FPS": "15 FPS",
+ "10 FPS": "10 FPS"
}
diff --git a/src/platform/workflowSettings.ts b/src/platform/workflowSettings.ts
index 80612e3ec..ffbb4dc19 100644
--- a/src/platform/workflowSettings.ts
+++ b/src/platform/workflowSettings.ts
@@ -138,6 +138,16 @@ export interface ExternalDiffValid {
parameters: string;
}
+export type TerminalMaxFps = "unlimited" | "60" | "30" | "15" | "10";
+
+export const TERMINAL_MAX_FPS_OPTIONS: readonly { value: TerminalMaxFps; label: string }[] = [
+ { value: "unlimited", label: "Unlimited" },
+ { value: "60", label: "60 FPS" },
+ { value: "30", label: "30 FPS" },
+ { value: "15", label: "15 FPS" },
+ { value: "10", label: "10 FPS" },
+];
+
export interface TerminalSettingsValid {
startDirectory: string;
env: Record;
@@ -156,6 +166,11 @@ export interface TerminalSettingsValid {
escapeToEditor: boolean;
cursorShape: CursorShape;
cursorBlink: boolean;
+ /**
+ * Cap how often PTY output is painted. `unlimited` writes every chunk;
+ * while the document is hidden a slower floor always applies (#4216).
+ */
+ maxFps: TerminalMaxFps;
useEditorFont: boolean;
fontFamily: string;
fontSize: number;
@@ -357,6 +372,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
escapeToEditor: false,
cursorShape: "block",
cursorBlink: true,
+ maxFps: "unlimited",
useEditorFont: true,
fontFamily: "JetBrains Mono",
fontSize: 13,
@@ -564,6 +580,7 @@ export function validateTerminal(raw: unknown): TerminalSettingsValid {
escapeToEditor: bool(v.escapeToEditor, d.escapeToEditor),
cursorShape: oneOf(v.cursorShape, ["block", "underline", "bar"] as const, d.cursorShape),
cursorBlink: bool(v.cursorBlink, d.cursorBlink),
+ maxFps: oneOf(v.maxFps, ["unlimited", "60", "30", "15", "10"] as const, d.maxFps),
useEditorFont: bool(v.useEditorFont, d.useEditorFont),
fontFamily: nonEmpty(v.fontFamily, d.fontFamily),
fontSize: num(v.fontSize, d.fontSize, WORKFLOW_LIMITS.terminalFontSize),