Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/tui-rendering-pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,8 @@

`stop()` 的收尾(`tui-main-screen.ts:194-202`):把光标推到内容末尾再换行,退出后主屏 scrollback 不残留半行。

交互收缩:内联选择器或补全列表关闭后,如果文档末尾落在旧视口底边之上、视口顶部又有内容已滚进历史区,只擦除多余行会让输入栏悬在空白上方。常规模式在交互帧重放当前文档,让末尾回到可达的最底部;这会重建终端历史区。没有键盘输入、焦点切换或异步输入结果的普通后台帧,不触发这条回放路径。

## 6. 全屏渲染(fullscreen)

`TuiAltScreen` 的渲染分两层:先算布局,再行级差分。
Expand Down
4 changes: 3 additions & 1 deletion packages/coding-agent/src/features/step-questionnaire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,8 @@ async function executeFallback(
return { questions, answers, cancelled: false };
}

const CLARIFY_DIALOG_OPTIONS = { waitingForApproval: true } as const;

async function executeNativeDialog(
questions: NormalizedQuestion[],
ctx: ExtensionContext,
Expand Down Expand Up @@ -516,7 +518,7 @@ async function executeNativeDialog(
cachedLines = undefined;
},
};
});
}, CLARIFY_DIALOG_OPTIONS);
}

async function executeQuestionnaire(
Expand Down
17 changes: 16 additions & 1 deletion packages/coding-agent/test/step-capabilities-extension.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import type { AgentToolResult } from "@step-harness/agent-core";
import { type Model, validateToolArguments } from "@step-harness/providers";
import { expect, test } from "vitest";
import { expect, test, vi } from "vitest";
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "../src/core/extensions/types.ts";
import { createStepCapabilitiesExtension } from "../src/features/step-capabilities.ts";
import { createStepPlanExtension } from "../src/features/step-plan.ts";
Expand Down Expand Up @@ -274,6 +274,21 @@ test("subagent rejects unknown fields and ignores an empty chain beside parallel
expect(calls).toEqual(["first inspection", "second inspection"]);
});

test("clarify_user marks the native dialog as waiting for a user decision", async () => {
const { api, tools } = createApi();
createStepCapabilitiesExtension({ subagent: { includeBuiltinAgents: false } })(api);
const ctx = createContext("/workspace");
const dialogShown = new Error("dialog shown");
const present = vi.fn(async (_options: Parameters<ExtensionContext["ui"]["custom"]>[1]) => {
throw dialogShown;
});
ctx.ui.custom = (_factory, options) => present(options);
await expect(
tools.get("clarify_user")!.execute("ask", { question: "Describe the change" }, undefined, undefined, ctx),
).rejects.toBe(dialogShown);
expect(present).toHaveBeenCalledExactlyOnceWith({ waitingForApproval: true });
});

