The Open Framework for Building Agents
fix(eve): render HITL in TUI drawers (#3828)
OwenKephart3b6549c6236c
diff --git a/.changeset/tui-hitl-drawers.md b/.changeset/tui-hitl-drawers.mdnew file mode 100644index 000000000..f43c1be6d--- /dev/null+++ b/.changeset/tui-hitl-drawers.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Render terminal approvals and questions in drawers, and simplify the completed-turn stats line.diff --git a/packages/eve/src/cli/dev/tui/blocks.test.ts b/packages/eve/src/cli/dev/tui/blocks.test.tsindex a1b4e9ac8..5d2946b48 100644--- a/packages/eve/src/cli/dev/tui/blocks.test.ts+++ b/packages/eve/src/cli/dev/tui/blocks.test.ts@@ -256,9 +256,9 @@ describe("renderBlockLines", () => {expect(lines).toEqual([" ▪ Ran pnpm test"]);});- it("renders the end-of-turn stats as a dim cornered coda", () => {- expect(render({ kind: "turn-stats", body: "Done in 3min 24s ── ↑ 32.4K ↓ 682" })).toEqual([- "└ Done in 3min 24s ── ↑ 32.4K ↓ 682",+ it("renders the end-of-turn stats as a standalone dim coda", () => {+ expect(render({ kind: "turn-stats", body: "Done in 3min 24s (↑ 32.4K ↓ 682)" })).toEqual([+ "Done in 3min 24s (↑ 32.4K ↓ 682)",]);});diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.tsindex 5f658211c..405d86c3f 100644--- a/packages/eve/src/cli/dev/tui/blocks.ts+++ b/packages/eve/src/cli/dev/tui/blocks.ts@@ -562,13 +562,12 @@ function renderLog(block: DisplayBlock, width: number, theme: Theme): string[] {}/**- * The end-of-turn coda: `└ Done in 3min 24s ── ↑ 32.4K ↓ 682`, dim,- * closing the turn under the assistant's final prose. The corner is the- * settled form of the live `▪ Working… <duration> ── <flow>` turn bar; the- * body arrives fully composed from the renderer's shared stats builder.+ * The end-of-turn coda: `Done in 3min 24s (↑ 32.4K ↓ 682)`, dim and+ * standalone beneath the assistant's final prose. The body arrives fully+ * composed from the renderer's shared stats builder.*/function renderTurnStats(block: Block, width: number, theme: Theme): string[] {- const line = `${theme.glyph.corner} ${block.body ?? ""}`;+ const line = block.body ?? "";return [theme.colors.dim(truncatePlain(line, Math.max(1, width)))];}diff --git a/packages/eve/src/cli/dev/tui/question-panel.test.ts b/packages/eve/src/cli/dev/tui/question-panel.test.tsindex e7d36086d..fa7126c50 100644--- a/packages/eve/src/cli/dev/tui/question-panel.test.ts+++ b/packages/eve/src/cli/dev/tui/question-panel.test.ts@@ -31,24 +31,24 @@ function render(state: {}describe("renderQuestionPanel", () => {- it("opens with a borderless prompt and closes on the dismiss hint", () => {+ it("renders a prompt and options for its enclosing drawer", () => {const rows = render({ cursor: 0 });expect(rows[0]).toBe(" What type of options would you like to see?");expect(rows).toContain(" What type of options would you like to see?");- expect(rows.find((row) => row.includes("1. Available Tools"))).toContain("›");- expect(rows).toContain(" See 4 tools I can use");- expect(rows).toContain(" 2. Connected Services");+ expect(rows.find((row) => row.includes("Available Tools"))).toBe(" Available Tools");+ expect(rows).toContain(" See 4 tools I can use");+ expect(rows).toContain(" Connected Services");expect(rows[1]).toBe("");- expect(rows.at(-1)).toBe(" Esc to dismiss");+ expect(rows.at(-1)).toBe(" Type your own answer…");});it("marks only the cursor row with the pointer and enter badge", () => {const rows = render({ cursor: 1 });const selected = rows.find((row) => row.includes("Connected Services"));- expect(selected).toContain(" › 2. Connected Services ");- expect(selected).toContain("↵");+ expect(selected).toBe(" Connected Services");+ expect(selected).not.toContain("↵");expect(rows.find((row) => row.includes("Available Tools"))).not.toContain("›");});@@ -56,21 +56,21 @@ describe("renderQuestionPanel", () => {const columnsOf = (rows: string[]) =>rows.filter((row) => row.includes("Connected Services"))- .map((row) => row.indexOf("2. Connected Services"));+ .map((row) => row.indexOf("Connected Services"));// Selected and unselected variants of the same row must not drift.expect(columnsOf(render({ cursor: 1 }))).toEqual(columnsOf(render({ cursor: 0 })));});- it("shows the elbow editor only while the freeform row is focused or drafted", () => {- expect(render({ cursor: 0 }).some((row) => row.includes("⎿"))).toBe(false);+ it("turns the freeform placeholder into an inline editor when focused", () => {+ expect(render({ cursor: 0 }).at(-1)).toBe(" Type your own answer…");const focused = render({ cursor: 2 });- expect(focused.some((row) => row.includes("⎿"))).toBe(true);+ expect(focused.at(-1)).toBe(" Type your own answer…");- // A draft typed then abandoned stays visible under the row.+ // A draft remains in the inline field when the cursor moves away.const drafted = render({ cursor: 0, editor: { text: "custom", cursor: 6 } });- expect(drafted.find((row) => row.includes("⎿"))).toContain("custom");+ expect(drafted.at(-1)).toBe(" custom");});it("splits a multi-paragraph prompt into real rows before wrapping", () => {diff --git a/packages/eve/src/cli/dev/tui/question-panel.ts b/packages/eve/src/cli/dev/tui/question-panel.tsindex 560cf716c..8a445ada7 100644--- a/packages/eve/src/cli/dev/tui/question-panel.ts+++ b/packages/eve/src/cli/dev/tui/question-panel.ts@@ -1,8 +1,7 @@/**- * Pure rendering for the HITL question panel — the overlay a pending question- * request (such as one from `ask_question` or `ctx.ask()`) opens above the- * input area. A full-width rule separates- * it from the transcript, options render as numbered rows with their+ * Pure rendering for the HITL question drawer — a pending question request+ * (such as one from `ask_question` or `ctx.ask()`) opens above the input area.+ * Options render as numbered rows with their* descriptions always visible, and the trailing "Type your own answer" row* carries an inline elbow editor that receives focus the moment the cursor* rests on it (the provider-key grammar from the setup panel). The renderer@@ -12,9 +11,15 @@import type { AgentTUIInputOption } from "./runner.js";import { visibleLine, type LineState } from "./line-editor.js";import type { Theme } from "./theme.js";-import { clipVisible, renderInputWithBlockCursor, wrapVisibleLine } from "#cli/ui/terminal-text.js";+import {+ clipVisible,+ renderInputText,+ renderInputWithBlockCursor,+ wrapVisibleLine,+} from "#cli/ui/terminal-text.js";+import { renderOptionRow } from "#setup/cli/option-row.js";-const FREEFORM_ROW_LABEL = "Type your own answer";+const FREEFORM_ROW_LABEL = "Type your own answer…";export interface QuestionPanelState {readonly prompt: string;@@ -28,19 +33,12 @@ export interface QuestionPanelState {readonly caretVisible: boolean;}-/** Rows under the cursor paint like the setup panel's selected option. */-function selectedRow(text: string, theme: Theme): string {- const c = theme.colors;- return `${c.bold(` ${theme.glyph.selectedPointer} ${text}`)} ${c.dim("↵")}`;-}-export function renderQuestionPanel(state: QuestionPanelState,theme: Theme,width: number,): string[] {const c = theme.colors;- const g = theme.glyph;// The rule hugs the question — no blank row between them.const rows: string[] = [];@@ -55,63 +53,67 @@ export function renderQuestionPanel(}rows.push("");- for (const [index, option] of state.options.entries()) {- rows.push(...optionRows(option.label, option.description, index, state, theme));- }+ rows.push(...renderQuestionChoices(state.options, state.cursor, theme));if (state.allowFreeform) {- const index = state.options.length;- const focused = state.cursor === index;- rows.push(...optionRows(FREEFORM_ROW_LABEL, undefined, index, state, theme));- if (focused || state.editor.text.length > 0) {- rows.push(` ${c.dim(g.elbow)} ${freeformEditorBody(state, focused, theme, width)}`);- }+ rows.push(renderFreeformRow(state, theme, width));}- // One quiet hint; arrow/enter affordances are carried by the cursor row- // itself. The overlay suppresses the footer's status hint row entirely.- rows.push("", ` ${c.dim("Esc to dismiss")}`);return rows.map((row) => clipVisible(row, width));}-function optionRows(- label: string,- description: string | undefined,- index: number,- state: QuestionPanelState,+export function renderQuestionChoices(+ options: readonly AgentTUIInputOption[],+ cursor: number,theme: Theme,+ forceCursor = false,): string[] {- const c = theme.colors;- const numbered = `${index + 1}. ${label}`;- // Both variants put the number at column 5 and the label at column 8 —- // the selected row's extra cells are its pointer and padding, so moving- // the cursor never shifts the text horizontally.- const rows = [- state.cursor === index- ? ` ${selectedRow(numbered, theme)}`- : ` ${c.dim(`${index + 1}.`)} ${label}`,- ];- if (description !== undefined && description.length > 0) {- rows.push(` ${c.dim(description)}`);- }- return rows;+ return options.flatMap((option, index) => {+ const isCursor = forceCursor || cursor === index;+ const row = renderOptionRow({+ colors: theme.colors,+ glyphs: {+ pointer: theme.glyph.pointer,+ selectedPointer: theme.glyph.selectedPointer,+ success: theme.glyph.success,+ placeholder: theme.glyph.option,+ dot: theme.glyph.dot,+ warning: theme.glyph.warning,+ },+ label: option.label,+ isCursor,+ state: { kind: "available", checked: false },+ placeholder: false,+ presentation: "minimal",+ });+ const rows = [` ${row}`];+ if (option.description !== undefined && option.description.length > 0) {+ rows.push(` ${theme.colors.dim(option.description)}`);+ }+ return rows;+ });}-function freeformEditorBody(- state: QuestionPanelState,- focused: boolean,- theme: Theme,- width: number,-): string {+function renderFreeformRow(state: QuestionPanelState, theme: Theme, width: number): string {const c = theme.colors;- // Reserve the elbow gutter plus the block cursor's trailing cell.- const budget = Math.max(4, width - 12);+ const focused = state.cursor === state.options.length;+ // Reserve the block cursor's trailing cell so an input at the width limit+ // never clips its caret.+ const budget = Math.max(4, width - 6);if (!focused) {- const preserved = visibleLine(state.editor, budget, theme.glyph.ellipsis);- return c.dim(`${preserved.before}${preserved.under}${preserved.after}`);+ const visible = visibleLine(state.editor, budget, theme.glyph.ellipsis);+ const value =+ state.editor.text.length === 0+ ? FREEFORM_ROW_LABEL+ : `${visible.before}${visible.under}${visible.after}`;+ return ` ${c.dim(value)}`;}- return renderInputWithBlockCursor({- ...visibleLine(state.editor, budget, theme.glyph.ellipsis),++ const placeholder = state.editor.text.length === 0;+ const line = placeholder ? { text: FREEFORM_ROW_LABEL, cursor: 0 } : state.editor;+ return ` ${renderInputWithBlockCursor({+ ...visibleLine(line, budget, theme.glyph.ellipsis),visible: state.caretVisible,inverse: c.inverse,- });+ render: placeholder ? (text) => c.dim(renderInputText(text)) : undefined,+ })}`;}diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 13d0bbad1..d8dea6eaf 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -1671,12 +1671,12 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.renderSessionBoundary();const snapshot = screen.snapshot();// The dead turn's stats close before the boundary, not after it.- expect(snapshot.indexOf("└ Done in")).toBeGreaterThan(-1);- expect(snapshot.indexOf("└ Done in")).toBeLessThan(snapshot.indexOf("┌── Session restarted"));+ expect(snapshot.indexOf("Done in")).toBeGreaterThan(-1);+ expect(snapshot.indexOf("Done in")).toBeLessThan(snapshot.indexOf("┌── Session restarted"));// Control returning to the prompt must not add a second coda.const second = renderer.readPrompt();- expect(countOccurrences(screen.snapshot(), "└ Done in")).toBe(1);+ expect(countOccurrences(screen.snapshot(), "Done in")).toBe(1);input.ctrlC();expect(screen.snapshot()).toContain("❯");input.ctrlC();@@ -2029,7 +2029,7 @@ describe("TerminalRenderer (inline scrollback)", () => {const second = renderer.readPrompt();// Tokens are the turn's summed step usage, not the last report; the sum// crossing the 20K input threshold is what earns the row.- expect(screen.snapshot()).toContain("└ Done in 1s ── ↑ 20.5K ↓ 43");+ expect(screen.snapshot()).toContain("Done in 1s (↑ 20.5K ↓ 43)");input.ctrlC();expect(screen.snapshot()).toContain("❯");input.ctrlC();@@ -2058,7 +2058,7 @@ describe("TerminalRenderer (inline scrollback)", () => {// Under 10s and under 20K turn input: no coda row.const second = renderer.readPrompt();- expect(screen.snapshot()).not.toContain("\n└ ");+ expect(screen.snapshot()).not.toContain("\nDone in ");input.ctrlC();expect(screen.snapshot()).toContain("❯");input.ctrlC();@@ -2163,7 +2163,7 @@ describe("TerminalRenderer (inline scrollback)", () => {// 12s of wall clock qualifies the coda; the thought itself leaves no// separate transcript bar.const second = renderer.readPrompt();- expect(screen.snapshot()).toContain("└ Done in 12s");+ expect(screen.snapshot()).toContain("Done in 12s");expect(screen.snapshot()).not.toContain("Thought for");input.ctrlC();input.ctrlC();@@ -2927,7 +2927,7 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});- it("renders the question overlay with numbered rows and a bold cursor", async () => {+ it("renders the question drawer with shared option rows", async () => {const { screen, input, renderer } = makeRenderer();const answer = renderer.readInputQuestion({@@ -2943,24 +2943,27 @@ describe("TerminalRenderer (inline scrollback)", () => {const snapshot = screen.snapshot();const lines = snapshot.split("\n");const selected = lines.find((line) => line.includes("AI Gateway"));- expect(selected).toContain(" › 1. AI Gateway ");- expect(selected).toContain("↵");+ expect(selected).toBe(" AI Gateway");+ expect(selected).not.toContain("↵");+ expect(selected).not.toContain("1.");expect(screen.rawOutput()).not.toContain("\x1b[7m");expect(screen.rawOutput()).toContain("\x1b[1m");// Every option's description rides its own row, cursor or not.- expect(lines).toContain(" Managed access");- expect(lines).toContain(" Direct access");- // The panel carries its one quiet hint; no status hint row beneath it.- expect(snapshot).toContain("Esc to dismiss");- expect(snapshot).not.toContain("Enter to select");- expect(countOccurrences(snapshot, "Esc to")).toBe(1);+ expect(lines).toContain(" Managed access");+ expect(lines).toContain(" Direct access");+ // The drawer carries selection and dismissal controls; no status row+ // appears beneath it.+ expect(snapshot).toContain("esc to dismiss");+ expect(snapshot).toContain("enter to select");+ expect(snapshot).toContain("↑/↓ move");+ expect(countOccurrences(snapshot, "esc to dismiss")).toBe(1);input.send("j");const unselected = screen.snapshot().split("\n").find((line) => line.includes("AI Gateway"));- expect(unselected).toContain("1. AI Gateway");+ expect(unselected).toContain("AI Gateway");expect(unselected).not.toContain("›");input.send("k");@@ -2989,7 +2992,7 @@ describe("TerminalRenderer (inline scrollback)", () => {{ id: "external", label: "Other providers", description: "Direct access" },],});- expect(screen.snapshot()).toContain("Esc to dismiss");+ expect(screen.snapshot()).toContain("esc to dismiss");await escape();// No answer travels; the runner returns to the prompt and the question@@ -3019,13 +3022,15 @@ describe("TerminalRenderer (inline scrollback)", () => {options: [{ id: "gateway", label: "AI Gateway" }],allowFreeform: true,});- input.type("2");+ input.down();+ expect(screen.snapshot()).toContain("Type your own answer…");+ expect(screen.rawOutput()).toContain("\x1b[7m");input.type("draft answer");- expect(screen.snapshot()).toContain("⎿ draft answer");+ expect(screen.snapshot()).toContain("draft answer");await escape();expect(screen.snapshot()).not.toContain("draft answer");- expect(screen.snapshot()).toContain("Esc to dismiss");+ expect(screen.snapshot()).toContain("esc to dismiss");await escape();await expect(answer).resolves.toBeUndefined();@@ -3083,24 +3088,6 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(screen.snapshot()).not.toContain("Ask Pick a color.");});- it("selects a question option directly by its number key", async () => {- const { input, renderer } = makeRenderer();-- const answer = renderer.readInputQuestion({- requestId: "q1",- prompt: "Choose access",- display: "select",- options: [- { id: "gateway", label: "AI Gateway" },- { id: "external", label: "Other providers" },- ],- });- input.type("2");-- await expect(answer).resolves.toEqual({ optionId: "external" });- renderer.shutdown();- });-it("focuses the freeform editor when the cursor reaches its row", async () => {const { screen, input, renderer } = makeRenderer();@@ -3115,12 +3102,14 @@ describe("TerminalRenderer (inline scrollback)", () => {allowFreeform: true,});- expect(screen.snapshot()).toContain("3. Type your own answer");- // The freeform row's number moves focus into its inline editor; typing- // lands there without a separate enter.- input.type("3");+ expect(screen.snapshot()).toContain("Type your own answer…");+ // Moving to the freeform row focuses its inline editor; typing lands+ // there without a separate enter.+ input.down();+ input.down();+ expect(screen.rawOutput()).toContain("\x1b[7m");input.type("neither");- expect(screen.snapshot()).toContain("⎿ neither");+ expect(screen.snapshot()).toContain("neither");input.enter();await expect(answer).resolves.toEqual({ text: "neither" });@@ -3141,8 +3130,9 @@ describe("TerminalRenderer (inline scrollback)", () => {});input.type("New York");await escape();- // First Esc only clears the draft; the question is still answerable.- expect(screen.snapshot()).toContain("? What city are you in?");+ // First Esc only clears the draft; the question drawer stays open.+ expect(screen.snapshot()).toContain("What city are you in?");+ expect(screen.snapshot()).toContain("Enter submit · Esc dismiss");await escape();await expect(answer).resolves.toBeUndefined();@@ -4036,6 +4026,57 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});+ it("renders tool approval in a drawer", async () => {+ const { screen, input, renderer } = makeRenderer();+ const approval = renderer.readToolApproval({+ approvalId: "a1",+ toolCallId: "c1",+ toolName: "random_color",+ input: {},+ });++ const snapshot = screen.snapshot();+ expect(snapshot).toContain("\n\n─");+ expect(snapshot).toContain("Approve random_color?");+ const yes = snapshot.split("\n").find((row) => row.includes("Yes"));+ expect(yes).toBe(" Yes");+ expect(snapshot).toContain("No");+ expect(snapshot).toContain("y yes · n no · Ctrl-C cancel");+ expect(snapshot).not.toContain("(y/n)");+ input.down();+ expect(+ screen+ .snapshot()+ .split("\n")+ .find((row) => row.includes("No")),+ ).toBe(" No");+ input.up();+ input.enter();++ await expect(approval).resolves.toEqual({ approved: true });+ renderer.shutdown();+ });++ it("clears a pending approval drawer when interrupted externally", async () => {+ const { screen, renderer } = makeRenderer();+ const approval = renderer.readToolApproval({+ approvalId: "a1",+ toolCallId: "c1",+ toolName: "random_color",+ input: {},+ });+ expect(screen.snapshot()).toContain("Approve random_color?");++ renderer.requestInterrupt();+ await expect(approval).rejects.toThrow();++ const prompt = renderer.readPrompt();+ expect(screen.snapshot()).not.toContain("Approve random_color?");+ renderer.requestInterrupt();+ await expect(prompt).rejects.toThrow();+ renderer.shutdown();+ });+it("marks a tool block denied when the user rejects the approval", async () => {const { screen, input, renderer } = makeRenderer();await renderer.renderStream(diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex 31dec1ad7..1f03b7812 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -80,7 +80,6 @@ import {selectValueAtCursor,type SelectState,} from "#setup/cli/select-state.js";-import { renderCursorRow } from "#setup/cli/option-row.js";import type {AssistantResponseStatsMode,LogDisplayMode,@@ -150,7 +149,7 @@ import {} from "./tool-presentation.js";import { FileContentCache } from "./file-content-cache.js";import { groupToolBlocksForDisplay } from "./tool-block-groups.js";-import { renderQuestionPanel } from "./question-panel.js";+import { renderQuestionChoices, renderQuestionPanel } from "./question-panel.js";import { TurnClock } from "./turn-clock.js";import { MessageQueue, renderMessageQueueRows } from "./message-queue.js";import { formatStoredDiagnostic, presentDiagnostic } from "./diagnostic-presentation.js";@@ -589,8 +588,8 @@ export class TerminalRenderer implements AgentTUIRenderer {/** Monotonic id source — committed cycle ids must never be reused. */#devRebuildSequence = 0;#pendingEchoedPrompt?: string;- /** The open HITL question overlay, painted above the input area. */- #questionPanel?: (width: number) => string[];+ /** The open HITL drawer, painted above the input area. */+ #hitlDrawer?: (width: number) => ReturnType<typeof renderTransientDrawer>;#transientPanel?: (width: number) => ReturnType<typeof renderTransientDrawer>;#transientPanelClose?: () => void;/** The active setup flow's bordered panel: progress, question, status. */@@ -1290,11 +1289,46 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#stopTicker();this.#inputActive = false;this.#turnIndicator = { kind: "idle" };- this.#status = `Approve ${formatToolApprovalTitle(request)}? (y/n)`;this.#interrupted = false;+ let approvalCursor = 0;+ this.#hitlDrawer = (width) =>+ renderTransientDrawer(+ [+ ` ${this.#theme.colors.bold(`Approve ${formatToolApprovalTitle(request)}?`)}`,+ "",+ ...renderQuestionChoices(+ [+ { id: "yes", label: "Yes" },+ { id: "no", label: "No" },+ ],+ approvalCursor,+ this.#theme,+ ),+ ],+ ["y yes · n no · Ctrl-C cancel"],+ this.#theme,+ width,+ );this.#paint();return await new Promise((resolve, reject) => {+ const approve = () => {+ this.#hitlDrawer = undefined;+ this.#startWorking();+ this.#status = STATUS.processing;+ this.#detachInput();+ this.#paint();+ resolve({ approved: true });+ };+ const deny = () => {+ this.#hitlDrawer = undefined;+ this.#startWorking();+ this.#status = STATUS.processing;+ this.#markToolDenied(request.toolCallId);+ this.#detachInput();+ this.#paint();+ resolve({ approved: false, reason: "Denied by user." });+ };this.#rejectActiveReader = reject;this.#consumeKey = (key) => {switch (key.type) {@@ -1303,27 +1337,30 @@ export class TerminalRenderer implements AgentTUIRenderer {// accident; terminal framing is not an authentication signal.if (key.framing !== "unframed") break;const value = key.value.toLowerCase();- if (value === "y") {- this.#startWorking();- this.#status = STATUS.processing;- this.#detachInput();- this.#paint();- resolve({ approved: true });- } else if (value === "n") {- this.#startWorking();- this.#status = STATUS.processing;- this.#markToolDenied(request.toolCallId);- this.#detachInput();- this.#paint();- resolve({ approved: false, reason: "Denied by user." });- }+ if (value === "y") approve();+ else if (value === "n") deny();break;}+ case "up":+ case "ctrl-p":+ approvalCursor = 0;+ this.#paint();+ break;+ case "down":+ case "ctrl-n":+ approvalCursor = 1;+ this.#paint();+ break;+ case "enter":+ if (approvalCursor === 0) approve();+ else deny();+ break;case "ctrl-r":this.#paint();break;case "ctrl-c":this.#interrupted = true;+ this.#hitlDrawer = undefined;this.#stop();reject(interruptedError());break;@@ -1354,12 +1391,11 @@ export class TerminalRenderer implements AgentTUIRenderer {const totalRows = optionList.length + (hasFreeformRow ? 1 : 0);const sectionKey = questionSectionId(question.requestId);- // The overlay is the primary surface for option questions; text mode- // serves prompts without options. Esc (with nothing to clear) dismisses+ // Both question shapes use a drawer. Esc (with nothing to clear) dismisses// the question: it resolves `undefined`, the runner returns to the// prompt, and the server records the still-parked request as `ignored`// when the user's next message resumes the turn.- let mode: "overlay" | "text" = hasOptions ? "overlay" : "text";+ let mode: "select" | "text" = hasOptions ? "select" : "text";let cursorIndex = 0;let editor = EMPTY_LINE;@@ -1367,29 +1403,46 @@ export class TerminalRenderer implements AgentTUIRenderer {// The panel closure reads the mutable interaction state at paint time,// so key handlers only update it and repaint.- const overlayPanel = (width: number): string[] =>- renderQuestionPanel(- {- prompt: stripTerminalControls(question.prompt),- options: optionList,- cursor: cursorIndex,- allowFreeform: hasFreeformRow,- editor,- caretVisible: this.#caretVisible,- },+ const selectDrawer = (width: number) =>+ renderTransientDrawer(+ renderQuestionPanel(+ {+ prompt: stripTerminalControls(question.prompt),+ options: optionList,+ cursor: cursorIndex,+ allowFreeform: hasFreeformRow,+ editor,+ caretVisible: this.#caretVisible,+ },+ this.#theme,+ width,+ ),+ ["↑/↓ move · enter to select · esc to dismiss"],this.#theme,width,);- const renderTextSection = () => {- this.#upsertBlock({- id: sectionKey,- kind: "question",- title: stripTerminalControls(question.prompt),- body: formatQuestionContent(question, undefined, this.#theme),- preformatted: true,- live: true,+ const textPanel = (width: number) => {+ const inputRows = promptInputRows({+ text: editor.text,+ cursor: editor.cursor,+ width: Math.max(1, width - 2),+ theme: this.#theme,+ caretVisible: this.#caretVisible,+ ghost: "",+ maxRows: 3,});+ if (inputRows.at(-1) === "") inputRows.pop();+ return renderTransientDrawer(+ [+ ` ${this.#theme.colors.bold(stripTerminalControls(question.prompt))}`,+ "",+ ...inputRows.map((row) => ` ${row}`),+ ],+ ["Enter submit · Esc dismiss"],+ this.#theme,+ width,+ );};const syncFreeformCaret = () => {@@ -1401,11 +1454,11 @@ export class TerminalRenderer implements AgentTUIRenderer {}};- const enterOverlay = () => {- mode = "overlay";+ const enterSelectDrawer = () => {+ mode = "select";this.#inputActive = false;this.#removeBlock(sectionKey);- this.#questionPanel = overlayPanel;+ this.#hitlDrawer = selectDrawer;this.#status = "";syncFreeformCaret();this.#paint();@@ -1413,8 +1466,7 @@ export class TerminalRenderer implements AgentTUIRenderer {const enterTextMode = () => {mode = "text";- this.#questionPanel = undefined;- renderTextSection();+ this.#hitlDrawer = textPanel;this.#inputActive = true;this.#syncInput(editor);this.#status = "";@@ -1422,18 +1474,15 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();};- if (mode === "overlay") {- enterOverlay();- } else {- enterTextMode();- }+ if (mode === "select") enterSelectDrawer();+ else enterTextMode();const finalize = (resolved: {optionId?: string;text?: string;label: string;}): AgentTUIInputQuestionResponse => {- this.#questionPanel = undefined;+ this.#hitlDrawer = undefined;this.#upsertBlock({id: sectionKey,kind: "question",@@ -1457,7 +1506,7 @@ export class TerminalRenderer implements AgentTUIRenderer {// Dismissal resolves `undefined` — no answer travels and the question stays// open; the transcript records it compactly instead of keeping its options.const dismiss = () => {- this.#questionPanel = undefined;+ this.#hitlDrawer = undefined;this.#upsertBlock({id: sectionKey,kind: "question",@@ -1502,7 +1551,7 @@ export class TerminalRenderer implements AgentTUIRenderer {return;}this.#interrupted = true;- this.#questionPanel = undefined;+ this.#hitlDrawer = undefined;this.#stopCaretBlink();this.#stop();reject(interruptedError());@@ -1514,7 +1563,7 @@ export class TerminalRenderer implements AgentTUIRenderer {return;}- if (mode === "overlay") {+ if (mode === "select") {const textNavigation = setupSelectionIntent(key, {textNavigation: !isOnFreeformRow(),});@@ -1558,19 +1607,6 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#showCaret();this.#paint();}- break;- }- // A number press selects its row directly; the freeform row's- // number moves focus into its inline editor instead.- if (key.type === "text" && /^[1-9]$/u.test(key.value)) {- const rowIndex = Number(key.value) - 1;- if (rowIndex < optionList.length) {- selectOptionAt(rowIndex);- } else if (rowIndex === optionList.length && hasFreeformRow) {- cursorIndex = rowIndex;- syncFreeformCaret();- this.#paint();- }}break;}@@ -3276,6 +3312,7 @@ export class TerminalRenderer implements AgentTUIRenderer {};#stop() {+ this.#hitlDrawer = undefined;const closeTransientPanel = this.#transientPanelClose;if (closeTransientPanel !== undefined) {this.#transientPanelClose = undefined;@@ -4462,12 +4499,11 @@ export class TerminalRenderer implements AgentTUIRenderer {return [...drawer.rows, ...drawer.controls];}- // The HITL question overlay owns the footer down to the status bar —- // no indicator or hint row beneath it (the panel carries its own).- if (this.#questionPanel !== undefined) {- rows.push(...this.#questionPanel(width), "");- this.#pushStatusLine(rows, width);- return rows;+ // The HITL drawer opens one row below the transcript, then owns the+ // footer down to its controls with no status line beneath it.+ if (this.#hitlDrawer !== undefined) {+ const drawer = this.#hitlDrawer(width);+ return [...rows, ...drawer.rows, ...drawer.controls];}const flow = this.#setupFlow;@@ -4624,7 +4660,7 @@ export class TerminalRenderer implements AgentTUIRenderer {// Every waiting state — a streaming turn, a just-submitted prompt, a// question answer or approval resuming — shows the one live turn bar,// with the inert prompt anchored beneath it while a stream owns the- // turn. The `└ Done in …` coda is this bar's settled form.+ // turn. The `Done in … (↑ … ↓ …)` coda is this bar's settled form.const waitingOnStream = turnIndicator.kind === "waiting" && this.#flowlessStatus === undefined;if (this.#streamDraftActive || waitingOnStream) {rows.push(this.#streamingTurnBar(width));@@ -4681,20 +4717,14 @@ export class TerminalRenderer implements AgentTUIRenderer {return clip(`${marker} ${label}${tokens}`, width);}- /**- * The settled coda: `3min 24s ── ↑ 32.4K ↓ 682`, with token flow only once- * the turn has moved a token.- */+ /** The settled coda's duration and optional token flow. */#turnStatsBody(elapsedMs: number): string {- return `${formatTurnDuration(elapsedMs)}${this.#turnFlowSuffix()}`;- }-- /** ` ── ↑ 32.4K ↓ 682` once the turn has moved a token; empty before. */- #turnFlowSuffix(): string {const { inputTokens, outputTokens } = this.#turnClock.usage;- if (inputTokens === 0 && outputTokens === 0) return "";- const seg = this.#theme.glyph.dash.repeat(2);- return ` ${seg} ${formatTokenFlow({ inputTokens, outputTokens }, this.#theme.glyph)}`;+ const flow =+ inputTokens === 0 && outputTokens === 0+ ? ""+ : ` (${formatTokenFlow({ inputTokens, outputTokens }, this.#theme.glyph)})`;+ return `${formatTurnDuration(elapsedMs)}${flow}`;}/**@@ -5544,42 +5574,6 @@ function formatConnectionAuthContent(return lines.join("\n");}-function formatQuestionContent(- question: AgentTUIInputQuestion,- highlight: number | undefined,- theme: Theme,-): string {- const c = theme.colors;- const lines: string[] = [];- const options = question.options ?? [];-- if (options.length > 0) {- for (const [index, option] of options.entries()) {- const labelText = stripTerminalControls(option.label);- const descriptionText =- option.description === undefined ? "" : stripTerminalControls(option.description);- const selected = highlight === index;- const description =- descriptionText.length > 0- ? `${selected ? " " : " "}${c.dim(`— ${descriptionText}`)}`- : "";- const content = selected ? `${theme.glyph.selectedPointer} ${labelText}` : ` ${labelText}`;- const selection = renderCursorRow(content, selected, c);- lines.push(`${selection}${description}`);- }- if (question.allowFreeform === true) {- const selected = highlight === options.length;- const label = "Type your own answer";- const content = selected ? `${theme.glyph.selectedPointer} ${label}` : ` ${c.dim(label)}`;- lines.push(renderCursorRow(content, selected, c));- }- } else {- lines.push(c.dim(" (type your answer)"));- }-- return lines.join("\n");-}-function resolveQuestionText(rawText: string,question: AgentTUIInputQuestion,diff --git a/packages/eve/src/cli/dev/tui/theme.ts b/packages/eve/src/cli/dev/tui/theme.tsindex 08c217c23..c9949ed28 100644--- a/packages/eve/src/cli/dev/tui/theme.ts+++ b/packages/eve/src/cli/dev/tui/theme.ts@@ -103,7 +103,7 @@ export interface ThemeGlyphs {elbow: string;/** `▔` — strong full-width rule opening the bottom question panel. */hrule: string;- /** `─` — light rule segment framing the end-of-turn stats line. */+ /** `─` — light rule segment framing drawers and panel boundaries. */dash: string;/** `▏` — the synthetic input caret. */caret: string;diff --git a/packages/eve/test/tui-client/tui-questions-freeform.ts b/packages/eve/test/tui-client/tui-questions-freeform.tsindex 669a1f741..ce1b97d2b 100644--- a/packages/eve/test/tui-client/tui-questions-freeform.ts+++ b/packages/eve/test/tui-client/tui-questions-freeform.ts@@ -1,4 +1,3 @@-import { Buffer } from "node:buffer";import { setTimeout as sleep } from "node:timers/promises";import { Client } from "eve/client";@@ -48,17 +47,17 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {input.type(promptLines.join(" · "));input.enter();- await screen.waitForText("› 1. Production", 60_000);- console.log(theme.muted("[tui-freeform] select UI live, highlight on Production"));+ await screen.waitForText("↑/↓ move · enter to select · esc to dismiss", 60_000);+ console.log(theme.muted("[tui-freeform] select drawer is live"));- await sleep(500);+ await sleep(1_000);// Navigate past every predefined option to the freeform row.- input.emit("data", Buffer.from("\x1B[B")); // → Staging- input.emit("data", Buffer.from("\x1B[B")); // → Preview- input.emit("data", Buffer.from("\x1B[B")); // → Type your own answer- await screen.waitForText("› 4. Type your own answer", 2_000);- console.log(theme.muted("[tui-freeform] highlight moved to freeform row"));+ input.down(); // → Staging+ input.down(); // → Preview+ input.down(); // → Type your own answer+ await screen.waitForText("Type your own answer", 2_000);+ console.log(theme.muted("[tui-freeform] moved to freeform row"));// The freeform row focuses its inline elbow editor the moment the cursor// reaches it — typing lands there directly, no Enter required.diff --git a/packages/eve/test/tui-client/tui-questions.ts b/packages/eve/test/tui-client/tui-questions.tsindex 00998c419..0815cef0e 100644--- a/packages/eve/test/tui-client/tui-questions.ts+++ b/packages/eve/test/tui-client/tui-questions.ts@@ -1,4 +1,3 @@-import { Buffer } from "node:buffer";import { setTimeout as sleep } from "node:timers/promises";import { Client } from "eve/client";@@ -18,8 +17,8 @@ import { theme } from "./lib/theme.ts";* 2. Boot an `EveTUIRunner` with a mock terminal.* 3. Type a prompt that asks the model to call `ask_question` with* two options (Red/Blue).- * 4. Wait for the question overlay to display the numbered select- * indicator (`› 1. <label>`), which proves the question UI is up.+ * 4. Wait for the question drawer's control row, which proves it is ready+ * for input.* 5. Send Down arrow + Enter to pick the second option (blue).* 6. Wait for the answered marker (`⎿ <label>`) in the transcript.* 7. Wait for the post-answer assistant turn to render. The runner@@ -58,20 +57,18 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {input.type(promptLines.join(" · "));input.enter();- await screen.waitForText("› 1. Red", 60_000);- console.log(theme.muted("[tui-questions] select UI is live, highlight on Red"));+ await screen.waitForText("↑/↓ move · enter to select · esc to dismiss", 60_000);+ console.log(theme.muted("[tui-questions] select drawer is live"));// Bridges a server-side race where the park hook isn't yet// registered when `session.waiting` reaches the client. The TUI// is human-paced in practice; scripted clients need a short// handshake delay before delivering the response.- await sleep(500);-- input.emit("data", Buffer.from("\x1B[B"));- await screen.waitForText("› 2. Blue", 2_000);- console.log(theme.muted("[tui-questions] highlight moved to Blue"));+ await sleep(1_000);+ input.down();input.enter();+ console.log(theme.muted("[tui-questions] selected Blue"));await screen.waitForText("⎿ Blue", 5_000);console.log(theme.muted("[tui-questions] answer recorded in body"));