diff --git a/perf/budgets.json b/perf/budgets.json index 663902ce3..d88e6d13b 100644 --- a/perf/budgets.json +++ b/perf/budgets.json @@ -46,6 +46,13 @@ "consoleOutput.keyMissedFramePct": 10, "consoleOutput.tbtMs": 50, + "terminalTui.rowsRebuiltPerTuiFrame": 3, + "terminalTui.styleLayoutMsPerTuiFrame": 6, + "terminalTui.droppedFramesPct": 2, + "terminalTui.keyP95Ms": 25, + "terminalTui.keyMissedFramePct": 15, + "terminalTui.tbtMs": 50, + "gitLog.showMs": 300, "gitLog.droppedFramesPct": 2, "gitLog.tbtMs": 50, diff --git a/perf/lib/tuiRows.test.ts b/perf/lib/tuiRows.test.ts new file mode 100644 index 000000000..4a310eb1a --- /dev/null +++ b/perf/lib/tuiRows.test.ts @@ -0,0 +1,54 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from "vitest"; +import { startTuiRowObserver, stopTuiRowObserver } from "./tuiRows.ts"; + +afterEach(() => { + try { + stopTuiRowObserver(); + } catch { + // A test may already have stopped it, or deliberately rendered no rows. + } + document.body.replaceChildren(); +}); + +function terminalRow() { + document.body.innerHTML = '
ready
'; + return document.querySelector(".xterm-rows > div")!; +} + +describe("TUI row measurement", () => { + it.each([false, true])("counts each rebuild with separate deliveries: %s", async (separate) => { + const row = terminalRow(); + startTuiRowObserver(); + for (let n = 0; n < 3; n++) { + row.replaceChildren(document.createElement("span")); + if (separate) await Promise.resolve(); + } + expect(stopTuiRowObserver()).toBe(3); + row.replaceChildren(); + expect(() => stopTuiRowObserver()).toThrow("did not start"); + }); + + it("ignores nested span changes and changes outside the terminal rows", () => { + const row = terminalRow(); + startTuiRowObserver(); + row.firstChild!.textContent = "changed"; + document.body.append(document.createElement("div")); + row.replaceChildren(); + expect(stopTuiRowObserver()).toBe(1); + }); + + it.each(["", '
'])( + "rejects a missing or empty row renderer: %s", + (html) => { + document.body.innerHTML = html; + expect(() => startTuiRowObserver()).toThrow("row renderer did not open"); + }, + ); + + it("rejects a stream that never renders", () => { + terminalRow(); + startTuiRowObserver(); + expect(() => stopTuiRowObserver()).toThrow("did not render any rows"); + }); +}); diff --git a/perf/lib/tuiRows.ts b/perf/lib/tuiRows.ts new file mode 100644 index 000000000..a68a852e0 --- /dev/null +++ b/perf/lib/tuiRows.ts @@ -0,0 +1,28 @@ +type TuiWindow = Window & { __stopTuiRows?: () => number }; + +/** Runs in the page; count replacements independently of observer delivery batches. */ +export function startTuiRowObserver() { + const container = document.querySelector(".xterm .xterm-rows"); + if (!container?.childElementCount) throw new Error("terminal row renderer did not open"); + let rebuilt = 0; + const count = (records: MutationRecord[]) => { + for (const record of records) if (record.target.parentNode === container) rebuilt++; + }; + const observer = new MutationObserver(count); + observer.observe(container, { childList: true, subtree: true }); + (window as TuiWindow).__stopTuiRows = () => { + count(observer.takeRecords()); + observer.disconnect(); + return rebuilt; + }; +} + +export function stopTuiRowObserver(): number { + const w = window as TuiWindow; + const stop = w.__stopTuiRows; + delete w.__stopTuiRows; + if (!stop) throw new Error("terminal row observer did not start"); + const rebuilt = stop(); + if (!rebuilt) throw new Error("terminal TUI did not render any rows"); + return rebuilt; +} diff --git a/perf/scenarios.ts b/perf/scenarios.ts index 6ed8cba12..02853cf94 100644 --- a/perf/scenarios.ts +++ b/perf/scenarios.ts @@ -4,6 +4,7 @@ */ import { Harness, type Metrics, type Scenario } from "./lib/harness.ts"; import { frameSummary, keySummary, latencySummary, totalBlockingTime } from "./lib/stats.ts"; +import { startTuiRowObserver, stopTuiRowObserver } from "./lib/tuiRows.ts"; const ROOT = "/dev/acme-api"; const SAMPLE = `${ROOT}/src/main/kotlin/com/acme/orders/service/OrderService.kt`; @@ -192,6 +193,65 @@ const consoleOutput: Scenario = { }, }; +/** + * A full-screen agent TUI (Claude Code, Grok) repainting the terminal 10 times a second + * for 6 s — every row rewritten, only the spinner row changed — while the user types in + * an editor. Guards the terminal's unchanged-row skip: without it every frame restyles + * and lays out the whole screen. + */ +const TUI_FRAMES = 60; +const terminalTui: Scenario = { + id: "terminalTui", + title: "Type while a full-screen TUI repaints the terminal", + async run(h) { + await h.openFile(SAMPLE); + const st = await h.editorState(); + await h.setCursor(Math.floor((st?.length ?? 0) / 2)); + // Open the terminal and let it settle before measuring. + const opened = await h.page.evaluate(() => + ( + window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise } } + ).__openideaPerf.runAction("terminal.sampleTui", { frames: 1, fps: 10 }), + ); + if (!opened) throw new Error("terminal.sampleTui is unavailable"); + await h.page.waitForTimeout(300); + await h.setCursor((await h.editorState())?.head ?? 0); + const refresh = await h.refreshMs(); + const t0 = await h.now(); + const before = await h.counters(); + await h.page.evaluate(startTuiRowObserver); + await h.inPage((p) => p.startFrames()); + const stream = h.page.evaluate( + (frames) => + ( + window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise } } + ).__openideaPerf.runAction("terminal.sampleTui", { frames, fps: 10 }), + TUI_FRAMES, + ); + let keys: number[]; + let rebuilt: number; + try { + await h.page.waitForTimeout(200); + await h.setCursor((await h.editorState())?.head ?? 0); + keys = await h.typeMeasured(TYPED.slice(0, 40), 70); + if (!(await stream)) throw new Error("terminal.sampleTui is unavailable"); + } finally { + rebuilt = await h.page.evaluate(stopTuiRowObserver); + } + const frames = await h.inPage((p) => p.stopFrames()); + const work = Harness.delta(before, await h.counters()); + return { + // ~1 with unchanged rows left in place (only the spinner row changes), the screen height without. + rowsRebuiltPerTuiFrame: rebuilt / TUI_FRAMES, + styleLayoutMsPerTuiFrame: work.styleLayoutMs / TUI_FRAMES, + scriptMsPerTuiFrame: work.scriptMs / TUI_FRAMES, + ...frameSummary(frames, refresh), + ...keySummary(keys, refresh, "key"), + tbtMs: totalBlockingTime(await h.longTasksSince(t0)), + }; + }, +}; + /** Held key: auto-repeat at ~30 Hz must never fall behind. */ const keyRepeat: Scenario = { id: "keyRepeat", @@ -740,6 +800,7 @@ export const SCENARIOS: Scenario[] = [ typingAngular, completion, consoleOutput, + terminalTui, gitLog, gitLogScrollbar, resizePanels, diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts index 06fd6c03c..ac0136a49 100644 --- a/src/features/terminal/index.ts +++ b/src/features/terminal/index.ts @@ -10,6 +10,7 @@ import { provideEmbeddedTerminal, registerToolWindow, toolWindowService } from " import { lazyComponent } from "@/ui"; import { installTerminalKeys } from "./keys"; import { loadTerminalRuntime, terminalRuntime } from "./loader"; +import { SAMPLE_TUI_END, SAMPLE_TUI_START, sampleTuiFrame } from "./sampleTui"; const WINDOW = "terminal"; @@ -52,8 +53,47 @@ async function split(arg: unknown, orientation: "horizontal" | "vertical", move focusActiveSoon(); } +/** + * The performance harness (`perf/`): a full-screen TUI repainting the active terminal + * `frames` times at `fps`, opening a tab first when there is none. + */ +async function streamSampleTui(frames: number, fps: number) { + const rt = await loadTerminalRuntime(); + if (!rt.activeSession()) rt.newTab(rt.startDirectory(projectRoot() ?? "/")); + toolWindowService().show(WINDOW, true); + const deadline = performance.now() + 5_000; + let term = rt.activeSession()?.term; + while (!term?.element && performance.now() < deadline) { + await new Promise((r) => requestAnimationFrame(r)); + term = rt.activeSession()?.term; + } + if (!term?.element) throw new Error("terminal did not open"); + const write = (data: string) => new Promise((resolve) => term.write(data, resolve)); + await write(SAMPLE_TUI_START); + for (let n = 0; n < frames; n++) { + const next = performance.now() + 1000 / fps; + await write(sampleTuiFrame(n, term.cols, term.rows)); + await new Promise((r) => setTimeout(r, Math.max(0, next - performance.now()))); + } + await write(SAMPLE_TUI_END); +} + export function activate(): () => void { const disposers: Array<() => void> = [ + import.meta.env.DEV || import.meta.env.MODE === "perf" + ? registerActions([ + { + id: "terminal.sampleTui", + title: "Stream Sample TUI", + category: "Terminal", + hidden: true, + run: async ({ arg }) => { + const { frames = 40, fps = 10 } = (arg ?? {}) as { frames?: number; fps?: number }; + await streamSampleTui(frames, fps); + }, + }, + ]) + : () => {}, registerToolWindow({ id: WINDOW, title: "Terminal", diff --git a/src/features/terminal/sampleTui.test.ts b/src/features/terminal/sampleTui.test.ts new file mode 100644 index 000000000..ab6ace429 --- /dev/null +++ b/src/features/terminal/sampleTui.test.ts @@ -0,0 +1,30 @@ +// @vitest-environment jsdom +import { describe, expect, it } from "vitest"; +import { Terminal } from "@xterm/xterm"; +import { SAMPLE_TUI_START, sampleTuiFrame } from "./sampleTui"; + +function screen(term: Terminal): string[] { + const buffer = term.buffer.active; + return Array.from({ length: term.rows }, (_, y) => buffer.getLine(y)?.translateToString(true) ?? ""); +} + +const write = (term: Terminal, data: string) => new Promise((resolve) => term.write(data, resolve)); + +describe("sampleTuiFrame", () => { + it("repaints the full screen and retitles, with only the spinner row changing", async () => { + const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }); + const titles: string[] = []; + term.onTitleChange((t) => titles.push(t)); + await write(term, SAMPLE_TUI_START + sampleTuiFrame(0, 80, 24)); + const first = screen(term); + await write(term, sampleTuiFrame(1, 80, 24)); + const second = screen(term); + + expect(term.buffer.active.type).toBe("alternate"); + expect(first.filter((line) => line.trim()).length).toBeGreaterThan(20); + const changed = first.map((line, y) => (line === second[y] ? -1 : y)).filter((y) => y >= 0); + expect(changed).toEqual([24 - 7]); + expect(titles).toEqual(["⠋ Thinking - sample", "⠙ Thinking - sample"]); + term.dispose(); + }); +}); diff --git a/src/features/terminal/sampleTui.ts b/src/features/terminal/sampleTui.ts new file mode 100644 index 000000000..dd8086488 --- /dev/null +++ b/src/features/terminal/sampleTui.ts @@ -0,0 +1,42 @@ +/** + * Synthetic output of a full-screen TUI (agent CLIs such as Claude Code or Grok) for the + * performance harness: every frame repaints the whole screen and retitles the window, while + * only the spinner row actually changes. That is the pattern that made typing lag (#2239). + */ + +const SPINNER = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"; + +const rgb = (r: number, g: number, b: number) => `\x1b[38;2;${r};${g};${b}m`; + +/** Fills `width` columns with `text`, repeated and cut. */ +function fill(text: string, width: number): string { + return text.repeat(Math.ceil(width / text.length)).slice(0, width); +} + +/** Frame `n` of a `cols`×`rows` screen: alt screen, cursor home, every row rewritten. */ +export function sampleTuiFrame(n: number, cols: number, rows: number): string { + const inner = Math.max(cols - 6, 1); + const spinner = SPINNER[n % SPINNER.length]; + let out = `\x1b]0;${spinner} Thinking - sample\x07\x1b[?25l\x1b[H`; + const line = (row: number, text: string) => { + out += `\x1b[${row};1H\x1b[2K${text}\x1b[0m`; + }; + line(1, `${rgb(130, 130, 140)} ~/projects/sample`); + for (let r = 2; r < rows - 6; r++) { + line(r, `${rgb(200, 200, 205)} ${fill(`Line ${r - 1} of the answer, with words and \`code\` in it. `, inner)}`); + } + line(rows - 6, `${rgb(220, 180, 90)} ${spinner} Thinking… ${(n / 10).toFixed(1)}s ${rgb(110, 110, 120)}[stop]`); + line(rows - 4, `${rgb(90, 90, 100)} ╭${"─".repeat(inner)}╮`); + line( + rows - 3, + `${rgb(90, 90, 100)} │ ${rgb(200, 200, 205)}❯${" ".repeat(Math.max(inner - 2, 0))}${rgb(90, 90, 100)}│`, + ); + line(rows - 2, `${rgb(90, 90, 100)} ╰${"─".repeat(inner)}╯`); + line(rows, `${rgb(150, 150, 160)} Enter:send │ Shift+Tab:mode │ Ctrl+c:cancel`); + return `${out}\x1b[${rows - 3};6H\x1b[?25h`; +} + +/** Enters the alternate screen; written once before the first frame. */ +export const SAMPLE_TUI_START = "\x1b[?1049h"; +/** Leaves it again. */ +export const SAMPLE_TUI_END = "\x1b[?1049l"; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index ef981f5d2..1272fd87a 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,4 +1,5 @@ { + "Stream Sample TUI": "Stream Sample TUI", "Arduino tool '{configured}' was not found. Set its path in Settings > Languages & Frameworks > Language Servers, or in settings.toml under languages.arduino.": "Arduino tool '{configured}' was not found. Set its path in Settings > Languages & Frameworks > Language Servers, or in settings.toml under languages.arduino.", "Arduino tool '{name}' was not found on PATH or in Arduino IDE. Install Arduino IDE 2, or set its path in Settings > Languages & Frameworks > Language Servers or settings.toml under languages.arduino.": "Arduino tool '{name}' was not found on PATH or in Arduino IDE. Install Arduino IDE 2, or set its path in Settings > Languages & Frameworks > Language Servers or settings.toml under languages.arduino.", "Install Arduino IDE 2 (includes Arduino Language Server, Arduino CLI and clangd) and the board's core. Configure the server command and arguments in Settings > Languages & Frameworks > Language Servers, or set languages.arduino.cli, languages.arduino.clangd, languages.arduino.languageServer and languages.arduino.cliConfig in settings.toml. Set the board FQBN in sketch.yaml or languages.arduino.fqbn in settings.toml.": "Install Arduino IDE 2 (includes Arduino Language Server, Arduino CLI and clangd) and the board's core. Configure the server command and arguments in Settings > Languages & Frameworks > Language Servers, or set languages.arduino.cli, languages.arduino.clangd, languages.arduino.languageServer and languages.arduino.cliConfig in settings.toml. Set the board FQBN in sketch.yaml or languages.arduino.fqbn in settings.toml.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 92c471558..010f09508 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2467,6 +2467,7 @@ "Stop to Edit": "停止以编辑", "Stopped after {count} matches": "匹配 {count} 处后停止", "Stream Sample Output": "流式输出示例日志", + "Stream Sample TUI": "流式全屏 TUI 示例", "Open Sample Conversations": "打开示例会话", "Strikeout": "删除线", "Struct": "结构体",