test("Step capability adapters report clarification, plan, and subagent telemetry", async () => {
const { api, tools, emit } = createApi();
const events: Array<{
Expand Down
8 changes: 5 additions & 3 deletions packages/tui/src/components/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2303,9 +2303,11 @@ export class Editor implements Component, Focusable {

this.autocompleteAbort = undefined;

// Suggestions complete the keystroke that requested them, so their frames count
// as user interaction (a menu that closes must not strand the editor mid-screen).
if (!suggestions || !Array.isArray(suggestions.items) || suggestions.items.length === 0) {
this.cancelAutocomplete();
this.tui.requestRender();
this.tui.requestRender(false, { interaction: true });
return;
}

Expand All @@ -2324,12 +2326,12 @@ export class Editor implements Component, Focusable {
this.state.cursorLine = result.cursorLine;
this.setCursorCol(result.cursorCol);
if (this.onChange) this.onChange(this.getText());
this.tui.requestRender();
this.tui.requestRender(false, { interaction: true });
return;
}

this.applyAutocompleteSuggestions(suggestions, options.force ? "force" : "regular");
this.tui.requestRender();
this.tui.requestRender(false, { interaction: true });
}

private isAutocompleteRequestCurrent(
Expand Down
14 changes: 14 additions & 0 deletions packages/tui/src/tui-main-screen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ export class TuiMainScreen extends TuiBase implements TUI {

protected doRender(): void {
if (this.stopped) return;
const followsInteraction = this.consumeInteractionRender();
const width = this.terminal.columns;
const height = this.terminal.rows;
const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
Expand Down Expand Up @@ -441,6 +442,19 @@ export class TuiMainScreen extends TuiBase implements TUI {
return;
}

// If a transient UI shrank after scrolling the terminal, erasing its rows cannot
// bring back lines already in scrollback. Replay the document to restore the bottom
// on interaction; this recovery does not run on ordinary background frames.
if (
followsInteraction &&
!this.hasOverlayEntries &&
prevViewportTop > 0 &&
newLines.length < prevViewportTop + height
) {
fullRender(true);
return;
}

// Content shrunk below the working area and no overlays - re-render to clear empty rows
// (overlays need the padding, so only do this when no overlays are active)
// Configurable via setClearOnShrink()
Expand Down
24 changes: 22 additions & 2 deletions packages/tui/src/tui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,8 @@ export interface TUI extends Component {
start(): void;
stop(options?: TuiStopOptions): void;
renderNow(force?: boolean): void;
requestRender(force?: boolean): void;
/** Mark asynchronous updates that complete a user's input as part of the interaction. */
requestRender(force?: boolean, options?: { interaction?: boolean }): void;
addInputListener(listener: TuiInputListener): () => void;
removeInputListener(listener: TuiInputListener): void;
onTerminalColorSchemeChange(listener: (scheme: TerminalColorScheme) => void): () => void;
Expand Down Expand Up @@ -450,6 +451,8 @@ export abstract class TuiBase extends Container implements TUI {
private static readonly MIN_RENDER_INTERVAL_MS = 16;
private showHardwareCursor = false;
private clearOnShrink = false;
// Keyboard input, focus changes, and their async continuations can re-anchor a frame.
private interactionRenderPending = false;
protected fullRedrawCount = 0;
protected stopped = false;
private pendingOsc11BackgroundReplies = 0;
Expand Down Expand Up @@ -485,6 +488,18 @@ export abstract class TuiBase extends Container implements TUI {

protected abstract doRender(): void;

/**
* Whether this frame follows keyboard input handled by the focused component, a
* focus move, or work completing such input. The flag is consumed, so each event
* marks at most one frame: the user is at the input surface then, unlike during
* background updates.
*/
protected consumeInteractionRender(): boolean {
const pending = this.interactionRenderPending;
this.interactionRenderPending = false;
return pending;
}

protected resetRenderState(): void {}

protected beforeTerminalStart(): void {}
Expand Down Expand Up @@ -585,6 +600,9 @@ export abstract class TuiBase extends Container implements TUI {
}

this.focusedComponent = nextFocus;
// Moving focus swaps the input surface (a dialog opened or closed), whether the
// swap follows a keystroke directly or an asynchronous decision.
if (nextFocus !== previousFocus) this.interactionRenderPending = true;

if (isFocusable(nextFocus)) {
nextFocus.focused = true;
Expand Down Expand Up @@ -883,7 +901,8 @@ export abstract class TuiBase extends Container implements TUI {
this.doRender();
}

requestRender(force = false): void {
requestRender(force = false, options?: { interaction?: boolean }): void {
if (options?.interaction) this.interactionRenderPending = true;
if (force) {
this.resetRenderState();
this.requestImmediateRender();
Expand Down Expand Up @@ -1009,6 +1028,7 @@ export abstract class TuiBase extends Container implements TUI {
return;
}
this.focusedComponent.handleInput(data);
this.interactionRenderPending = true;
// Keyboard input is latency-sensitive. Avoid the throttled timer path,
// where even setTimeout(0) can take a full 16 ms tick on Windows.
this.requestImmediateRender();
Expand Down
98 changes: 98 additions & 0 deletions packages/tui/test/tui-render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,104 @@ describe("TUI resize handling", () => {
});
});

describe("TUI shrink after interaction", () => {
// A transcript taller than the screen with a tall selector below it, then the
// selector closes. Mirrors `/model` followed by Esc in the regular renderer.
const transcript = Array.from({ length: 14 }, (_, index) => `history ${index}`);
const selector = Array.from({ length: 6 }, (_, index) => `selector ${index}`);
const lastNonBlankRow = (viewport: string[]): number =>
viewport.reduce((last, line, row) => (line.trim() ? row : last), -1);

/** Typing replaces only the prompt row, like an editor below a transcript. */
class PromptComponent extends TestComponent {
handleInput(data: string): void {
this.lines = [...this.lines.slice(0, -1), data];
}
}

async function openAndClose(close: (tui: TuiMainScreen, input: PromptComponent) => void) {
const terminal = new VirtualTerminal(40, 10);
const tui = new TuiMainScreen(terminal);
const input = new PromptComponent();
input.lines = [...transcript, ...selector, "> prompt"];
tui.addChild(input);
tui.setFocus(input);
tui.start();
await terminal.waitForRender();
const redrawsBefore = tui.fullRedraws;
input.lines = [...transcript, "> prompt"];
close(tui, input);
await terminal.waitForRender();
return { terminal, tui, input, redrawsBefore };
}

it("reanchors the input on the next keystroke after a background shrink", async () => {
// The shrink itself arrives as a background update (no interaction).
const { terminal, tui, redrawsBefore } = await openAndClose((ui) => ui.requestRender());
try {
// Background shrink alone leaves the gap (no wipe while the user may read scrollback).
let viewport = terminal.getViewport();
assert.strictEqual(tui.fullRedraws, redrawsBefore);
assert.ok(lastNonBlankRow(viewport) < 9, `expected a gap, got ${JSON.stringify(viewport)}`);

// The next keystroke heals it.
terminal.sendInput("> typed");
await terminal.waitForRender();
viewport = terminal.getViewport();
assert.ok(tui.fullRedraws > redrawsBefore);
assert.strictEqual(lastNonBlankRow(viewport), 9);
assert.strictEqual(viewport[9]?.trim(), "> typed");
assert.ok(viewport[8]?.includes("history 13"));
} finally {
tui.stop();
}
});

it("pins the input to the bottom when focus moves with the shrink", async () => {
const { terminal, tui, input, redrawsBefore } = await openAndClose((ui, component) => {
ui.setFocus(null);
ui.setFocus(component);
ui.requestRender();
});
try {
const viewport = terminal.getViewport();
assert.ok(tui.fullRedraws > redrawsBefore);
assert.strictEqual(lastNonBlankRow(viewport), 9);
assert.strictEqual(viewport[9]?.trim(), "> prompt");
assert.deepStrictEqual(input.lines.at(-1), "> prompt");
} finally {
tui.stop();
}
});

it("pins the input to the bottom for a requested interaction frame", async () => {
const { terminal, tui, redrawsBefore } = await openAndClose((ui) =>
ui.requestRender(false, { interaction: true }),
);
try {
assert.ok(tui.fullRedraws > redrawsBefore);
assert.strictEqual(lastNonBlankRow(terminal.getViewport()), 9);
} finally {
tui.stop();
}
});

it("does not redraw again once the document fills the screen", async () => {
const { terminal, tui } = await openAndClose((ui) => ui.requestRender(false, { interaction: true }));
try {
const redraws = tui.fullRedraws;
terminal.sendInput("> a");
await terminal.waitForRender();
terminal.sendInput("> ab");
await terminal.waitForRender();
assert.strictEqual(tui.fullRedraws, redraws);
assert.strictEqual(terminal.getViewport()[9]?.trim(), "> ab");
} finally {
tui.stop();
}
});
});

describe("TUI content shrinkage", () => {
it("clears empty rows when content shrinks significantly", async () => {
const terminal = new VirtualTerminal(40, 10);
Expand Down