From 24a894b1cea7a86ace92cae742de1effd598b5e9 Mon Sep 17 00:00:00 2001 From: ZouR-Ma <2605315944@qq.com> Date: Sun, 29 Nov 2026 14:07:36 +0800 Subject: [PATCH 1/2] fix(tui): restore the input position after interactive shrink --- docs/tui-rendering-pipeline.md | 2 + packages/tui/src/components/editor.ts | 8 ++- packages/tui/src/tui-main-screen.ts | 14 ++++ packages/tui/src/tui.ts | 24 ++++++- packages/tui/test/tui-render.test.ts | 98 +++++++++++++++++++++++++++ 5 files changed, 141 insertions(+), 5 deletions(-) diff --git a/docs/tui-rendering-pipeline.md b/docs/tui-rendering-pipeline.md index b7ae687fb..8ef947112 100644 --- a/docs/tui-rendering-pipeline.md +++ b/docs/tui-rendering-pipeline.md @@ -205,6 +205,8 @@ `stop()` 的收尾(`tui-main-screen.ts:194-202`):把光标推到内容末尾再换行,退出后主屏 scrollback 不残留半行。 +交互收缩:内联选择器或补全列表关闭后,如果文档末尾落在旧视口底边之上、视口顶部又有内容已滚进历史区,只擦除多余行会让输入栏悬在空白上方。常规模式在交互帧重放当前文档,让末尾回到可达的最底部;这会重建终端历史区。没有键盘输入、焦点切换或异步输入结果的普通后台帧,不触发这条回放路径。 + ## 6. 全屏渲染(fullscreen) `TuiAltScreen` 的渲染分两层:先算布局,再行级差分。 diff --git a/packages/tui/src/components/editor.ts b/packages/tui/src/components/editor.ts index d1ccdaa98..bb3a398ac 100644 --- a/packages/tui/src/components/editor.ts +++ b/packages/tui/src/components/editor.ts @@ -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; } @@ -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( diff --git a/packages/tui/src/tui-main-screen.ts b/packages/tui/src/tui-main-screen.ts index 61203cc9b..2affb9f04 100644 --- a/packages/tui/src/tui-main-screen.ts +++ b/packages/tui/src/tui-main-screen.ts @@ -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; @@ -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() diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.ts index 16f3ab569..48be7f1f6 100644 --- a/packages/tui/src/tui.ts +++ b/packages/tui/src/tui.ts @@ -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; @@ -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; @@ -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 {} @@ -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; @@ -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(); @@ -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(); diff --git a/packages/tui/test/tui-render.test.ts b/packages/tui/test/tui-render.test.ts index 4878091d0..abf9a1d87 100644 --- a/packages/tui/test/tui-render.test.ts +++ b/packages/tui/test/tui-render.test.ts @@ -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); From 6d1a377703c1d3f0361b2481c1c6daedd91c586d Mon Sep 17 00:00:00 2001 From: ZouR-Ma <2605315944@qq.com> Date: Sun, 29 Nov 2026 14:07:36 +0800 Subject: [PATCH 2/2] fix(coding-agent): pause progress while a clarification is open --- .../src/features/step-questionnaire.ts | 4 +++- .../test/step-capabilities-extension.test.ts | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/coding-agent/src/features/step-questionnaire.ts b/packages/coding-agent/src/features/step-questionnaire.ts index 1c972658d..2272e423d 100644 --- a/packages/coding-agent/src/features/step-questionnaire.ts +++ b/packages/coding-agent/src/features/step-questionnaire.ts @@ -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, @@ -516,7 +518,7 @@ async function executeNativeDialog( cachedLines = undefined; }, }; - }); + }, CLARIFY_DIALOG_OPTIONS); } async function executeQuestionnaire( diff --git a/packages/coding-agent/test/step-capabilities-extension.test.ts b/packages/coding-agent/test/step-capabilities-extension.test.ts index 019f3a95b..f12a8e927 100644 --- a/packages/coding-agent/test/step-capabilities-extension.test.ts +++ b/packages/coding-agent/test/step-capabilities-extension.test.ts @@ -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"; @@ -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[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<{