Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix(tui): speed up focused overlay navigation (#398)

kt0d3876cd0e47
diff --git a/packages/tui/CHANGELOG.md b/packages/tui/CHANGELOG.md
index c5cb4c7945..a5fd68dddd 100644
--- a/packages/tui/CHANGELOG.md
+++ b/packages/tui/CHANGELOG.md
@@ -2,6 +2,8 @@
## [Unreleased]
+- Fixed focused full-pane overlays becoming slow to navigate on wider terminals.
+
## [0.3.0] - 2026-07-13
- Fixed fullscreen TUI handoffs temporarily releasing raw input and leaking keyboard-protocol timers, which caused flicker and echoed arrow escape sequences while opening sessions.
diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.ts
index 159fdf5c2c..7a8ce7c0b7 100644
--- a/packages/tui/src/tui.ts
+++ b/packages/tui/src/tui.ts
@@ -17,7 +17,7 @@ import {
normalizeTerminalOutput,
sliceByColumn,
sliceWithWidth,
- stripAnsi,
+ visibleContentSpan,
visibleWidth,
} from "./utils.js";
@@ -1108,16 +1108,7 @@ export class TUI extends Container {
}
private selectableSpan(line: string, maxWidth: number): { from: number; to: number } | null {
- const width = Math.min(maxWidth, visibleWidth(line));
- let from = -1;
- let to = -1;
- for (let col = 0; col < width; col++) {
- const cell = stripAnsi(sliceByColumn(line, col, 1));
- if (cell.trim().length === 0) continue;
- if (from === -1) from = col;
- to = col + 1;
- }
- return from === -1 ? null : { from, to };
+ return visibleContentSpan(line, maxWidth);
}
private createDockSelectionRegions(
diff --git a/packages/tui/src/utils.ts b/packages/tui/src/utils.ts
index b049a0d808..06ad6dd2bc 100644
--- a/packages/tui/src/utils.ts
+++ b/packages/tui/src/utils.ts
@@ -255,6 +255,53 @@ export function visibleWidth(str: string): number {
return width;
}
+/** Find the terminal-column span containing visible, non-whitespace content. */
+export function visibleContentSpan(line: string, maxWidth: number): { from: number; to: number } | null {
+ const limit = Math.floor(maxWidth);
+ if (line.length === 0 || !Number.isFinite(limit) || limit <= 0) {
+ return null;
+ }
+
+ let from = -1;
+ let to = -1;
+ let currentCol = 0;
+ let i = 0;
+
+ while (i < line.length && currentCol < limit) {
+ const ansi = extractAnsiCode(line, i);
+ if (ansi) {
+ i += ansi.length;
+ continue;
+ }
+
+ if (line[i] === "\t") {
+ currentCol += 3;
+ i++;
+ continue;
+ }
+
+ let textEnd = i;
+ while (textEnd < line.length && line[textEnd] !== "\t" && !extractAnsiCode(line, textEnd)) {
+ textEnd++;
+ }
+
+ for (const { segment } of segmenter.segment(line.slice(i, textEnd))) {
+ const width = graphemeWidth(segment);
+ const segmentStart = currentCol;
+ const segmentEnd = currentCol + width;
+ if (width > 0 && segment.trim().length > 0 && segmentStart < limit) {
+ if (from === -1) from = segmentStart;
+ to = Math.min(segmentEnd, limit);
+ }
+ currentCol = segmentEnd;
+ if (currentCol >= limit) break;
+ }
+ i = textEnd;
+ }
+
+ return from === -1 ? null : { from, to };
+}
+
/**
* Normalize text for terminal output without changing logical editor content.
* Some terminals render precomposed Thai/Lao AM vowels inconsistently during
diff --git a/packages/tui/test/fullscreen.test.ts b/packages/tui/test/fullscreen.test.ts
index 743595f478..f589e16673 100644
--- a/packages/tui/test/fullscreen.test.ts
+++ b/packages/tui/test/fullscreen.test.ts
@@ -19,6 +19,21 @@ class InputComponent extends TestComponent {
}
}
+class SelectionOverlay extends TestComponent {
+ private selected = 0;
+
+ override render(width: number): string[] {
+ return ["first", "second"].map((label, index) => {
+ const line = label.padEnd(width);
+ return index === this.selected ? `\x1b[48;5;238m${line}\x1b[49m` : line;
+ });
+ }
+
+ handleInput(_data: string): void {
+ this.selected = (this.selected + 1) % 2;
+ }
+}
+
class LoggingVirtualTerminal extends VirtualTerminal {
private writes: string[] = [];
lastStopOptions: TerminalStopOptions | undefined;
@@ -263,6 +278,26 @@ describe("TUI fullscreen mode", () => {
tui.stop();
});
+ it("repaints only changed rows when navigating a focused overlay", async () => {
+ const { terminal, tui, chat, dock } = setup(lines(20));
+ tui.enterFullscreen({ scroll: [chat], dock });
+ await terminal.waitForRender();
+
+ tui.showOverlay(new SelectionOverlay(), { anchor: "center", width: 20 });
+ await terminal.waitForRender();
+ terminal.clearWrites();
+
+ terminal.sendInput("j");
+ await terminal.waitForRender();
+
+ const writes = terminal.getWrites();
+ const repaintedRows = writes.match(/\x1b\[\d+;1H\x1b\[2K/g) ?? [];
+ assert.ok(!writes.includes("\x1b[2J"), "overlay navigation should not clear the screen");
+ assert.strictEqual(repaintedRows.length, 2, "only the old and new selected rows should repaint");
+
+ tui.stop();
+ });
+
it("suspends fullscreen mouse tracking while a visible overlay requests native mouse", async () => {
const { terminal, tui, chat, dock } = setup(lines(20), 80, 10);
tui.enterFullscreen({ scroll: [chat], dock });
@@ -329,6 +364,27 @@ describe("TUI fullscreen mode", () => {
tui.stop();
});
+ it("drag-selects ANSI-styled wide text from a focused overlay", async () => {
+ const { terminal, tui, chat, dock } = setup(lines(20), 40, 10);
+ const copies: string[] = [];
+ tui.onCopy = (text) => copies.push(text);
+ tui.enterFullscreen({ scroll: [chat], dock });
+ await terminal.waitForRender();
+
+ const overlay = new InputComponent();
+ overlay.lines = ["\x1b[48;5;236m η•ŒπŸ™‚ \x1b[49m"];
+ tui.showOverlay(overlay, { anchor: "top-left", width: 20 });
+ await terminal.waitForRender();
+
+ terminal.sendInput("\x1b[<0;3;1M");
+ terminal.sendInput("\x1b[<32;7;1M");
+ terminal.sendInput("\x1b[<0;7;1m");
+ await terminal.waitForRender();
+
+ assert.deepStrictEqual(copies, ["η•ŒπŸ™‚"]);
+ tui.stop();
+ });
+
it("maps focused overlay selection to the painted viewport slice", async () => {
const { terminal, tui, chat, dock } = setup(lines(20), 80, 5);
const copies: string[] = [];
diff --git a/packages/tui/test/overlay-navigation-bench.ts b/packages/tui/test/overlay-navigation-bench.ts
new file mode 100644
index 0000000000..c36053aa05
--- /dev/null
+++ b/packages/tui/test/overlay-navigation-bench.ts
@@ -0,0 +1,131 @@
+/**
+ * Benchmark focused full-pane overlay navigation. Run with:
+ *
+ * npx tsx test/overlay-navigation-bench.ts
+ */
+import { performance } from "node:perf_hooks";
+import type { Terminal, TerminalStopOptions } from "../src/terminal.js";
+import { type Component, type Focusable, TUI } from "../src/tui.js";
+
+const HEIGHT = 40;
+const ITERATIONS = 200;
+const WIDTHS = [80, 120, 200];
+
+class BenchmarkTerminal implements Terminal {
+ altScreenActive = false;
+ mouseTrackingActive = false;
+ readonly kittyProtocolActive = false;
+
+ constructor(
+ readonly columns: number,
+ readonly rows: number,
+ ) {}
+
+ start(_onInput: (data: string) => void, _onResize: () => void): void {}
+ stop(_options?: TerminalStopOptions): void {}
+ async drainInput(): Promise<void> {}
+ write(_data: string): void {}
+ moveBy(_lines: number): void {}
+ hideCursor(): void {}
+ showCursor(): void {}
+ clearLine(): void {}
+ clearFromCursor(): void {}
+ clearScreen(): void {}
+ setTitle(_title: string): void {}
+ setProgress(_active: boolean): void {}
+
+ enterAltScreen(): void {
+ this.altScreenActive = true;
+ }
+
+ leaveAltScreen(): void {
+ this.altScreenActive = false;
+ }
+
+ setMouseTracking(enabled: boolean): void {
+ this.mouseTrackingActive = enabled;
+ }
+}
+
+class StaticComponent implements Component {
+ constructor(private readonly lines: string[]) {}
+
+ render(_width: number): string[] {
+ return this.lines;
+ }
+
+ invalidate(): void {}
+}
+
+class FullPaneSelector implements Component, Focusable {
+ focused = false;
+ private selected = 0;
+
+ constructor(private readonly rows: number) {}
+
+ handleInput(_data: string): void {
+ this.selected = (this.selected + 1) % 10;
+ }
+
+ render(width: number): string[] {
+ const lines = Array.from({ length: this.rows }, () => `\x1b[48;5;235m${" ".repeat(width)}\x1b[49m`);
+ for (let index = 0; index < 10; index++) {
+ const label = ` model-${index} provider`.padEnd(width);
+ const background = index === this.selected ? 238 : 235;
+ lines[index + 5] = `\x1b[48;5;${background}m${label}\x1b[49m`;
+ }
+ return lines;
+ }
+
+ invalidate(): void {}
+}
+
+interface ImmediateTuiRender {
+ doRender(): void;
+}
+
+function percentile(sorted: number[], percentileValue: number): number {
+ const index = Math.min(sorted.length - 1, Math.floor((percentileValue / 100) * sorted.length));
+ return sorted[index];
+}
+
+function run(width: number, fullscreen: boolean): { p50: number; p95: number } {
+ const terminal = new BenchmarkTerminal(width, HEIGHT);
+ const tui = new TUI(terminal);
+ const transcript = new StaticComponent(Array.from({ length: 100 }, (_, index) => `line-${index}`));
+ const dock = new StaticComponent(["> prompt", "footer"]);
+ const overlay = new FullPaneSelector(HEIGHT);
+
+ if (fullscreen) {
+ tui.enterFullscreen({ scroll: [transcript], dock, mouse: false });
+ } else {
+ tui.addChild(transcript);
+ tui.addChild(dock);
+ }
+ tui.showOverlay(overlay, { width: "100%", maxHeight: "100%", row: 0, col: 0 });
+
+ const render = (tui as unknown as ImmediateTuiRender).doRender.bind(tui);
+ render();
+ const durations: number[] = [];
+ for (let iteration = 0; iteration < ITERATIONS; iteration++) {
+ overlay.handleInput("down");
+ const start = performance.now();
+ render();
+ durations.push(performance.now() - start);
+ }
+ tui.stop({ flushFullscreen: false });
+
+ durations.sort((a, b) => a - b);
+ return { p50: percentile(durations, 50), p95: percentile(durations, 95) };
+}
+
+console.log(`focused overlay navigation (${HEIGHT} rows, ${ITERATIONS} updates)`);
+for (const fullscreen of [false, true]) {
+ const mode = fullscreen ? "fullscreen" : "inline";
+ for (const width of WIDTHS) {
+ const result = run(width, fullscreen);
+ console.log(
+ `${mode.padEnd(10)} ${String(width).padStart(3)} cols p50 ${result.p50.toFixed(3)} ms p95 ${result.p95.toFixed(3)} ms`,
+ );
+ }
+}
diff --git a/packages/tui/test/visible-content-span.test.ts b/packages/tui/test/visible-content-span.test.ts
new file mode 100644
index 0000000000..09dcb1ea52
--- /dev/null
+++ b/packages/tui/test/visible-content-span.test.ts
@@ -0,0 +1,27 @@
+import assert from "node:assert";
+import { describe, it } from "node:test";
+import { visibleContentSpan } from "../src/utils.js";
+
+describe("visibleContentSpan", () => {
+ it("finds content between surrounding and interior whitespace", () => {
+ assert.deepStrictEqual(visibleContentSpan(" alpha beta ", 80), { from: 2, to: 12 });
+ });
+
+ it("ignores ANSI styling and styled padding", () => {
+ const line = "\x1b[48;5;236m \x1b[1malpha\x1b[22m \x1b[49m";
+ assert.deepStrictEqual(visibleContentSpan(line, 80), { from: 2, to: 7 });
+ assert.strictEqual(visibleContentSpan("\x1b[48;5;236m \x1b[49m", 80), null);
+ });
+
+ it("measures tabs, wide graphemes, and combining marks in terminal columns", () => {
+ assert.deepStrictEqual(visibleContentSpan("\talpha\t", 80), { from: 3, to: 8 });
+ assert.deepStrictEqual(visibleContentSpan(" η•ŒπŸ™‚ ", 80), { from: 1, to: 5 });
+ assert.deepStrictEqual(visibleContentSpan(" e\u0301 ", 80), { from: 1, to: 2 });
+ });
+
+ it("clips the content span to the requested width", () => {
+ assert.deepStrictEqual(visibleContentSpan(" alpha", 4), { from: 2, to: 4 });
+ assert.deepStrictEqual(visibleContentSpan(" η•Œ", 4), { from: 3, to: 4 });
+ assert.strictEqual(visibleContentSpan("alpha", 0), null);
+ });
+});