Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): multi-line input in the dev TUI prompt (#67)

Ruid22fd0477f01
diff --git a/.changeset/tui-ctrlc-clears-prompt.md b/.changeset/tui-ctrlc-clears-prompt.md
new file mode 100644
index 000000000..9b4ecbf22
--- /dev/null
+++ b/.changeset/tui-ctrlc-clears-prompt.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+In the dev TUI, Ctrl+C now clears a non-empty chat or freeform `ask_question` prompt instead of quitting. On an empty prompt it still quits, and during a running turn it still interrupts.
diff --git a/.changeset/tui-multiline-paste-bracketed.md b/.changeset/tui-multiline-paste-bracketed.md
new file mode 100644
index 000000000..742b19d94
--- /dev/null
+++ b/.changeset/tui-multiline-paste-bracketed.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The dev TUI prompt now takes multi-line input in both chat and freeform `ask_question` fields. Pasting multi-line text inserts it intact instead of submitting at the first line, `Shift+Enter` inserts a newline, a tall prompt scrolls within the terminal height, and editing moves by whole graphemes so wide and emoji characters aren't split.
diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.md
index e306f5d21..40cc7f3c1 100644
--- a/docs/guides/dev-tui.md
+++ b/docs/guides/dev-tui.md
@@ -58,18 +58,21 @@ The provider row demands attention (a bold yellow "Configure provider" with "Req
## Keyboard shortcuts
-The prompt input behaves like a shell line editor.
+Chat and freeform `ask_question` inputs behave like a shell line editor.
| Key | Action |
| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
-| `Enter` | Send the message. |
-| `Ctrl+C` | Interrupt a running turn, or quit at the prompt. |
-| `↑` / `↓` | Cycle through the messages you have sent this session. |
-| `←` / `→`, `Home` / `End`, `Ctrl+A` / `Ctrl+E` | Move the caret. |
-| `Ctrl+U` / `Ctrl+K` / `Ctrl+W` | Kill the whole line, the rest of the line, or the previous word. |
+| `Enter` | Submit the message or question response. |
+| `Shift+Enter` | Insert a newline without sending (needs a terminal that reports modified keys). |
+| `Ctrl+C` | Interrupt a running turn. At the chat or freeform-question prompt, clear non-empty input; when empty, quit. |
+| `↑` / `↓` | Move between input lines; at a chat-buffer edge, navigate messages you have sent this session. |
+| `←` / `→`, `Home` / `End`, `Ctrl+A` / `Ctrl+E` | Move the caret; Home/End stay within the current line. |
+| `Ctrl+U` / `Ctrl+K` / `Ctrl+W` | Delete to the start of the line, to its end, or through the previous word. |
| `Ctrl+L` | Cycle the log display mode (`none → all → stderr → sandbox → none`) and briefly show the mode in the status line. |
| `Ctrl+R` | Redraw the screen. |
+In terminals that support bracketed paste, pasting multi-line text into chat or a freeform question inserts it intact and renders one row per line rather than submitting at the first line. `Shift+Enter` adds a line by hand. The input grows down to the available terminal height, then scrolls to keep the caret visible; `Enter` submits the whole response.
+
If a turn fails terminally (the server session dies or the connection drops), the TUI starts a fresh session and notes it inline so you can keep going. Server-side context resets with the old session.
## Answer the agent inline
@@ -77,7 +80,7 @@ If a turn fails terminally (the server session dies or the connection drops), th
When the agent needs something from you, the TUI asks inline.
- Tool approvals are a `y` or `n`.
-- Option questions let you pick with `↑` / `↓` and `Enter`, or you can type a freeform answer.
+- Option questions let you pick with `↑` / `↓` and `Enter`, or you can compose a multi-line freeform answer.
- If a tool needs an authorized [connection](../connections), the URL shows up right in the transcript, and the turn picks back up once you finish the flow.
## Control what logs show
diff --git a/packages/eve/src/cli/dev/tui/line-editor.test.ts b/packages/eve/src/cli/dev/tui/line-editor.test.ts
index 1a41b090d..fe738e3f6 100644
--- a/packages/eve/src/cli/dev/tui/line-editor.test.ts
+++ b/packages/eve/src/cli/dev/tui/line-editor.test.ts
@@ -9,10 +9,12 @@ import {
insert,
killToEnd,
killToStart,
+ layoutPromptInput,
lineOf,
moveEnd,
moveHome,
moveLeft,
+ movePromptLine,
moveRight,
visibleLine,
} from "./line-editor.js";
@@ -25,11 +27,46 @@ describe("line editing", () => {
expect(line).toEqual({ text: "hello", cursor: 4 });
});
+ it("allows newlines only in multiline inputs", () => {
+ const paste = { type: "text", value: "one\ntwo", framing: "bracketed-paste" } as const;
+ expect(applyLineEditorKey(lineOf(""), paste, { multiline: true })).toEqual({
+ text: "one\ntwo",
+ cursor: 7,
+ });
+ expect(applyLineEditorKey(lineOf(""), paste)).toEqual({ text: "one two", cursor: 7 });
+ expect(applyLineEditorKey(lineOf("a"), { type: "newline" }, { multiline: true })).toEqual({
+ text: "a\n",
+ cursor: 2,
+ });
+ expect(applyLineEditorKey(lineOf("a"), { type: "newline" })).toBeUndefined();
+ });
+
it("backspaces the character before the caret", () => {
const line = backspace({ text: "abc", cursor: 2 });
expect(line).toEqual({ text: "ac", cursor: 1 });
});
+ it("moves and deletes by grapheme instead of UTF-16 code unit", () => {
+ const family = "👨‍👩‍👧‍👦";
+ const text = `A${family}B`;
+ const beforeB = 1 + family.length;
+
+ expect(moveLeft({ text, cursor: beforeB })).toEqual({ text, cursor: 1 });
+ expect(moveRight({ text, cursor: 1 })).toEqual({ text, cursor: beforeB });
+ expect(backspace({ text, cursor: beforeB })).toEqual({ text: "AB", cursor: 1 });
+ expect(deleteForward({ text, cursor: 1 })).toEqual({ text: "AB", cursor: 1 });
+
+ const accented = "Ae\u0301B";
+ expect(backspace({ text: accented, cursor: 3 })).toEqual({ text: "AB", cursor: 1 });
+ });
+
+ it("keeps the cursor on a grapheme boundary when insertion joins characters", () => {
+ expect(insert({ text: "👨👩", cursor: 2 }, "\u200d")).toEqual({
+ text: "👨‍👩",
+ cursor: 5,
+ });
+ });
+
it("backspace at the start is a no-op", () => {
const line = { text: "abc", cursor: 0 };
expect(backspace(line)).toBe(line);
@@ -50,11 +87,18 @@ describe("line editing", () => {
it("jumps home and end", () => {
expect(moveHome({ text: "abc", cursor: 2 })).toEqual({ text: "abc", cursor: 0 });
expect(moveEnd({ text: "abc", cursor: 0 })).toEqual({ text: "abc", cursor: 3 });
+ expect(moveHome({ text: "\nsecond", cursor: 0 })).toEqual({ text: "\nsecond", cursor: 0 });
+ expect(moveHome({ text: "one\ntwo", cursor: 6 })).toEqual({ text: "one\ntwo", cursor: 4 });
+ expect(moveEnd({ text: "one\ntwo", cursor: 1 })).toEqual({ text: "one\ntwo", cursor: 3 });
});
it("kills to the end and to the start", () => {
expect(killToEnd({ text: "hello world", cursor: 5 })).toEqual({ text: "hello", cursor: 5 });
expect(killToStart({ text: "hello world", cursor: 6 })).toEqual({ text: "world", cursor: 0 });
+ expect(killToEnd({ text: "one\ntwo", cursor: 0 })).toEqual({ text: "\ntwo", cursor: 0 });
+ expect(killToEnd({ text: "one\ntwo", cursor: 3 })).toEqual({ text: "one\ntwo", cursor: 3 });
+ expect(killToStart({ text: "one\ntwo", cursor: 7 })).toEqual({ text: "one\n", cursor: 4 });
+ expect(killToStart({ text: "one\ntwo", cursor: 4 })).toEqual({ text: "one\ntwo", cursor: 4 });
});
it("deletes the previous word", () => {
@@ -65,10 +109,17 @@ describe("line editing", () => {
expect(deleteWord({ text: "trailing ", cursor: 11 })).toEqual({ text: "", cursor: 0 });
});
+ it("bounds delete-word to the current line", () => {
+ // Deletes within the current line, leaving the newline and the line above.
+ expect(deleteWord({ text: "one\ntwo", cursor: 7 })).toEqual({ text: "one\n", cursor: 4 });
+ // At the start of a line there is nothing on it to delete; no line merge.
+ expect(deleteWord({ text: "one\ntwo", cursor: 4 })).toEqual({ text: "one\ntwo", cursor: 4 });
+ });
+
it("routes editing keys while leaving controller keys unhandled", () => {
const line = { text: "abc", cursor: 1 };
- expect(applyLineEditorKey(line, { type: "character", value: "X" })).toEqual({
+ expect(applyLineEditorKey(line, { type: "text", value: "X", framing: "unframed" })).toEqual({
text: "aXbc",
cursor: 2,
});
@@ -83,13 +134,26 @@ describe("line editing", () => {
describe("visibleLine", () => {
it("shows the whole line when it fits, split at the caret", () => {
- expect(visibleLine({ text: "hello", cursor: 2 }, 80)).toEqual({ before: "he", after: "llo" });
+ expect(visibleLine({ text: "hello", cursor: 2 }, 80)).toEqual({
+ before: "he",
+ under: "l",
+ after: "lo",
+ });
+ });
+
+ it("keeps the grapheme under the caret intact", () => {
+ expect(visibleLine({ text: "A👨‍👩‍👧‍👦B", cursor: 1 }, 80)).toEqual({
+ before: "A",
+ under: "👨‍👩‍👧‍👦",
+ after: "B",
+ });
});
it("windows a long line and keeps the caret visible", () => {
const text = "0123456789abcdef";
const { before, after } = visibleLine({ text, cursor: text.length }, 6, "…");
- const visible = before + after;
+ const { under } = visibleLine({ text, cursor: text.length }, 6, "…");
+ const visible = before + under + after;
expect(visible.length).toBe(6);
// Caret sits at the end of the window; the truncated head is marked.
expect(after).toBe("");
@@ -98,9 +162,9 @@ describe("visibleLine", () => {
it("marks a truncated tail when the caret is near the start", () => {
const text = "0123456789abcdef";
- const { before, after } = visibleLine({ text, cursor: 0 }, 6, "…");
+ const { before, under, after } = visibleLine({ text, cursor: 0 }, 6, "…");
expect(before).toBe("");
- expect((before + after).endsWith("…")).toBe(true);
+ expect((before + under + after).endsWith("…")).toBe(true);
});
});
@@ -133,3 +197,65 @@ describe("PromptHistory", () => {
expect(history.previous("hello")).toBeUndefined();
});
});
+
+describe("layoutPromptInput", () => {
+ it("keeps a short single line as one row with the caret in place", () => {
+ const layout = layoutPromptInput({ text: "hello", cursor: 2 });
+ expect(layout.rows).toEqual([{ text: "hello", start: 0 }]);
+ expect({ caretRow: layout.caretRow, caretOffset: layout.caretOffset }).toEqual({
+ caretRow: 0,
+ caretOffset: 2,
+ });
+ });
+
+ it("breaks on embedded newlines, one row per logical line", () => {
+ const layout = layoutPromptInput({ text: "ab\ncd", cursor: 4 });
+ expect(layout.rows).toEqual([
+ { text: "ab", start: 0 },
+ { text: "cd", start: 3 },
+ ]);
+ // Cursor 4 is the "d": second row (start 3), offset 1.
+ expect({ caretRow: layout.caretRow, caretOffset: layout.caretOffset }).toEqual({
+ caretRow: 1,
+ caretOffset: 1,
+ });
+ });
+
+ it("places the caret at the end of a line when it sits on the newline", () => {
+ const layout = layoutPromptInput({ text: "ab\ncd", cursor: 2 });
+ expect({ caretRow: layout.caretRow, caretOffset: layout.caretOffset }).toEqual({
+ caretRow: 0,
+ caretOffset: 2,
+ });
+ });
+
+ it("keeps blank lines as their own row", () => {
+ const layout = layoutPromptInput({ text: "a\n\nb", cursor: 3 });
+ expect(layout.rows).toEqual([
+ { text: "a", start: 0 },
+ { text: "", start: 2 },
+ { text: "b", start: 3 },
+ ]);
+ expect(layout.caretRow).toBe(2);
+ });
+
+ it("does not wrap a long line; it stays one row for the renderer to clip", () => {
+ const layout = layoutPromptInput({ text: "abcdefgh", cursor: 5 });
+ expect(layout.rows).toEqual([{ text: "abcdefgh", start: 0 }]);
+ expect({ caretRow: layout.caretRow, caretOffset: layout.caretOffset }).toEqual({
+ caretRow: 0,
+ caretOffset: 5,
+ });
+ });
+
+ it("moves between rows by terminal column without splitting graphemes", () => {
+ expect(movePromptLine({ text: "界x\nab", cursor: 5 }, "up")).toEqual({
+ text: "界x\nab",
+ cursor: 1,
+ });
+ expect(movePromptLine({ text: "e\u0301x\nab", cursor: 6 }, "up")).toEqual({
+ text: "e\u0301x\nab",
+ cursor: 3,
+ });
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/line-editor.ts b/packages/eve/src/cli/dev/tui/line-editor.ts
index c6578cc35..65d2a7654 100644
--- a/packages/eve/src/cli/dev/tui/line-editor.ts
+++ b/packages/eve/src/cli/dev/tui/line-editor.ts
@@ -1,23 +1,34 @@
/**
* A tiny, dependency-free line-editing model for the prompt input.
*
- * The renderer owns the terminal; this module owns the *text* — a single
- * logical line plus a caret position — and exposes pure transforms for the
- * common readline-style edits (insert, delete, word/line kill, cursor moves)
- * and a {@link visibleLine} helper that windows a long line around the caret
- * so it stays on screen. Keeping it pure makes the editing rules trivial to
- * unit test without a TTY.
+ * The renderer owns the terminal; this module owns the *text* — buffer plus
+ * caret position, where the buffer may carry embedded newlines — and exposes
+ * pure transforms for the common readline-style edits (insert, delete,
+ * word/line kill, cursor moves), a {@link visibleLine} helper that windows a
+ * long line around the caret, and {@link layoutPromptInput} which splits a
+ * multi-line buffer into logical rows. Keeping it pure makes the editing rules
+ * trivial to unit test without a TTY.
*/
import type { TerminalKey } from "./stream-format.js";
+import {
+ graphemeBoundaryAtOrAfter,
+ graphemes,
+ nextGraphemeBoundary,
+ previousGraphemeBoundary,
+} from "#shared/text-boundaries.js";
+import { inputTextWidth, offsetAtVisibleColumn } from "./terminal-text.js";
-/** One logical input line: its text and the caret's index within it. */
+/**
+ * Editor text and a caret at a grapheme boundary, represented as a UTF-16
+ * offset so it can be passed directly to `String.slice`.
+ */
export interface LineState {
readonly text: string;
readonly cursor: number;
}
-/** The empty line with the caret at column 0. */
+/** The empty editor buffer with the caret at offset 0. */
export const EMPTY_LINE: LineState = { text: "", cursor: 0 };
/** Builds a line from `text` with the caret placed at the end. */
@@ -29,74 +40,125 @@ export function lineOf(text: string): LineState {
export function insert(state: LineState, value: string): LineState {
if (value.length === 0) return state;
const text = state.text.slice(0, state.cursor) + value + state.text.slice(state.cursor);
- return { text, cursor: state.cursor + value.length };
+ const cursor = graphemeBoundaryAtOrAfter(text, state.cursor + value.length);
+ return { text, cursor };
}
-/** Deletes the character before the caret (Backspace). */
+/** Deletes the grapheme before the caret (Backspace). */
export function backspace(state: LineState): LineState {
if (state.cursor === 0) return state;
- const text = state.text.slice(0, state.cursor - 1) + state.text.slice(state.cursor);
- return { text, cursor: state.cursor - 1 };
+ const cursor = previousGraphemeBoundary(state.text, state.cursor);
+ const text = state.text.slice(0, cursor) + state.text.slice(state.cursor);
+ return { text, cursor: graphemeBoundaryAtOrAfter(text, cursor) };
}
-/** Deletes the character at the caret (Delete / Ctrl+D mid-line). */
+/** Deletes the grapheme at the caret (Delete / Ctrl+D mid-line). */
export function deleteForward(state: LineState): LineState {
if (state.cursor >= state.text.length) return state;
- const text = state.text.slice(0, state.cursor) + state.text.slice(state.cursor + 1);
- return { text, cursor: state.cursor };
+ const end = nextGraphemeBoundary(state.text, state.cursor);
+ const text = state.text.slice(0, state.cursor) + state.text.slice(end);
+ return { text, cursor: graphemeBoundaryAtOrAfter(text, state.cursor) };
}
-/** Moves the caret one column left. */
+/** Moves the caret one grapheme left. */
export function moveLeft(state: LineState): LineState {
- return state.cursor === 0 ? state : { text: state.text, cursor: state.cursor - 1 };
+ return state.cursor === 0
+ ? state
+ : { text: state.text, cursor: previousGraphemeBoundary(state.text, state.cursor) };
}
-/** Moves the caret one column right. */
+/** Moves the caret one grapheme right. */
export function moveRight(state: LineState): LineState {
- return state.cursor >= state.text.length ? state : { text: state.text, cursor: state.cursor + 1 };
+ return state.cursor >= state.text.length
+ ? state
+ : { text: state.text, cursor: nextGraphemeBoundary(state.text, state.cursor) };
}
/** Moves the caret to the start of the line (Home / Ctrl+A). */
export function moveHome(state: LineState): LineState {
- return state.cursor === 0 ? state : { text: state.text, cursor: 0 };
+ const cursor = logicalLineStart(state.text, state.cursor);
+ return state.cursor === cursor ? state : { text: state.text, cursor };
}
/** Moves the caret to the end of the line (End / Ctrl+E). */
export function moveEnd(state: LineState): LineState {
- return state.cursor === state.text.length
- ? state
- : { text: state.text, cursor: state.text.length };
+ const cursor = logicalLineEnd(state.text, state.cursor);
+ return state.cursor === cursor ? state : { text: state.text, cursor };
}
/** Deletes from the caret to the end of the line (Ctrl+K). */
export function killToEnd(state: LineState): LineState {
- if (state.cursor >= state.text.length) return state;
- return { text: state.text.slice(0, state.cursor), cursor: state.cursor };
+ const lineEnd = logicalLineEnd(state.text, state.cursor);
+ if (state.cursor >= lineEnd) return state;
+ return {
+ text: state.text.slice(0, state.cursor) + state.text.slice(lineEnd),
+ cursor: state.cursor,
+ };
}
/** Deletes from the start of the line to the caret (Ctrl+U). */
export function killToStart(state: LineState): LineState {
- if (state.cursor === 0) return state;
- return { text: state.text.slice(state.cursor), cursor: 0 };
+ const lineStart = logicalLineStart(state.text, state.cursor);
+ if (state.cursor <= lineStart) return state;
+ return {
+ text: state.text.slice(0, lineStart) + state.text.slice(state.cursor),
+ cursor: lineStart,
+ };
}
/** Deletes the whitespace-delimited word before the caret (Ctrl+W). */
export function deleteWord(state: LineState): LineState {
if (state.cursor === 0) return state;
+ // Bound to the current logical line, like killToEnd/killToStart: Ctrl+W stops
+ // at the line start instead of reaching up and merging the line above.
+ const lineStart = logicalLineStart(state.text, state.cursor);
let start = state.cursor;
- while (start > 0 && isWhitespace(state.text[start - 1])) start -= 1;
- while (start > 0 && !isWhitespace(state.text[start - 1])) start -= 1;
- return { text: state.text.slice(0, start) + state.text.slice(state.cursor), cursor: start };
+ while (start > lineStart) {
+ const previous = previousGraphemeBoundary(state.text, start);
+ if (!isWhitespace(state.text.slice(previous, start))) break;
+ start = previous;
+ }
+ while (start > lineStart) {
+ const previous = previousGraphemeBoundary(state.text, start);
+ if (isWhitespace(state.text.slice(previous, start))) break;
+ start = previous;
+ }
+ const text = state.text.slice(0, start) + state.text.slice(state.cursor);
+ return { text, cursor: graphemeBoundaryAtOrAfter(text, start) };
+}
+
+function logicalLineStart(text: string, cursor: number): number {
+ if (cursor === 0) return 0;
+ return text.lastIndexOf("\n", cursor - 1) + 1;
+}
+
+function logicalLineEnd(text: string, cursor: number): number {
+ const newline = text.indexOf("\n", cursor);
+ return newline === -1 ? text.length : newline;
+}
+
+/** Options for {@link applyLineEditorKey}. */
+interface LineEditorOptions {
+ /** Single-line inputs flatten pasted newlines and ignore Shift+Enter. */
+ readonly multiline?: boolean;
}
/**
- * Applies a key owned by the single-line editor. Returns `undefined` when the
- * key belongs to the surrounding controller (submit, cancel, history, menus).
+ * Applies a key owned by the line editor. Returns `undefined` when the key
+ * belongs to the surrounding controller (submit, cancel, history, menus), which
+ * on a single-line input includes Shift+Enter.
*/
-export function applyLineEditorKey(state: LineState, key: TerminalKey): LineState | undefined {
+export function applyLineEditorKey(
+ state: LineState,
+ key: TerminalKey,
+ options?: LineEditorOptions,
+): LineState | undefined {
+ const multiline = options?.multiline ?? false;
switch (key.type) {
- case "character":
- return insert(state, key.value);
+ case "text":
+ return insert(state, multiline ? key.value : key.value.replaceAll("\n", " "));
+ case "newline":
+ return multiline ? insert(state, "\n") : undefined;
case "backspace":
return backspace(state);
case "delete":
@@ -122,46 +184,123 @@ export function applyLineEditorKey(state: LineState, key: TerminalKey): LineStat
}
}
-function isWhitespace(char: string | undefined): boolean {
- return char !== undefined && /\s/u.test(char);
+function isWhitespace(text: string): boolean {
+ return /^\s+$/u.test(text);
}
/**
* The portion of `state.text` to draw within `budget` columns, split at the
- * caret so the renderer can place its caret glyph between `before` and
- * `after`. When the line is wider than `budget` it is windowed around the
- * caret, marking truncated ends with `…` so the caret is always visible.
+ * caret so the renderer can highlight `under` without slicing a grapheme.
+ * When the line is wider than `budget` it is windowed around the caret,
+ * marking truncated ends with `…` so the caret is always visible.
*/
-export interface VisibleLine {
+interface VisibleLine {
readonly before: string;
+ readonly under: string;
readonly after: string;
}
export function visibleLine(state: LineState, budget: number, ellipsis = "…"): VisibleLine {
const width = Math.max(1, budget);
const { text, cursor } = state;
+ const segments = graphemes(text);
+ const caretIndex = segments.findIndex((segment) => segment.start === cursor);
+ const underIndex = caretIndex === -1 ? segments.length : caretIndex;
+ const under = segments[underIndex]?.text ?? "";
- if (text.length <= width) {
- return { before: text.slice(0, cursor), after: text.slice(cursor) };
+ if (inputTextWidth(text) <= width) {
+ return {
+ before: text.slice(0, cursor),
+ under,
+ after: text.slice(cursor + under.length),
+ };
}
- // Window the line so the caret stays on screen, keeping a little context
- // ahead of the caret when scrolling right.
- let start = cursor < width ? 0 : cursor - width + 1;
- start = Math.min(start, text.length - width);
- start = Math.max(0, start);
- const end = start + width;
-
- let visible = text.slice(start, end);
- const rel = cursor - start;
- if (start > 0 && rel > 0) {
- visible = ellipsis + visible.slice(ellipsis.length);
+ let start = underIndex;
+ let end = underIndex + (under.length > 0 ? 1 : 0);
+ const windowWidth = (candidateStart: number, candidateEnd: number): number => {
+ const startOffset = segments[candidateStart]?.start ?? text.length;
+ const endOffset = segments[candidateEnd]?.start ?? text.length;
+ return (
+ inputTextWidth(text.slice(startOffset, endOffset)) +
+ (candidateStart > 0 ? inputTextWidth(ellipsis) : 0) +
+ (candidateEnd < segments.length ? inputTextWidth(ellipsis) : 0)
+ );
+ };
+
+ let preferBefore = true;
+ while (true) {
+ const beforeFits = start > 0 && windowWidth(start - 1, end) <= width;
+ const afterFits = end < segments.length && windowWidth(start, end + 1) <= width;
+ if (!beforeFits && !afterFits) break;
+ if ((preferBefore && beforeFits) || !afterFits) start -= 1;
+ else end += 1;
+ preferBefore = !preferBefore;
}
- if (end < text.length && rel < visible.length) {
- visible = visible.slice(0, visible.length - ellipsis.length) + ellipsis;
+
+ const startOffset = segments[start]?.start ?? text.length;
+ const endOffset = segments[end]?.start ?? text.length;
+ return {
+ before: `${start > 0 ? ellipsis : ""}${text.slice(startOffset, cursor)}`,
+ under,
+ after: `${text.slice(cursor + under.length, endOffset)}${end < segments.length ? ellipsis : ""}`,
+ };
+}
+
+/** One logical prompt row and the UTF-16 offset where it starts in the buffer. */
+interface PromptLogicalRow {
+ readonly text: string;
+ readonly start: number;
+}
+
+/**
+ * A multi-line prompt split into logical rows. `caretRow` indexes {@link rows};
+ * `caretOffset` is a UTF-16 offset within that row.
+ */
+interface PromptLayout {
+ readonly rows: PromptLogicalRow[];
+ readonly caretRow: number;
+ readonly caretOffset: number;
+}
+
+/**
+ * Splits a prompt buffer on newlines and locates the caret. This function does
+ * not measure terminal columns or wrap rows; the renderer windows each logical
+ * row to the available width.
+ */
+export function layoutPromptInput(state: LineState): PromptLayout {
+ const rows: PromptLogicalRow[] = [];
+ let caretRow = 0;
+ let caretOffset = 0;
+
+ let start = 0;
+ for (const text of state.text.split("\n")) {
+ // The caret sits on this line when it falls within [start, start + length];
+ // the next line begins one past the "\n", so the ranges never overlap.
+ if (state.cursor >= start && state.cursor <= start + text.length) {
+ caretRow = rows.length;
+ caretOffset = state.cursor - start;
+ }
+ rows.push({ text, start });
+ start += text.length + 1; // + 1 for the "\n" that split removed
}
- return { before: visible.slice(0, rel), after: visible.slice(rel) };
+ return { rows, caretRow, caretOffset };
+}
+
+/** Moves to the adjacent logical line while preserving the terminal column where possible. */
+export function movePromptLine(state: LineState, direction: "up" | "down"): LineState | undefined {
+ const layout = layoutPromptInput(state);
+ const targetRow = direction === "up" ? layout.caretRow - 1 : layout.caretRow + 1;
+ if (targetRow < 0 || targetRow >= layout.rows.length) return undefined;
+
+ const current = layout.rows[layout.caretRow]!;
+ const target = layout.rows[targetRow]!;
+ const column = inputTextWidth(current.text.slice(0, layout.caretOffset));
+ return {
+ text: state.text,
+ cursor: target.start + offsetAtVisibleColumn(target.text, column),
+ };
}
/**
diff --git a/packages/eve/src/cli/dev/tui/live-region.ts b/packages/eve/src/cli/dev/tui/live-region.ts
index 2aa311aad..3015383a3 100644
--- a/packages/eve/src/cli/dev/tui/live-region.ts
+++ b/packages/eve/src/cli/dev/tui/live-region.ts
@@ -29,6 +29,8 @@ const CLEAR_SCROLLBACK = `${ESC}[3J`;
const CURSOR_HOME = `${ESC}[H`;
const SYNC_START = `${ESC}[?2026h`;
const SYNC_END = `${ESC}[?2026l`;
+const BRACKETED_PASTE_ON = `${ESC}[?2004h`;
+const BRACKETED_PASTE_OFF = `${ESC}[?2004l`;
export interface LiveRegionOutput {
write(chunk: string): boolean;
@@ -59,6 +61,11 @@ export class LiveRegion {
this.#write(SHOW_CURSOR);
}
+ /** Toggles bracketed paste through the original write, bypassing foreign-output capture. */
+ emitBracketedPaste(enabled: boolean): void {
+ this.#write(enabled ? BRACKETED_PASTE_ON : BRACKETED_PASTE_OFF);
+ }
+
/** Writes a newline through the bound (original) write. */
newline(): void {
this.#write("\n");
diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.ts
index 4d60e066e..b44c947e6 100644
--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts
@@ -657,16 +657,17 @@ describe("renderTextQuestion", () => {
expect(rows[1]).toBe(" New project name");
});
- it("masks the typed value", () => {
+ it("masks one bullet per grapheme", () => {
const text = renderTextQuestion(
- { message: "API key", editor: lineOf("secret"), mask: true },
+ { message: "API key", editor: lineOf("e\u0301👨‍👩‍👧‍👦"), mask: true },
theme,
60,
false,
).join("\n");
- expect(text).toContain("••••••");
- expect(text).not.toContain("secret");
+ expect(text).toContain("••");
+ expect(text).not.toContain("•••");
+ expect(text).not.toContain("👨");
});
});
diff --git a/packages/eve/src/cli/dev/tui/setup-panel.ts b/packages/eve/src/cli/dev/tui/setup-panel.ts
index 1083167a2..07a01f20a 100644
--- a/packages/eve/src/cli/dev/tui/setup-panel.ts
+++ b/packages/eve/src/cli/dev/tui/setup-panel.ts
@@ -18,19 +18,14 @@ import type { ChannelSetupAction, PromptOption } from "#setup/cli/index.js";
import { renderOptionRow, resolveOptionRowState } from "#setup/cli/option-row.js";
import { filterOptions, submitRowIndex, type SelectState } from "#setup/cli/select-state.js";
import type { SelectNotice } from "#setup/prompter.js";
+import { graphemes } from "#shared/text-boundaries.js";
import { visibleLine, type LineState } from "./line-editor.js";
import type { Theme } from "./theme.js";
-import { sliceVisible, visibleLength, wrapVisibleLine } from "./terminal-text.js";
+import { clipVisible, renderInputText, visibleLength, wrapVisibleLine } from "./terminal-text.js";
function clip(line: string, width: number): string {
- if (visibleLength(line) <= width) {
- return line;
- }
- const sliced = sliceVisible(line, width);
- // Truncation can cut a color span before its close; reset so the open
- // style cannot bleed into every row painted below.
- return sliced.includes("\x1b[") ? `${sliced}\x1b[0m` : sliced;
+ return clipVisible(line, width);
}
/** One row of a setup select panel; the shared prompt-option shape. */
@@ -626,14 +621,17 @@ export function renderTextQuestion(
const budget = Math.max(4, width - 4);
const display = state.mask
- ? { text: "•".repeat(state.editor.text.length), cursor: state.editor.cursor }
+ ? {
+ text: "•".repeat(graphemes(state.editor.text).length),
+ cursor: graphemes(state.editor.text.slice(0, state.editor.cursor)).length,
+ }
: { text: state.editor.text, cursor: state.editor.cursor };
- const { before, after } = visibleLine(display, budget, theme.glyph.ellipsis);
+ const { before, under, after } = visibleLine(display, budget, theme.glyph.ellipsis);
const caret = caretVisible ? c.cyan(theme.glyph.caret) : " ";
const body =
state.editor.text.length === 0 && state.placeholder !== undefined
? `${caret}${c.dim(state.placeholder)}`
- : `${before}${caret}${after}`;
+ : `${renderInputText(before)}${caret}${renderInputText(under)}${renderInputText(after)}`;
rows.push(` ${body}`);
if (state.error !== undefined) {
diff --git a/packages/eve/src/cli/dev/tui/setup-selection-input.test.ts b/packages/eve/src/cli/dev/tui/setup-selection-input.test.ts
index 17ec9d6cc..05a124e23 100644
--- a/packages/eve/src/cli/dev/tui/setup-selection-input.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-selection-input.test.ts
@@ -15,7 +15,7 @@ describe("setupSelectionIntent", () => {
});
it("leaves text-editing keys to the active selection surface", () => {
- expect(setupSelectionIntent({ type: "character", value: "a" })).toBeUndefined();
+ expect(setupSelectionIntent({ type: "text", value: "a", framing: "unframed" })).toBeUndefined();
expect(setupSelectionIntent({ type: "backspace" })).toBeUndefined();
});
@@ -65,7 +65,7 @@ describe("setupSelectionIntent", () => {
];
const initial = initialSelectState({ options });
const filtered = reduceSetupSelectInput({
- key: { type: "character", value: "s" },
+ key: { type: "text", value: "s", framing: "unframed" },
kind: "search",
options,
select: initial,
@@ -82,4 +82,36 @@ describe("setupSelectionIntent", () => {
}),
).toEqual({ kind: "submit", values: ["slack"] });
});
+
+ it("applies bracketed-paste text to searchable fields", () => {
+ const options = [
+ { value: "new-york", label: "New York" },
+ { value: "boston", label: "Boston" },
+ ];
+ const result = reduceSetupSelectInput({
+ key: { type: "text", value: "Boston", framing: "bracketed-paste" },
+ kind: "search",
+ options,
+ select: initialSelectState({ options }),
+ });
+
+ expect(result.kind).toBe("update");
+ if (result.kind !== "update") return;
+ expect(result.select.filter).toBe("Boston");
+ });
+
+ it("does not turn a pasted space into a multi-select toggle", () => {
+ const options = [{ value: "web", label: "Web Chat" }];
+ const select = initialSelectState({ options, submitRow: true });
+
+ expect(
+ reduceSetupSelectInput({
+ key: { type: "text", value: " ", framing: "bracketed-paste" },
+ kind: "multi",
+ options,
+ select,
+ required: false,
+ }),
+ ).toEqual({ kind: "ignore" });
+ });
});
diff --git a/packages/eve/src/cli/dev/tui/setup-selection-input.ts b/packages/eve/src/cli/dev/tui/setup-selection-input.ts
index 423fb6d24..52e2020cc 100644
--- a/packages/eve/src/cli/dev/tui/setup-selection-input.ts
+++ b/packages/eve/src/cli/dev/tui/setup-selection-input.ts
@@ -111,15 +111,15 @@ function editSetupSelect(input: SetupSelectInputState): SetupSelectInputResult {
return isSearchableSelect(input)
? updatedSelect(input, { type: "backspace" })
: { kind: "ignore" };
- case "character": {
- if (isMultiSelect(input) && input.key.value === " ") {
+ case "text": {
+ if (input.key.framing === "unframed" && isMultiSelect(input) && input.key.value === " ") {
return updatedSelect(input, { type: "toggle" });
}
if (!isSearchableSelect(input)) return { kind: "ignore" };
let select = input.select;
const context = { options: input.options, submitRow: isMultiSelect(input) };
- for (const char of input.key.value) {
+ for (const char of input.key.value.replaceAll("\n", " ")) {
if (char >= " " && char !== "\u007f") {
select = reduceSelect(select, { type: "char", char }, context);
}
diff --git a/packages/eve/src/cli/dev/tui/stream-format.test.ts b/packages/eve/src/cli/dev/tui/stream-format.test.ts
index 582fcfbea..91ab320e0 100644
--- a/packages/eve/src/cli/dev/tui/stream-format.test.ts
+++ b/packages/eve/src/cli/dev/tui/stream-format.test.ts
@@ -3,14 +3,47 @@ import { describe, expect, it } from "vitest";
import {
formatCompactTokenCount,
formatTokenFlow,
+ isIncompletePaste,
nextKey,
parseKey,
+ sanitizePastedText,
+ stripPasteStart,
stripPromptControlCharacters,
takeUntil,
} from "./stream-format.js";
const FLOW_GLYPHS = { arrowUp: "↑", arrowDown: "↓" };
+describe("sanitizePastedText", () => {
+ it("keeps newlines and tabs but drops other control characters and ESC", () => {
+ expect(sanitizePastedText("a\tb\nc")).toBe("a\tb\nc");
+ expect(sanitizePastedText("a\x1b[31mb\x07c")).toBe("a[31mbc");
+ });
+
+ it("normalizes CRLF and lone CR to LF", () => {
+ expect(sanitizePastedText("a\r\nb\rc")).toBe("a\nb\nc");
+ });
+
+ it("drops C1 control bytes that terminals read as control introducers", () => {
+ // 0x9b is single-byte CSI, 0x9d is OSC: leaving them in would let a paste
+ // smuggle in an escape sequence.
+ expect(sanitizePastedText("a›bc")).toBe("abc");
+ });
+});
+
+describe("incomplete bracketed paste", () => {
+ it("flags a paste whose end marker hasn't arrived, and clears once it has", () => {
+ expect(isIncompletePaste("\x1b[200~partial")).toBe(true);
+ expect(isIncompletePaste("\x1b[200~done\x1b[201~")).toBe(false);
+ expect(isIncompletePaste("plain text")).toBe(false);
+ });
+
+ it("strips the start marker so recovery can read the buffered payload", () => {
+ expect(stripPasteStart("\x1b[200~oops")).toBe("oops");
+ expect(stripPasteStart("no marker")).toBe("no marker");
+ });
+});
+
describe("formatCompactTokenCount", () => {
it("keeps small counts plain and abbreviates with one trimmed decimal", () => {
expect(formatCompactTokenCount(0)).toBe("0");
@@ -57,11 +90,55 @@ describe("nextKey", () => {
});
it("takes a printable run as a single character token", () => {
- expect(nextKey("hello")).toEqual({ key: { type: "character", value: "hello" }, consumed: 5 });
+ expect(nextKey("hello")).toEqual({
+ key: { type: "text", value: "hello", framing: "unframed" },
+ consumed: 5,
+ });
+ });
+
+ it("decodes a bracketed paste as one token, preserving newlines", () => {
+ const buffer = "\x1b[200~first\nsecond\x1b[201~";
+ expect(nextKey(buffer)).toEqual({
+ key: { type: "text", value: "first\nsecond", framing: "bracketed-paste" },
+ consumed: buffer.length,
+ });
+ });
+
+ it("sanitizes the paste payload as it decodes, not just at insert time", () => {
+ // A hostile frame carrying ESC and a bell must come out stripped, pinning
+ // the sanitize call on the decode path itself.
+ const buffer = "\x1b[200~a\x1b[31mb\x07c\x1b[201~";
+ expect(nextKey(buffer)).toEqual({
+ key: { type: "text", value: "a[31mbc", framing: "bracketed-paste" },
+ consumed: buffer.length,
+ });
+ });
+
+ it("waits for the bracketed-paste end marker before decoding", () => {
+ expect(nextKey("\x1b[200~still arriving")).toEqual({ consumed: 0, incomplete: true });
+ });
+
+ it("re-tokenizes input that follows a bracketed paste", () => {
+ const buffer = "\x1b[200~hi\x1b[201~\r";
+ const token = nextKey(buffer);
+ expect(token).toEqual({
+ key: { type: "text", value: "hi", framing: "bracketed-paste" },
+ consumed: buffer.length - 1,
+ });
+ expect(nextKey(buffer.slice(token.consumed))).toEqual({ key: { type: "enter" }, consumed: 1 });
+ });
+
+ it("decodes Shift+Enter as a newline while a bare Enter still submits", () => {
+ expect(nextKey("\x1b[27;2;13~")).toEqual({ key: { type: "newline" }, consumed: 10 });
+ expect(nextKey("\x1b[13;2u")).toEqual({ key: { type: "newline" }, consumed: 7 });
+ expect(nextKey("\r")).toEqual({ key: { type: "enter" }, consumed: 1 });
});
it("stops a printable run at a control byte", () => {
- expect(nextKey("ab\rcd")).toEqual({ key: { type: "character", value: "ab" }, consumed: 2 });
+ expect(nextKey("ab\rcd")).toEqual({
+ key: { type: "text", value: "ab", framing: "unframed" },
+ consumed: 2,
+ });
});
it("decodes a lone control byte", () => {
@@ -72,7 +149,11 @@ describe("nextKey", () => {
describe("parseKey", () => {
it("strips control characters from pasted/batched input", () => {
- expect(parseKey(Buffer.from("hi\tthere"))).toEqual({ type: "character", value: "hithere" });
+ expect(parseKey(Buffer.from("hi\tthere"))).toEqual({
+ type: "text",
+ value: "hithere",
+ framing: "unframed",
+ });
expect(parseKey(Buffer.from("\r"))).toEqual({ type: "enter" });
});
});
diff --git a/packages/eve/src/cli/dev/tui/stream-format.ts b/packages/eve/src/cli/dev/tui/stream-format.ts
index 59292f17c..1e5a71023 100644
--- a/packages/eve/src/cli/dev/tui/stream-format.ts
+++ b/packages/eve/src/cli/dev/tui/stream-format.ts
@@ -7,7 +7,13 @@
import type { AssistantResponseStatsMode } from "./types.js";
export type TerminalKey =
- | { type: "character"; value: string }
+ | {
+ type: "text";
+ value: string;
+ /** Terminal framing, not proof that the text came from a physical keypress. */
+ framing: "unframed" | "bracketed-paste";
+ }
+ | { type: "newline" }
| { type: "backspace" }
| { type: "delete" }
| { type: "enter" }
@@ -30,7 +36,7 @@ export type TerminalKey =
| { type: "ctrl-c" }
| { type: "ignore" };
-/** One decoded key plus how many bytes it consumed from the input buffer. */
+/** One decoded key plus the UTF-16 code units it consumed from the input buffer. */
export interface KeyToken {
key?: TerminalKey;
consumed: number;
@@ -41,6 +47,46 @@ export interface KeyToken {
// Final byte of a CSI escape sequence (`ESC [ … <final>`), range 0x40–0x7e.
const CSI_FINAL = /[\u0040-\u007e]/u;
+// Bracketed paste markers (DEC private mode 2004). The terminal wraps pasted
+// text in these so an embedded newline inserts literally instead of submitting.
+const PASTE_START = "\x1B[200~";
+const PASTE_END = "\x1B[201~";
+
+/**
+ * Preserves newlines and tabs, normalizes CR to LF, and drops C0, DEL, and C1
+ * controls. The first end marker closes the frame. This prevents escape
+ * injection, not display spoofing by bidi or zero-width characters.
+ */
+export function sanitizePastedText(text: string): string {
+ let printable = "";
+ for (const character of text.replace(/\r\n?/gu, "\n")) {
+ if (character === "\n" || character === "\t") {
+ printable += character;
+ continue;
+ }
+ const code = character.codePointAt(0);
+ if (code === undefined) continue;
+ if (code < 0x20 || code === 0x7f || (code >= 0x80 && code <= 0x9f)) continue;
+ printable += character;
+ }
+ return printable;
+}
+
+/**
+ * True when `buffer` is a bracketed paste whose closing marker hasn't arrived.
+ * {@link nextKey} reports such a buffer as `incomplete` indefinitely, so the
+ * caller needs this to recover if the end marker never comes (a process that
+ * emits a bare start marker and dies, a malformed terminal).
+ */
+export function isIncompletePaste(buffer: string): boolean {
+ return buffer.startsWith(PASTE_START) && !buffer.includes(PASTE_END, PASTE_START.length);
+}
+
+/** Drops a leading bracketed-paste start marker, leaving the buffered payload. */
+export function stripPasteStart(buffer: string): string {
+ return buffer.startsWith(PASTE_START) ? buffer.slice(PASTE_START.length) : buffer;
+}
+
/** Removes C0 control characters and DEL from text intended for the prompt. */
export function stripPromptControlCharacters(text: string): string {
let printable = "";
@@ -72,6 +118,21 @@ export function nextKey(buffer: string): KeyToken {
return { key: parseKey(Buffer.from(buffer.slice(0, 3))), consumed: 3 };
}
if (second === "[") {
+ // Bracketed paste: capture everything between the start and end markers as
+ // one chunk so embedded newlines insert literally instead of each one
+ // submitting the line. Wait for the closing marker if it hasn't arrived.
+ if (buffer.startsWith(PASTE_START)) {
+ const end = buffer.indexOf(PASTE_END, PASTE_START.length);
+ if (end === -1) return { consumed: 0, incomplete: true };
+ return {
+ key: {
+ type: "text",
+ value: sanitizePastedText(buffer.slice(PASTE_START.length, end)),
+ framing: "bracketed-paste",
+ },
+ consumed: end + PASTE_END.length,
+ };
+ }
for (let i = 2; i < buffer.length; i += 1) {
if (CSI_FINAL.test(buffer[i]!)) {
return { key: parseKey(Buffer.from(buffer.slice(0, i + 1))), consumed: i + 1 };
@@ -124,6 +185,11 @@ export function parseKey(chunk: Buffer): TerminalKey {
case "\r":
case "\n":
return { type: "enter" };
+ // Shift+Enter inserts a newline instead of submitting. Terminals report it
+ // as xterm modifyOtherKeys (`CSI 27 ; 2 ; 13 ~`) or the kitty/CSI-u form.
+ case "\x1b[27;2;13~":
+ case "\x1b[13;2u":
+ return { type: "newline" };
case "\u007f":
case "\b":
return { type: "backspace" };
@@ -154,11 +220,12 @@ export function parseKey(chunk: Buffer): TerminalKey {
case "\x1B":
return { type: "escape" };
default: {
- // Strip C0 control characters and DEL so pasted text — which arrives as
- // one batched chunk that may carry newlines/tabs — inserts cleanly
- // instead of injecting literal control bytes into the line.
+ // Strip C0 control characters and DEL from an unframed printable run.
+ // Bracketed paste and control keys were tokenized above.
const printable = stripPromptControlCharacters(value);
- return printable.length > 0 ? { type: "character", value: printable } : { type: "ignore" };
+ return printable.length > 0
+ ? { type: "text", value: printable, framing: "unframed" }
+ : { type: "ignore" };
}
}
}
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index c5a4a8d66..c7e77b324 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -234,6 +234,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(abort).toHaveBeenCalledTimes(1);
expect(screen.snapshot()).toContain("Interrupted");
expect(input.rawModes).toEqual([true]);
+ expect(screen.rawOutput()).toContain("\x1b[?2004h");
// Control returns to the prompt rather than exiting; the next prompt works.
const nextPrompt = renderer.readPrompt();
@@ -243,6 +244,149 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
expect(input.rawModes).toEqual([true, false]);
+ expect(screen.rawOutput()).toContain("\x1b[?2004l");
+ });
+
+ it("reassembles and renders a byte-split multi-line paste", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const text = "first 😀\nsecond 界";
+
+ const prompt = renderer.readPrompt();
+ for (const byte of Buffer.from(`\x1b[200~${text}\x1b[201~`)) {
+ input.emit("data", Buffer.of(byte));
+ }
+
+ const lines = screen.snapshot().split("\n");
+ const firstRow = lines.findIndex((line) => line.includes("first 😀"));
+ const secondRow = lines.findIndex((line) => line.includes("second 界"));
+ expect(firstRow).toBeGreaterThanOrEqual(0);
+ expect(secondRow).toBe(firstRow + 1);
+ expect(screen.snapshot()).not.toContain("⏎");
+
+ input.enter();
+ expect(await prompt).toBe(text);
+ renderer.shutdown();
+ });
+
+ it("clears a non-empty prompt on Ctrl+C, and quits only when already empty", async () => {
+ const { input, renderer } = makeRenderer();
+
+ const prompt = renderer.readPrompt();
+ input.type("draft message");
+ input.ctrlC(); // first Ctrl+C clears the buffer instead of quitting
+ input.type("real message");
+ input.enter();
+
+ // The cleared draft is gone (otherwise this would be "draft messagereal message").
+ expect(await prompt).toBe("real message");
+
+ // A Ctrl+C on the now-empty prompt quits.
+ const second = renderer.readPrompt();
+ input.ctrlC();
+ await expect(second).rejects.toThrow();
+
+ renderer.shutdown();
+ });
+
+ it("windows a line longer than the terminal around the caret", async () => {
+ const { screen, input, renderer } = makeRenderer(20); // narrow terminal
+
+ const prompt = renderer.readPrompt();
+ input.type("abcdefghijklmnopqrstuvwxyz"); // 26 chars into ~18 columns of room
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("xyz"); // the caret end stays visible
+ expect(snapshot).toContain("…"); // the truncated head is marked
+ expect(snapshot).not.toContain("abcde"); // the head scrolled off
+
+ input.enter();
+ expect(await prompt).toBe("abcdefghijklmnopqrstuvwxyz"); // full text still submits
+ renderer.shutdown();
+ });
+
+ it("draws the caret over the character under it without inserting a cell", async () => {
+ const { screen, input, renderer } = makeRenderer();
+
+ const prompt = renderer.readPrompt();
+ input.type("hello");
+ input.left();
+ input.left(); // caret between "hel" and "lo"
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("hello"); // text stays contiguous, not split by a caret
+ expect(snapshot).not.toContain("▏"); // no inserted bar-caret cell
+ // The block caret is reverse-video (SGR 7) over the grapheme under the
+ // cursor; snapshot() strips SGR, so assert it on the raw output.
+ expect(screen.rawOutput()).toContain("\x1b[7m");
+
+ input.enter();
+ await prompt;
+ renderer.shutdown();
+ });
+
+ it("recovers from an unterminated bracketed paste instead of wedging input", async () => {
+ vi.useFakeTimers();
+ try {
+ const { input, renderer } = makeRenderer();
+ const prompt = renderer.readPrompt();
+ input.send("\x1b[200~first\nsecond"); // paste start, closing marker never arrives
+ vi.advanceTimersByTime(1_100); // past the incomplete-paste flush
+ input.type("X"); // input still works rather than being wedged
+ input.enter();
+ expect(await prompt).toBe("first\nsecondX");
+ renderer.shutdown();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("inserts a newline on Shift+Enter and submits the whole multi-line buffer", async () => {
+ const { input, renderer } = makeRenderer();
+
+ const prompt = renderer.readPrompt();
+ input.type("line one");
+ input.send("\x1b[27;2;13~"); // Shift+Enter (xterm modifyOtherKeys)
+ input.type("line two");
+ input.enter();
+
+ expect(await prompt).toBe("line one\nline two");
+ renderer.shutdown();
+ });
+
+ it("moves the caret into the line above on ↑, then edits it", async () => {
+ const { input, renderer } = makeRenderer();
+
+ const prompt = renderer.readPrompt();
+ input.send("\x1b[200~ab\ncd\x1b[201~"); // caret lands after "cd"
+ input.up(); // to the end of "ab"
+ input.type("X");
+ input.enter();
+
+ expect(await prompt).toBe("abX\ncd");
+ renderer.shutdown();
+ });
+
+ it("bounds a tall prompt and moves its viewport with the caret", async () => {
+ const { screen, input, renderer } = makeRenderer(40, 8);
+ const lines = Array.from({ length: 20 }, (_, index) => `line ${index + 1}`);
+
+ const prompt = renderer.readPrompt();
+ input.send(`\x1b[200~${lines.join("\n")}\x1b[201~`);
+
+ expect(screen.snapshot().split("\n").length).toBeLessThanOrEqual(8);
+ expect(screen.snapshot()).toContain("line 20");
+ expect(screen.snapshot()).toContain("…");
+
+ for (let index = 0; index < 15; index += 1) input.up();
+
+ expect(screen.snapshot()).toContain("line 5");
+ expect(screen.snapshot()).not.toContain("line 20");
+
+ input.type("X");
+ input.enter();
+ lines[4] += "X";
+ expect(await prompt).toBe(lines.join("\n"));
+ renderer.shutdown();
});
it("renders reused stream block ids across separate prompt turns", async () => {
@@ -573,6 +717,65 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
+ it("preserves bracketed multi-line paste in freeform question input", async () => {
+ const { input, renderer } = makeRenderer();
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "What city are you in?",
+ display: "text",
+ options: [],
+ allowFreeform: true,
+ });
+ input.send("\x1b[200~New\nYork\x1b[201~");
+ input.enter();
+
+ await expect(answer).resolves.toEqual({ text: "New\nYork" });
+ renderer.shutdown();
+ });
+
+ it("edits freeform question input across lines", async () => {
+ const { input, renderer } = makeRenderer();
+
+ const answer = renderer.readInputQuestion({
+ requestId: "q1",
+ prompt: "What should I know?",
+ display: "text",
+ });
+ input.type("first");
+ input.send("\x1b[27;2;13~");
+ input.type("second");
+ input.up();
+ input.type("!");
+ input.enter();
+
+ await expect(answer).resolves.toEqual({ text: "first!\nsecond" });
+ renderer.shutdown();
+ });
+
+ it("clears non-empty freeform question input on Ctrl+C before interrupting", async () => {
+ const { input, renderer } = makeRenderer();
+ const question = {
+ requestId: "q1",
+ prompt: "What city are you in?",
+ display: "text",
+ options: [],
+ allowFreeform: true,
+ } satisfies Parameters<typeof renderer.readInputQuestion>[0];
+
+ const answer = renderer.readInputQuestion(question);
+ input.type("New York");
+ input.ctrlC();
+ input.type("Boston");
+ input.enter();
+ await expect(answer).resolves.toEqual({ text: "Boston" });
+
+ const interrupted = renderer.readInputQuestion({ ...question, requestId: "q2" });
+ input.ctrlC();
+ await expect(interrupted).rejects.toThrow();
+ renderer.shutdown();
+ });
+
it("paints a fully typed known command blue in the input line", async () => {
const { screen, input, renderer } = makeRenderer();
@@ -1150,6 +1353,44 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(snapshot).toContain("→ denied");
});
+ it("does not treat bracketed-paste text as a tool approval action", async () => {
+ const { input, renderer } = makeRenderer();
+ const approval = renderer.readToolApproval({
+ approvalId: "a1",
+ toolCallId: "c1",
+ toolName: "delete_files",
+ input: { path: "/" },
+ });
+
+ input.send("\x1b[200~y\x1b[201~");
+ input.type("n");
+
+ await expect(approval).resolves.toEqual({ approved: false, reason: "Denied by user." });
+ renderer.shutdown();
+ });
+
+ it("does not treat an unterminated bracketed paste as a tool approval action", async () => {
+ vi.useFakeTimers();
+ try {
+ const { input, renderer } = makeRenderer();
+ const approval = renderer.readToolApproval({
+ approvalId: "a1",
+ toolCallId: "c1",
+ toolName: "delete_files",
+ input: { path: "/" },
+ });
+
+ input.send("\x1b[200~y");
+ vi.advanceTimersByTime(1_100);
+ input.type("n");
+
+ await expect(approval).resolves.toEqual({ approved: false, reason: "Denied by user." });
+ renderer.shutdown();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("commits a dim recovery notice to scrollback", () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index f45e69548..5938b48a9 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -1,3 +1,5 @@
+import { StringDecoder } from "node:string_decoder";
+
import type {
AgentTUIInputOption,
AgentTUIInputQuestion,
@@ -59,7 +61,6 @@ import {
type DevRebuildLogUpdate,
} from "#internal/nitro/host/dev-watcher-log.js";
import { toErrorMessage } from "#shared/errors.js";
-
import {
type Block,
type BlockKind,
@@ -74,7 +75,9 @@ import {
PromptHistory,
applyLineEditorKey,
deleteForward,
+ layoutPromptInput,
lineOf,
+ movePromptLine,
visibleLine,
type LineState,
} from "./line-editor.js";
@@ -82,14 +85,17 @@ import { LiveRegion } from "./live-region.js";
import { buildStatusLine } from "./status-line.js";
import { nextLogDisplayMode } from "./log-display-mode.js";
import { createTheme, detectUnicode, type Theme } from "./theme.js";
-import { sliceVisible, stripAnsi, stripTerminalControls, visibleLength } from "./terminal-text.js";
+import { clipVisible, renderInputText, stripAnsi, stripTerminalControls } from "./terminal-text.js";
import type { VercelStatusSnapshot } from "./vercel-status.js";
import { summarizeToolArgs, summarizeToolResult } from "./tool-format.js";
import { reduceSetupSelectInput, setupSelectionIntent } from "./setup-selection-input.js";
import {
formatAssistantResponseStats,
formatTokenFlow,
+ isIncompletePaste,
nextKey,
+ sanitizePastedText,
+ stripPasteStart,
stripPromptControlCharacters,
takeUntil,
type TerminalKey,
@@ -217,6 +223,10 @@ const tickMs = 90;
// How long to wait on a lone `ESC` before treating it as the Escape key, so a
// split arrow sequence (`ESC` then `[A`) has time to reassemble first.
const escFlushMs = 30;
+// How long to wait, with no further input, before abandoning a bracketed paste
+// whose closing marker never arrived. Generous because the timer resets on every
+// read, so an in-flight paste keeps it alive; it only fires once input goes quiet.
+const incompletePasteFlushMs = 1_000;
// How long the transient Ctrl+L log-mode hint stays in the status line after
// the last cycle before it clears itself.
const logLevelHintMs = 5_000;
@@ -307,8 +317,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
#logLevelHintActive = false;
/** Active per-mode key consumer (prompt, approval, question, streaming). */
#consumeKey?: (key: TerminalKey) => void;
- /** Bytes held back while an escape sequence is still arriving. */
+ /** Decoded input held while an escape sequence is still arriving. */
#keyBuffer = "";
+ #inputDecoder = new StringDecoder("utf8");
#keyFlushTimer?: ReturnType<typeof setTimeout>;
#onResize?: () => void;
#resolveStreamInterrupt?: () => void;
@@ -453,7 +464,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
};
this.#consumeKey = (key) => {
- const edited = applyLineEditorKey(editor, key);
+ // Chat keeps pasted newlines and honors Shift+Enter. Setup-panel inputs
+ // stay single-line; freeform questions opt in separately below.
+ const edited = applyLineEditorKey(editor, key, { multiline: true });
if (edited !== undefined) {
apply(edited);
return;
@@ -461,22 +474,28 @@ export class TerminalRenderer implements AgentTUIRenderer {
switch (key.type) {
case "up": {
const open = suggestions();
- if (open === undefined) {
- recall(this.#promptHistory.previous(editor.text));
- } else {
+ if (open !== undefined) {
this.#typeahead = moveTypeaheadSelection(open, -1);
this.#paint();
+ break;
}
+ // Within a multi-line buffer, ↑ walks to the row above; only at the
+ // top row does it hand off to prompt history.
+ const moved = movePromptLine(editor, "up");
+ if (moved !== undefined) apply(moved);
+ else recall(this.#promptHistory.previous(editor.text));
break;
}
case "down": {
const open = suggestions();
- if (open === undefined) {
- recall(this.#promptHistory.next());
- } else {
+ if (open !== undefined) {
this.#typeahead = moveTypeaheadSelection(open, 1);
this.#paint();
+ break;
}
+ const moved = movePromptLine(editor, "down");
+ if (moved !== undefined) apply(moved);
+ else recall(this.#promptHistory.next());
break;
}
case "tab": {
@@ -540,7 +559,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
break;
case "ctrl-c":
- interrupt();
+ // A first Ctrl+C clears a non-empty prompt; on an already-empty
+ // prompt it quits.
+ if (editor.text.length === 0) {
+ interrupt();
+ } else {
+ apply(EMPTY_LINE);
+ }
break;
default:
break;
@@ -632,7 +657,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
return await new Promise((resolve, reject) => {
this.#consumeKey = (key) => {
switch (key.type) {
- case "character": {
+ case "text": {
+ // This prevents ordinary bracketed paste from confirming by
+ // accident; terminal framing is not an authentication signal.
+ if (key.framing !== "unframed") break;
const value = key.value.toLowerCase();
if (value === "y") {
this.#status = STATUS.processing;
@@ -683,7 +711,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
let mode: "select" | "text" = hasOptions ? "select" : "text";
let cursorIndex = 0;
- let text = "";
+ let editor = EMPTY_LINE;
const isOnFreeformRow = () => hasFreeformRow && cursorIndex === optionList.length;
@@ -705,7 +733,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#inputActive = false;
} else {
this.#inputActive = true;
- this.#syncInput(lineOf(text));
+ this.#syncInput(editor);
this.#status = "";
}
this.#paint();
@@ -742,6 +770,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
return await new Promise<AgentTUIInputQuestionResponse | undefined>((resolve, reject) => {
this.#consumeKey = (key) => {
if (key.type === "ctrl-c") {
+ if (mode === "text" && editor.text.length > 0) {
+ editor = EMPTY_LINE;
+ this.#showCaret();
+ repaintStatus();
+ return;
+ }
this.#interrupted = true;
this.#stopCaretBlink();
this.#stop();
@@ -773,7 +807,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
case "enter": {
if (isOnFreeformRow()) {
mode = "text";
- text = "";
+ editor = EMPTY_LINE;
this.#startCaretBlink();
repaintStatus();
break;
@@ -788,39 +822,47 @@ export class TerminalRenderer implements AgentTUIRenderer {
return;
}
+ const edited = applyLineEditorKey(editor, key, { multiline: true });
+ if (edited !== undefined) {
+ editor = edited;
+ this.#showCaret();
+ repaintStatus();
+ return;
+ }
+
switch (key.type) {
- case "character":
- text += key.value;
- this.#showCaret();
- repaintStatus();
- break;
- case "backspace":
- text = text.slice(0, -1);
- this.#showCaret();
- repaintStatus();
+ case "up":
+ case "down": {
+ const moved = movePromptLine(editor, key.type);
+ if (moved !== undefined) {
+ editor = moved;
+ this.#showCaret();
+ repaintStatus();
+ }
break;
+ }
case "enter": {
- const resolvedText = resolveQuestionText(text, question);
+ const resolvedText = resolveQuestionText(editor.text, question);
if (resolvedText === undefined) break;
resolve(finalize(resolvedText));
break;
}
case "escape":
if (hasOptions) {
- if (text.length > 0) {
- text = "";
+ if (editor.text.length > 0) {
+ editor = EMPTY_LINE;
this.#showCaret();
repaintStatus();
break;
}
mode = "select";
- text = "";
+ editor = EMPTY_LINE;
this.#inputActive = false;
this.#stopCaretBlink();
repaintStatus();
break;
}
- text = "";
+ editor = EMPTY_LINE;
this.#showCaret();
repaintStatus();
break;
@@ -1658,6 +1700,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (this.#input.isTTY) {
this.#input.setRawMode?.(true);
this.#input.resume();
+ // Enable bracketed paste (DEC private mode 2004) so the terminal wraps
+ // pasted text in \x1b[200~ … \x1b[201~; the decoder then inserts a
+ // multi-line paste intact instead of each newline submitting the prompt.
+ // Routed through the live region's original `write` so the foreign-output
+ // capture installed just above can't swallow the control sequence.
+ this.#live.emitBracketedPaste(true);
}
this.#onResize = () => this.#paint();
@@ -1691,6 +1739,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#live.newline();
if (this.#input.isTTY) {
+ // Disable bracketed paste, restoring the terminal to how we found it.
+ this.#live.emitBracketedPaste(false);
this.#input.setRawMode?.(false);
this.#input.pause();
}
@@ -1714,6 +1764,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#input.off("data", this.#feedRaw);
this.#clearKeyFlush();
this.#keyBuffer = "";
+ this.#inputDecoder = new StringDecoder("utf8");
this.#consumeKey = undefined;
}
@@ -1724,9 +1775,25 @@ export class TerminalRenderer implements AgentTUIRenderer {
*/
readonly #feedRaw = (chunk: Buffer) => {
this.#clearKeyFlush();
- this.#keyBuffer += chunk.toString("utf8");
+ this.#keyBuffer += this.#inputDecoder.write(chunk);
this.#drainKeys();
+ this.#armKeyFlush();
+ };
+ /**
+ * Arms a one-shot timer for an escape sequence that {@link nextKey} can't yet
+ * resolve, so the decoder never blocks all further input waiting on bytes that
+ * will not come. Re-armed on every read, so a sequence still in flight stays
+ * alive; it only fires once input goes quiet.
+ */
+ #armKeyFlush() {
+ // A lone trailing ESC may begin an arrow/function key; hold it briefly, then
+ // surface it as a bare Escape. This is the standard ESC-timeout heuristic: a
+ // lone ESC and the leading byte of a longer sequence are indistinguishable,
+ // so a paste whose `\x1b[200~` leader is split off by >escFlushMs (only under
+ // network/PTY fragmentation, never an atomically-delivered local paste) can
+ // be misread as Escape + literal text. Lengthening the timeout trades Escape
+ // latency for a smaller window; not worth it for a non-adversarial edge.
if (this.#keyBuffer === "\x1b") {
this.#keyFlushTimer = setTimeout(() => {
if (this.#keyBuffer !== "\x1b") return;
@@ -1734,8 +1801,24 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#consumeKey?.({ type: "escape" });
}, escFlushMs);
this.#keyFlushTimer.unref?.();
+ return;
+ }
+ // A bracketed paste whose closing marker never arrives would otherwise wedge
+ // input forever. Recover its sanitized payload without losing the paste
+ // framing that downstream consumers use to apply paste-safe behavior.
+ if (isIncompletePaste(this.#keyBuffer)) {
+ const stuck = this.#keyBuffer;
+ this.#keyFlushTimer = setTimeout(() => {
+ if (this.#keyBuffer !== stuck) return;
+ const value = sanitizePastedText(stripPasteStart(stuck));
+ this.#keyBuffer = "";
+ if (value.length > 0) {
+ this.#consumeKey?.({ type: "text", value, framing: "bracketed-paste" });
+ }
+ }, incompletePasteFlushMs);
+ this.#keyFlushTimer.unref?.();
}
- };
+ }
#drainKeys() {
while (this.#keyBuffer.length > 0) {
@@ -2345,23 +2428,29 @@ export class TerminalRenderer implements AgentTUIRenderer {
) {
rows.push(...renderCommandSuggestions(this.#typeahead, this.#theme, width));
}
- // Reserve three columns: prompt glyph, its trailing space, and the caret.
- const budget = Math.max(4, width - 3);
- const { before, after } = visibleLine(
- { text: this.#inputText, cursor: this.#inputCursor },
- budget,
- this.#theme.glyph.ellipsis,
- );
// A fully typed known command paints blue, confirming it will dispatch
// as a command instead of being sent to the agent as a message.
const isCommand = isPromptControlCommand(this.#inputText);
- const style = (segment: string): string =>
- isCommand && segment.length > 0 ? c.blue(segment) : segment;
- const caret = this.#caretVisible ? c.cyan(this.#theme.glyph.caret) : " ";
const ghost = inlineHint ? c.dim(` ${inlineHint}`) : "";
- const body = `${style(before)}${caret}${style(after)}${ghost}`;
- rows.push(...promptInputRows(body, width, this.#theme, true));
- this.#pushStatusLine(rows, width);
+ const statusRows: string[] = [];
+ this.#pushStatusLine(statusRows, width);
+ // Keep one transcript row above the footer and one separator below the
+ // prompt. Everything already in `rows` has higher-level footer ownership
+ // (attention or typeahead), so the prompt receives only what remains.
+ const maxPromptRows = Math.max(1, this.#height() - 1 - rows.length - 1 - statusRows.length);
+ rows.push(
+ ...promptInputRows({
+ text: this.#inputText,
+ cursor: this.#inputCursor,
+ width,
+ theme: this.#theme,
+ caretVisible: this.#caretVisible,
+ isCommand,
+ ghost,
+ maxRows: maxPromptRows,
+ }),
+ );
+ rows.push(...statusRows);
return rows;
}
@@ -2695,19 +2784,83 @@ async function* iterateTUIStream(
}
function clip(line: string, width: number): string {
- return visibleLength(line) > width ? sliceVisible(line, width) : line;
+ return clipVisible(line, width);
+}
+
+interface PromptInputRowsInput {
+ readonly text: string;
+ readonly cursor: number;
+ readonly width: number;
+ readonly theme: Theme;
+ readonly caretVisible: boolean;
+ /** A fully typed known command paints blue, confirming it will dispatch as a command. */
+ readonly isCommand: boolean;
+ readonly ghost: string;
+ readonly maxRows: number;
}
/**
- * Renders the original prompt glyph and horizontal position, followed by a
- * blank row that keeps the persistent status visually separate. During a
- * turn the same row stays visible but dimmed beneath live activity.
+ * Renders the prompt buffer as terminal rows, followed by a blank row that keeps
+ * the persistent status visually separate. The buffer can carry newlines from
+ * paste or Shift+Enter, so it renders one row per logical line and windows tall
+ * input to `maxRows`, marking any hidden rows with an ellipsis.
*/
-function promptInputRows(content: string, width: number, theme: Theme, active: boolean): string[] {
+function promptInputRows({
+ text,
+ cursor,
+ width,
+ theme,
+ caretVisible,
+ isCommand,
+ ghost,
+ maxRows,
+}: PromptInputRowsInput): string[] {
const c = theme.colors;
- const prompt = active ? c.cyan(theme.glyph.prompt) : c.dim(theme.glyph.prompt);
- const body = active ? content : c.dim(content);
- return [clip(`${prompt} ${body}`, width), ""];
+ const style = (segment: string): string => {
+ const rendered = renderInputText(segment);
+ return isCommand && rendered.length > 0 ? c.blue(rendered) : rendered;
+ };
+
+ const layout = layoutPromptInput({ text, cursor });
+ const visibleCount = Math.min(Math.max(1, maxRows), layout.rows.length);
+ const top = Math.max(
+ 0,
+ Math.min(layout.caretRow - visibleCount + 1, layout.rows.length - visibleCount),
+ );
+ const promptGlyph = c.cyan(theme.glyph.prompt);
+ const ellipsis = c.dim(theme.glyph.ellipsis);
+ // Reserve the gutter and the block caret's trailing cell at end-of-line.
+ const budget = Math.max(1, width - 3);
+ const out: string[] = [];
+ for (let r = top; r < top + visibleCount; r += 1) {
+ const row = layout.rows[r]!;
+ let gutter = r === 0 ? promptGlyph : " ";
+ if (r === top && top > 0) gutter = ellipsis;
+ else if (r === top + visibleCount - 1 && top + visibleCount < layout.rows.length) {
+ gutter = ellipsis;
+ }
+
+ let body: string;
+ if (r === layout.caretRow) {
+ // Window the active row so the caret remains visible on long lines.
+ const { before, under, after } = visibleLine(
+ { text: row.text, cursor: layout.caretOffset },
+ budget,
+ theme.glyph.ellipsis,
+ );
+ // Inverse video keeps the underlying text in place; EOL uses a space.
+ const caretText = under || " ";
+ const caretCell = caretVisible ? c.inverse(renderInputText(caretText)) : style(caretText);
+ body = `${style(before)}${caretCell}${style(after)}`;
+ // The argument hint trails the caret only on a single-line command draft.
+ if (ghost.length > 0 && layout.rows.length === 1) body += ghost;
+ } else {
+ body = style(row.text);
+ }
+ out.push(clip(`${gutter} ${body}`, width));
+ }
+ out.push("");
+ return out;
}
/** Kind + title of the previously rendered block, for gap / run decisions. */
diff --git a/packages/eve/src/cli/dev/tui/terminal-text.test.ts b/packages/eve/src/cli/dev/tui/terminal-text.test.ts
index 7cd358ddb..e88ac1d71 100644
--- a/packages/eve/src/cli/dev/tui/terminal-text.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-text.test.ts
@@ -1,6 +1,16 @@
import { describe, expect, it } from "vitest";
-import { stripAnsi, stripTerminalControls } from "./terminal-text.js";
+import {
+ clipVisible,
+ inputTextWidth,
+ offsetAtVisibleColumn,
+ renderInputText,
+ sliceVisible,
+ stripAnsi,
+ stripTerminalControls,
+ visibleLength,
+ wrapVisibleLine,
+} from "./terminal-text.js";
describe("stripTerminalControls", () => {
it("removes C0 and C1 controls while preserving tabs and newlines", () => {
@@ -23,3 +33,40 @@ describe("stripAnsi", () => {
expect(stripAnsi(input)).toBe("abc]0;titled");
});
});
+
+describe("editable input geometry", () => {
+ it("measures graphemes rather than summing their code points", () => {
+ expect(inputTextWidth("界x")).toBe(3);
+ expect(inputTextWidth("e\u0301")).toBe(1);
+ expect(inputTextWidth("👨‍👩‍👧‍👦")).toBe(2);
+ expect(inputTextWidth("🇺🇸")).toBe(2);
+ expect(inputTextWidth("1️⃣")).toBe(2);
+ expect(inputTextWidth("©️")).toBe(2);
+ expect(inputTextWidth("A\uFE0F")).toBe(1);
+ expect(inputTextWidth("\t")).toBe(4);
+ });
+
+ it("uses the same grapheme widths when clipping styled terminal text", () => {
+ const family = "👨‍👩‍👧‍👦";
+ const styled = `\x1b[7m${family}X\x1b[0m`;
+
+ expect(visibleLength(styled)).toBe(3);
+ expect(stripAnsi(sliceVisible(styled, 2))).toBe(family);
+ expect(clipVisible(styled, 2)).toBe(`\x1b[7m${family}\x1b[0m`);
+ expect(clipVisible("A\uFE0F", 1)).toBe("A\uFE0F");
+ });
+
+ it("makes progress when a grapheme is wider than the requested wrap width", () => {
+ expect(wrapVisibleLine("🇺🇸", 1)).toEqual(["🇺🇸"]);
+ expect(wrapVisibleLine("\x1b[31m🇺🇸\x1b[0m", 1)).toEqual(["\x1b[31m🇺🇸\x1b[0m"]);
+ });
+
+ it("maps terminal columns to grapheme boundaries", () => {
+ expect(offsetAtVisibleColumn("界x", 2)).toBe(1);
+ expect(offsetAtVisibleColumn("e\u0301x", 1)).toBe(2);
+ });
+
+ it("renders tabs with the same fixed width used by input geometry", () => {
+ expect(renderInputText("a\tb")).toBe("a b");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/terminal-text.ts b/packages/eve/src/cli/dev/tui/terminal-text.ts
index a48039d6f..35a682f5e 100644
--- a/packages/eve/src/cli/dev/tui/terminal-text.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-text.ts
@@ -1,7 +1,12 @@
+import { graphemes } from "#shared/text-boundaries.js";
+
const ansiEscape = String.fromCharCode(27);
export const ansiPattern = new RegExp(`${ansiEscape}\\[[0-?]*[ -/]*[@-~]`, "g");
export const ansiPrefixPattern = new RegExp(`^${ansiEscape}\\[[0-?]*[ -/]*[@-~]`);
+const emojiPresentationPattern = /\p{Emoji_Presentation}/u;
+const extendedPictographicPattern = /\p{Extended_Pictographic}/u;
+const keycapPattern = /^[#*0-9]\u{fe0f}?\u{20e3}$/u;
export function stripAnsi(input: string): string {
return stripTerminalControls(input.replaceAll(ansiPattern, ""));
@@ -33,27 +38,7 @@ export function stripTerminalControls(input: string): string {
export function visibleLength(input: string): number {
let width = 0;
- let index = 0;
-
- while (index < input.length) {
- const ansiMatch = input.slice(index).match(ansiPrefixPattern);
-
- if (ansiMatch) {
- index += ansiMatch[0].length;
- continue;
- }
-
- const codePoint = input.codePointAt(index);
-
- if (codePoint == null) {
- break;
- }
-
- const character = String.fromCodePoint(codePoint);
- width += codePointWidth(codePoint);
- index += character.length;
- }
-
+ for (const unit of terminalTextUnits(input)) width += unit.width;
return width;
}
@@ -64,47 +49,101 @@ export function sliceVisible(input: string, width: number): string {
let output = "";
let visible = 0;
+ const units = terminalTextUnits(input);
let index = 0;
+ while (index < units.length && visible < width) {
+ const unit = units[index]!;
+ if (unit.width > 0 && visible + unit.width > width) break;
+ output += unit.text;
+ visible += unit.width;
+ index += 1;
+ }
- while (index < input.length && visible < width) {
- const ansiMatch = input.slice(index).match(ansiPrefixPattern);
+ while (units[index]?.ansi === true) {
+ output += units[index]!.text;
+ index += 1;
+ }
- if (ansiMatch) {
- output += ansiMatch[0];
- index += ansiMatch[0].length;
- continue;
- }
+ return output;
+}
- const codePoint = input.codePointAt(index);
+/** Clips text styled only at grapheme boundaries, resetting any truncated style. */
+export function clipVisible(input: string, width: number): string {
+ if (visibleLength(input) <= width) return input;
+ const sliced = sliceVisible(input, width);
+ return sliced.includes(ansiEscape) ? `${sliced}${ansiEscape}[0m` : sliced;
+}
- if (codePoint == null) {
- break;
- }
+/** Terminal-cell width of editor text, measured one grapheme cluster at a time. */
+export function inputTextWidth(input: string): number {
+ let width = 0;
+ for (const grapheme of graphemes(input)) {
+ width += terminalGraphemeWidth(grapheme.text);
+ }
+ return width;
+}
- const character = String.fromCodePoint(codePoint);
- const characterWidth = codePointWidth(codePoint);
+/** Expands editor tabs to the same fixed four cells used by {@link inputTextWidth}. */
+export function renderInputText(input: string): string {
+ return input.replaceAll("\t", " ");
+}
- if (characterWidth > 0 && visible + characterWidth > width) {
- break;
- }
+/**
+ * Returns the UTF-16 offset at or immediately before a terminal column.
+ * Graphemes stay intact even when the requested column falls inside a wide one.
+ */
+export function offsetAtVisibleColumn(input: string, column: number): number {
+ if (column <= 0) return 0;
- output += character;
- index += character.length;
- visible += characterWidth;
+ let visible = 0;
+ for (const grapheme of graphemes(input)) {
+ const next = visible + terminalGraphemeWidth(grapheme.text);
+ if (next > column) return grapheme.start;
+ if (next === column) return grapheme.end;
+ visible = next;
}
+ return input.length;
+}
- while (index < input.length) {
- const ansiMatch = input.slice(index).match(ansiPrefixPattern);
+function terminalGraphemeWidth(grapheme: string): number {
+ let width = 0;
+ for (const character of grapheme) {
+ const codePoint = character.codePointAt(0);
+ if (codePoint !== undefined) width = Math.max(width, codePointWidth(codePoint));
+ }
+ const emojiPresentation =
+ emojiPresentationPattern.test(grapheme) ||
+ keycapPattern.test(grapheme) ||
+ (grapheme.includes("\u{fe0f}") && extendedPictographicPattern.test(grapheme));
+ return emojiPresentation ? Math.max(2, width) : width;
+}
- if (!ansiMatch) {
- break;
+interface TerminalTextUnit {
+ readonly text: string;
+ readonly width: number;
+ readonly ansi: boolean;
+}
+
+function terminalTextUnits(input: string): TerminalTextUnit[] {
+ const units: TerminalTextUnit[] = [];
+ let index = 0;
+ while (index < input.length) {
+ const remaining = input.slice(index);
+ const ansiMatch = remaining.match(ansiPrefixPattern);
+ if (ansiMatch !== null) {
+ units.push({ text: ansiMatch[0], width: 0, ansi: true });
+ index += ansiMatch[0].length;
+ continue;
}
- output += ansiMatch[0];
- index += ansiMatch[0].length;
+ const nextAnsi = remaining.search(ansiPattern);
+ const plain = remaining.slice(0, nextAnsi === -1 ? remaining.length : nextAnsi);
+ for (const grapheme of graphemes(plain)) {
+ units.push({ text: grapheme.text, width: terminalGraphemeWidth(grapheme.text), ansi: false });
+ }
+ index += plain.length;
}
-
- return output;
+ return units;
}
/**
@@ -130,7 +169,7 @@ export function wrapVisibleLine(line: string, width: number): string[] {
remaining = remaining.slice(breakAt).trimStart();
}
- lines.push(remaining);
+ if (remaining.length > 0 || lines.length === 0) lines.push(remaining);
return lines;
}
@@ -142,7 +181,17 @@ function findVisibleBreakPoint(input: string, width: number): number {
return lastSpace;
}
- return sliceVisible(input, width).length;
+ const hardSlice = sliceVisible(input, width);
+ if (visibleLength(hardSlice) > 0) return hardSlice.length;
+
+ let offset = 0;
+ let foundVisibleUnit = false;
+ for (const unit of terminalTextUnits(input)) {
+ if (foundVisibleUnit && unit.width > 0) return offset;
+ offset += unit.text.length;
+ if (unit.width > 0) foundVisibleUnit = true;
+ }
+ return offset;
}
export function codePointWidth(codePoint: number): number {
diff --git a/packages/eve/src/cli/dev/tui/theme.ts b/packages/eve/src/cli/dev/tui/theme.ts
index 2811283e5..ddbb7812f 100644
--- a/packages/eve/src/cli/dev/tui/theme.ts
+++ b/packages/eve/src/cli/dev/tui/theme.ts
@@ -39,6 +39,8 @@ export interface ThemeColors {
reset: Style;
bold: Style;
dim: Style;
+ /** Reverse video (SGR 7), used to draw the block caret over the character under it. */
+ inverse: Style;
italic: Style;
white: Style;
gray: Style;
@@ -183,6 +185,7 @@ export function createTheme(options: CreateThemeOptions = {}): Theme {
reset: ansi(0, 0, color),
bold: ansi(1, 22, color),
dim: ansi(2, 22, color),
+ inverse: ansi(7, 27, color),
italic: ansi(3, 23, color),
white: ansi(97, 39, color),
gray: ansi(90, 39, color),
diff --git a/packages/eve/src/setup/cli/select-state.test.ts b/packages/eve/src/setup/cli/select-state.test.ts
index e1d5d65a4..8870eee15 100644
--- a/packages/eve/src/setup/cli/select-state.test.ts
+++ b/packages/eve/src/setup/cli/select-state.test.ts
@@ -88,8 +88,10 @@ describe("reduceSelect", () => {
]);
});
- it("ignores backspace on an empty filter", () => {
+ it("backspaces one grapheme and ignores an empty filter", () => {
expect(reduceSelect(initial, { type: "backspace" }, context())).toBe(initial);
+ const state = { filter: "😀", cursor: 0, selected: new Set<string>() };
+ expect(reduceSelect(state, { type: "backspace" }, context()).filter).toBe("");
});
it("wraps the cursor across the visible list", () => {
diff --git a/packages/eve/src/setup/cli/select-state.ts b/packages/eve/src/setup/cli/select-state.ts
index e4a5ce6c4..9638fb373 100644
--- a/packages/eve/src/setup/cli/select-state.ts
+++ b/packages/eve/src/setup/cli/select-state.ts
@@ -1,4 +1,5 @@
import type { PromptOption } from "./prompt-ui.js";
+import { previousGraphemeBoundary } from "#shared/text-boundaries.js";
/**
* Snapshot of the select interaction, advanced by {@link reduceSelect}. `cursor`
@@ -125,7 +126,10 @@ export function reduceSelect(
}
case "backspace": {
if (state.filter.length === 0) return state;
- const filter = state.filter.slice(0, -1);
+ const filter = state.filter.slice(
+ 0,
+ previousGraphemeBoundary(state.filter, state.filter.length),
+ );
return {
...state,
filter,
diff --git a/packages/eve/src/shared/text-boundaries.ts b/packages/eve/src/shared/text-boundaries.ts
new file mode 100644
index 000000000..c7c9ce2d7
--- /dev/null
+++ b/packages/eve/src/shared/text-boundaries.ts
@@ -0,0 +1,46 @@
+/**
+ * Shared grapheme-cluster boundaries for editable text. JavaScript offsets
+ * stay UTF-16 offsets; segmentation defines which offsets are legal caret
+ * positions and which spans editing operations may remove.
+ */
+
+interface GraphemeSpan {
+ readonly text: string;
+ readonly start: number;
+ readonly end: number;
+}
+
+const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
+
+/** Splits text into grapheme clusters while preserving `String.slice` offsets. */
+export function graphemes(text: string): GraphemeSpan[] {
+ return Array.from(graphemeSegmenter.segment(text), ({ index, segment }) => ({
+ text: segment,
+ start: index,
+ end: index + segment.length,
+ }));
+}
+
+/** The nearest grapheme boundary strictly before `offset`. */
+export function previousGraphemeBoundary(text: string, offset: number): number {
+ const clamped = Math.max(0, Math.min(offset, text.length));
+ if (clamped === 0) return 0;
+ return graphemeSegmenter.segment(text).containing(clamped - 1)?.index ?? 0;
+}
+
+/** The nearest grapheme boundary strictly after `offset`. */
+export function nextGraphemeBoundary(text: string, offset: number): number {
+ const clamped = Math.max(0, Math.min(offset, text.length));
+ if (clamped === text.length) return clamped;
+ const grapheme = graphemeSegmenter.segment(text).containing(clamped);
+ return grapheme === undefined ? text.length : grapheme.index + grapheme.segment.length;
+}
+
+/** The nearest grapheme boundary at or after `offset`. */
+export function graphemeBoundaryAtOrAfter(text: string, offset: number): number {
+ const clamped = Math.max(0, Math.min(offset, text.length));
+ if (clamped === 0 || clamped === text.length) return clamped;
+ const grapheme = graphemeSegmenter.segment(text).containing(clamped);
+ if (grapheme === undefined || grapheme.index === clamped) return clamped;
+ return grapheme.index + grapheme.segment.length;
+}