Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(tui): multi-line paste, bracketed paste, Shift+Enter newline, shared edit reducer

Salman Qureshiea6a1b14c2df
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index 872133f3..75026e31 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -16,6 +16,7 @@ import { TASK_SUMMARY_FILE_LIMIT } from '../ui/types.js';
import { TuiApp } from '../ui/App.js';
import { nextTip } from '../ui/tips.js';
import { ResilientTuiOutput } from '../ui/resilient-output.js';
+import { PASTE_SENTINEL, FORWARD_DELETE_KEY } from '../ui/input-composer.js';
import { detectInkPatch, inkPatchWarning } from '../ui/ink-patch-check.js';
/**
@@ -206,11 +207,45 @@ class TtyStdinProxy extends EventEmitter {
export class MouseSequenceFilter {
private buf = '';
+ /** Inside a bracketed paste (`ESC[200~` seen, `ESC[201~` not yet). */
+ private inPaste = false;
+ private flushTimer: ReturnType<typeof setTimeout> | null = null;
private static readonly SGR = /^\x1b\[<\d+;\d+;\d+[Mm]/;
private static readonly X10 = /^\x1b\[M[\x20-\x2f][\x20-\xff][\x20-\xff]/;
private static readonly DEC = /^\x1b\[\?100[0-7][hl]/;
private static readonly CSI_COMPLETE = /^\x1b\[[\d;<]*[A-Za-z]/;
+ private static readonly PASTE_START = /^\x1b\[200~/;
+ private static readonly PASTE_END = /^\x1b\[201~/;
+ /** Partial `ESC[201~` at the end of a paste chunk — wait for the rest. */
+ private static readonly PASTE_END_PARTIAL = /^\x1b(\[(2(0(1)?)?)?)?$/;
+ /** Any ANSI escape inside pasted text (never meaningful as input). */
+ private static readonly PASTE_ANSI = /\x1b(\[[0-9;?<>=]*[ -\/]*[@-~]|\][^\x07\x1b]*(\x07|\x1b\\)|[@-Z\\-_])?/g;
private static readonly MAX_HOLDBACK = 64;
+ /**
+ * A held-back prefix that is not completed within this window is a real
+ * keypress (a lone Esc, Alt+key) and is released as-is. Terminals deliver
+ * a complete sequence in one read or within a millisecond or two; 35 ms
+ * is the conventional ESC-disambiguation delay (vim's ttimeoutlen scale).
+ */
+ static readonly HOLDBACK_FLUSH_MS = 35;
+ /**
+ * Keys Ink either cannot parse or cannot tell apart, rewritten to
+ * sequences the shared composer understands (see input-composer.tsx):
+ * Shift+Enter / Ctrl+Enter in every common encoding → Ctrl+N (newline)
+ * the real Delete key (ESC[3~) → FORWARD_DELETE_KEY (Ink folds it into
+ * `key.delete` together with \x7f, which is Backspace on macOS/Linux)
+ */
+ private static readonly KEY_REWRITES: ReadonlyArray<readonly [RegExp, string]> = [
+ [/^\x1b\[13;[25]u/, '\x0e'], // kitty keyboard protocol
+ [/^\x1b\[27;[25];13~/, '\x0e'], // xterm modifyOtherKeys
+ [/^\x1b\r/, '\x0e'], // ESC CR (iTerm2 / Alt+Enter)
+ [/^\x1b\[3~/, FORWARD_DELETE_KEY],
+ // Home / End: Ink names them but hands the composer an empty `input`
+ // with no `key.home`/`key.end` flag, so they were dead keys. Readline
+ // Ctrl+A / Ctrl+E are what the composer binds to line start / end.
+ [/^\x1b(\[(1~|H)|OH)/, '\x01'],
+ [/^\x1b(\[(4~|F)|OF)/, '\x05'],
+ ];
constructor(
private onEvent: (ev: MouseEvent) => void,
@@ -220,10 +255,44 @@ export class MouseSequenceFilter {
/** Feed a raw chunk from the terminal; returns nothing, side-effects only. */
push(chunk: Buffer | string): void {
this.buf += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
+ this.drain();
+ }
+
+ private drain(): void {
let out = '';
+ let paste = '';
let i = 0;
+ const flushOut = () => { if (out) { this.write(out); out = ''; } };
+ const flushPaste = () => {
+ if (paste) {
+ this.write(PASTE_SENTINEL + paste.replace(MouseSequenceFilter.PASTE_ANSI, ''));
+ paste = '';
+ }
+ };
while (i < this.buf.length) {
const rest = this.buf.slice(i);
+ if (this.inPaste) {
+ if (rest[0] !== '\x1b') {
+ const esc = rest.indexOf('\x1b');
+ const text = esc < 0 ? rest : rest.slice(0, esc);
+ paste += text;
+ i += text.length;
+ continue;
+ }
+ const end = MouseSequenceFilter.PASTE_END.exec(rest)?.[0];
+ if (end) {
+ this.inPaste = false;
+ flushPaste();
+ i += end.length;
+ continue;
+ }
+ if (MouseSequenceFilter.PASTE_END_PARTIAL.test(rest)) break;
+ // An escape inside the paste: keep it in the payload (stripped
+ // from the text later) and move on.
+ paste += rest[0];
+ i += 1;
+ continue;
+ }
if (rest[0] !== '\x1b') {
out += rest[0];
i += 1;
@@ -240,6 +309,29 @@ export class MouseSequenceFilter {
i += seq.length;
continue;
}
+ const pasteStart = MouseSequenceFilter.PASTE_START.exec(rest)?.[0];
+ if (pasteStart) {
+ // Keystrokes typed before the paste must reach Ink before the
+ // paste payload, as their own chunk.
+ flushOut();
+ this.inPaste = true;
+ i += pasteStart.length;
+ continue;
+ }
+ let rewritten = false;
+ for (const [pattern, replacement] of MouseSequenceFilter.KEY_REWRITES) {
+ const m = pattern.exec(rest)?.[0];
+ if (m) {
+ // A rewritten key is a keystroke of its own: Ink parses a chunk
+ // as ONE key, so it must not be glued to surrounding text.
+ flushOut();
+ this.write(replacement);
+ i += m.length;
+ rewritten = true;
+ break;
+ }
+ }
+ if (rewritten) continue;
// X10 mouse in flight (ESC [ M + 0-2 pending payload bytes) — MUST be
// tested before the generic CSI pass-through, because 'M' is a valid
// CSI final byte and would otherwise leak the prefix downstream.
@@ -268,8 +360,45 @@ export class MouseSequenceFilter {
if (this.buf.length > MouseSequenceFilter.MAX_HOLDBACK) {
this.buf = '';
}
- if (out) this.write(out);
+ if (this.inPaste) flushPaste();
+ flushOut();
+ this.armHoldbackFlush();
}
+
+ /**
+ * A held-back prefix is either the head of a sequence still in flight or
+ * a real key (a lone Esc, Alt+letter). Release it after a short delay so
+ * Esc reaches Ink on its own instead of fusing with the NEXT keystroke.
+ */
+ private armHoldbackFlush(): void {
+ if (this.flushTimer) {
+ clearTimeout(this.flushTimer);
+ this.flushTimer = null;
+ }
+ if (this.buf.length === 0 || this.inPaste) return;
+ this.flushTimer = setTimeout(() => {
+ this.flushTimer = null;
+ if (this.buf.length === 0 || this.inPaste) return;
+ const held = this.buf;
+ this.buf = '';
+ // A bare ESC is the Escape key; anything longer is an unknown
+ // sequence whose bytes Ink can still interpret (Alt+key etc.).
+ this.write(held);
+ }, MouseSequenceFilter.HOLDBACK_FLUSH_MS);
+ (this.flushTimer as { unref?: () => void }).unref?.();
+ }
+
+ /** Drop timers (tests / teardown). */
+ dispose(): void {
+ if (this.flushTimer) clearTimeout(this.flushTimer);
+ this.flushTimer = null;
+ }
+}
+
+/** DECSET: bracketed paste on/off. On, the terminal wraps pasted text in
+ * `ESC[200~ … ESC[201~` so the filter can insert it literally. */
+export function bracketedPasteSequences(enable: boolean): string {
+ return enable ? '\x1b[?2004h' : '\x1b[?2004l';
}
/** Status-bar hint shown while the TUI is frozen (Ctrl+S scroll lock). The
@@ -748,7 +877,7 @@ export class CLIChannel extends BaseChannel {
*/
restoreTerminal(): void {
try {
- process.stdout.write(mouseTrackingSequences(false) + '\x1b[?25h');
+ process.stdout.write(mouseTrackingSequences(false) + bracketedPasteSequences(false) + '\x1b[?25h');
} catch { /* not a TTY */ }
}
@@ -1053,9 +1182,13 @@ export class CLIChannel extends BaseChannel {
};
// Reset mouse-report modes in case a previous run left the terminal
- // stuck emitting mouse sequences (1000/1002/1003 + SGR 1006).
+ // stuck emitting mouse sequences (1000/1002/1003 + SGR 1006), and turn
+ // on bracketed paste so multi-line pastes arrive as one literal chunk
+ // (the stdin filter strips the ESC[200~/201~ markers; see
+ // MouseSequenceFilter). Turned off again by restoreTerminal() and the
+ // output wrapper's dispose().
try {
- process.stdout.write('\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l');
+ process.stdout.write(mouseTrackingSequences(false) + bracketedPasteSequences(true));
} catch {
// Not a TTY or write failed — nothing to reset.
}
diff --git a/src/channels/mouse-filter.test.ts b/src/channels/mouse-filter.test.ts
index 1b8e7e18..925eb3c9 100644
--- a/src/channels/mouse-filter.test.ts
+++ b/src/channels/mouse-filter.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from 'vitest';
-import { MouseSequenceFilter, parseMouseSequence, mouseTrackingSequences } from './cli.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MouseSequenceFilter, parseMouseSequence, mouseTrackingSequences, bracketedPasteSequences } from './cli.js';
+import { PASTE_SENTINEL, FORWARD_DELETE_KEY } from '../ui/input-composer.js';
function collect() {
const events: Array<{ button: number; col: number; row: number; wheel: string | null; click: boolean; release: boolean; motion: boolean }> = [];
@@ -102,4 +103,92 @@ describe('parseMouseSequence edge cases', () => {
expect(parseMouseSequence('hello')).toBeNull();
expect(parseMouseSequence('\x1b[A')).toBeNull();
});
-});
\ No newline at end of file
+});
+
+describe('MouseSequenceFilter — bracketed paste and key rewrites', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('strips ESC[200~ / ESC[201~ and delivers the payload as ONE sentinel-tagged chunk', () => {
+ const { passthrough, filter } = collect();
+ filter.push('\x1b[200~line one\nline two\r\nline three\x1b[201~');
+ expect(passthrough).toEqual([PASTE_SENTINEL + 'line one\nline two\r\nline three']);
+ });
+
+ it('keeps typed text before and after a paste as separate chunks', () => {
+ const { passthrough, filter } = collect();
+ filter.push('ab\x1b[200~X\nY\x1b[201~cd');
+ expect(passthrough).toEqual(['ab', PASTE_SENTINEL + 'X\nY', 'cd']);
+ });
+
+ it('a pasted bare newline is paste payload, never an Enter keystroke', () => {
+ const { passthrough, filter } = collect();
+ filter.push('\x1b[200~\n\x1b[201~');
+ expect(passthrough).toEqual([PASTE_SENTINEL + '\n']);
+ });
+
+ it('joins a paste delivered across several stdin reads, end marker split mid-sequence', () => {
+ const { passthrough, filter } = collect();
+ filter.push('\x1b[20');
+ expect(passthrough).toEqual([]);
+ filter.push('0~first ');
+ filter.push('second\x1b[2');
+ filter.push('01~tail');
+ expect(passthrough.join('|')).toBe(`${PASTE_SENTINEL}first |${PASTE_SENTINEL}second|tail`);
+ });
+
+ it('drops ANSI colour escapes inside pasted text', () => {
+ const { passthrough, filter } = collect();
+ filter.push('\x1b[200~\x1b[31mred\x1b[0m\x1b[201~');
+ expect(passthrough).toEqual([PASTE_SENTINEL + 'red']);
+ });
+
+ it('never dispatches mouse events for sequences inside a paste', () => {
+ const { events, passthrough, filter } = collect();
+ filter.push('\x1b[200~\x1b[<64;5;6Mtext\x1b[201~');
+ expect(events).toHaveLength(0);
+ expect(passthrough).toEqual([PASTE_SENTINEL + 'text']);
+ });
+
+ it('rewrites every Shift+Enter / Ctrl+Enter encoding to Ctrl+N (newline)', () => {
+ for (const seq of ['\x1b[13;2u', '\x1b[13;5u', '\x1b[27;2;13~', '\x1b\r']) {
+ const { passthrough, filter } = collect();
+ filter.push('a' + seq + 'b');
+ expect(passthrough, JSON.stringify(seq)).toEqual(['a', '\x0e', 'b']);
+ }
+ });
+
+ it('rewrites the Delete key (ESC[3~) to the forward-delete sentinel, Home/End to Ctrl+A/Ctrl+E', () => {
+ const { passthrough, filter } = collect();
+ filter.push('\x1b[3~');
+ filter.push('\x1b[H');
+ filter.push('\x1b[F');
+ filter.push('\x1bOH\x1b[4~');
+ expect(passthrough).toEqual([FORWARD_DELETE_KEY, '\x01', '\x05', '\x01', '\x05']);
+ });
+
+ it('releases a lone Esc after the holdback window instead of fusing it with the next key', () => {
+ const { passthrough, filter } = collect();
+ filter.push('\x1b');
+ expect(passthrough).toEqual([]);
+ vi.advanceTimersByTime(MouseSequenceFilter.HOLDBACK_FLUSH_MS + 1);
+ expect(passthrough).toEqual(['\x1b']);
+ filter.push('x');
+ expect(passthrough).toEqual(['\x1b', 'x']);
+ filter.dispose();
+ });
+
+ it('a prefix completed within the window is still joined, not flushed early', () => {
+ const { passthrough, filter } = collect();
+ filter.push('\x1b[');
+ vi.advanceTimersByTime(5);
+ filter.push('A');
+ vi.advanceTimersByTime(100);
+ expect(passthrough).toEqual(['\x1b[A']);
+ });
+
+ it('bracketed paste DECSET/DECRST sequences', () => {
+ expect(bracketedPasteSequences(true)).toBe('\x1b[?2004h');
+ expect(bracketedPasteSequences(false)).toBe('\x1b[?2004l');
+ });
+});
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index c80b5110..78bf5b70 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -14,7 +14,7 @@ import { useTerminalSize as useSharedTerminalSize } from './use-terminal-size.js
import { buildMercuryMessageLines, buildMercuryBrandLines, buildStreamTailLines, parseChunkIndex, splitFinalMessage, splitStreamingMessage, type MercuryTranscriptLine } from './mercury-transcript.js';
import { GENERIC_PHASES, PLANNING_VERBS, lastUserText, pickStatusWord } from './status-word.js';
import { nextTip, rotateTip } from './tips.js';
-import { SLASH_COMMANDS, buildSlashSuggestions, buildSkillSuggestions, skillFillText, shouldSubmitSlash, pushHistoryLine, historyPrev, historyNext, insertInputChunk, backspaceAt, createInputHistoryState, SuggestionList, type SkillEntry } from './input-composer.js';
+import { SLASH_COMMANDS, buildSlashSuggestions, buildSkillSuggestions, skillFillText, shouldSubmitSlash, pushHistoryLine, historyPrev, historyNext, createInputHistoryState, SuggestionList, applyEditKey, isPasteChunk, graphemeAt, nextGraphemeBoundary, expandTabs, type EditorKey, type SkillEntry } from './input-composer.js';
import { PLAYER_CONTROLS, formatNowPlaying } from '../spotify/ui.js';
import type { SpotifyClient } from '../spotify/client.js';
import type { SubAgentStatus } from '../types/agent.js';
@@ -280,7 +280,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
useInput((ch, key) => {
const keyChar = (ch || (key as any)?.name || '').toLowerCase();
- const isEnter = key.return || (key as any)?.name === 'enter';
+ const isEnter = (key.return || (key as any)?.name === 'enter') && !isPasteChunk(ch);
const resolvePermissionAndMaybeContinue = (value: string | boolean) => {
const shouldAutoEnterChat = state.mode === 'splash' && state.permissionPrompt?.type === 'mode';
onPermissionResolve(value);
@@ -344,13 +344,8 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (key.ctrl && (ch === 'g' || ch === 'G')) { onInput('/code diff'); return; }
if (key.ctrl && (ch === 'o' || ch === 'O' || ch === '\x0f')) { onInput('/mc expand'); return; }
- // Ctrl+N newline in input
- if (key.ctrl && (ch === 'n' || ch === 'N' || ch === '\x0e')) {
- setInput((prev) => prev.slice(0, cursorPos) + '\n' + prev.slice(cursorPos));
- setCursorPos((p) => p + 1);
- return;
- }
-
+ // A bracketed paste is literal text — never Enter, even when the
+ // payload is a single "\n".
if (isEnter) {
const trimmed = input.trim();
if (trimmed) {
@@ -365,45 +360,30 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
if (key.tab) return;
- if (key.leftArrow) { setCursorPos((p) => Math.max(0, p - 1)); return; }
- if (key.rightArrow) { setCursorPos((p) => Math.min(input.length, p + 1)); return; }
// Transcript scrolling is terminal-native now (the transcript prints
// into scrollback via <Static>): ↑/↓ navigate input history instead.
// Shared composer history helpers (same behavior as chat mode).
- if (key.upArrow) {
+ if (key.upArrow && !key.meta && !key.ctrl) {
if (inputHistory.history.length === 0) return;
const h = historyPrev(inputHistory, input);
setInputHistory(h.state);
setInputAndCursor(h.input);
return;
}
- if (key.downArrow) {
+ if (key.downArrow && !key.meta && !key.ctrl) {
if (inputHistory.index === -1) return;
const h = historyNext(inputHistory);
setInputHistory(h.state);
setInputAndCursor(h.input);
return;
}
- if ((key as any).home) { setCursorPos(0); return; }
- if ((key as any).end) { setCursorPos(input.length); return; }
- // Readline-style cursor shortcuts (the old Ctrl+A/Ctrl+E scroll
- // bindings are gone with the in-app viewport).
- if (key.ctrl && (ch === 'a' || ch === 'A')) { setCursorPos(0); return; }
- if (key.ctrl && (ch === 'e' || ch === 'E')) { setCursorPos(input.length); return; }
- if (key.backspace || key.delete) {
- const del = backspaceAt(input, cursorPos);
- setInput(del.input);
- setCursorPos(del.cursorPos);
- return;
- }
- if (key.ctrl || key.meta) return;
-
- if (ch && ch.length > 0 && !key.escape) {
- // Shared composer char-insert (clean + cursor + flood guard in one
- // place — same pipeline as the attach TUI and chat mode).
- const next = insertInputChunk(input, cursorPos, ch);
- setInput(next.input);
- setCursorPos(next.cursorPos);
+ // Shared editing reducer: paste, newline (Ctrl+N / Shift+Enter),
+ // grapheme-aware cursor moves and deletes, word moves, Ctrl+W/U/K —
+ // one pipeline for the attach TUI, chat mode and Mercury Code.
+ const edited = applyEditKey(input, cursorPos, ch, key as EditorKey);
+ if (edited) {
+ setInput(edited.input);
+ setCursorPos(edited.cursorPos);
}
return;
}
@@ -671,13 +651,6 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
return;
}
- // Ctrl+N → insert newline (multi-line input)
- if (key.ctrl && (ch === 'n' || ch === 'N' || ch === '\x0e')) {
- setInput((prev) => prev.slice(0, cursorPos) + '\n' + prev.slice(cursorPos));
- setCursorPos((p) => p + 1);
- return;
- }
-
if (key.escape) {
if (state.mode === 'coding') {
onInput('/chat');
@@ -696,16 +669,6 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
return;
}
- // Left/right arrow: move cursor within input
- if (key.leftArrow) {
- setCursorPos((p) => Math.max(0, p - 1));
- return;
- }
- if (key.rightArrow) {
- setCursorPos((p) => Math.min(input.length, p + 1));
- return;
- }
-
// Up/down arrow: navigate slash suggestions when popup is visible
if (slashSuggestions.length > 0) {
if (key.upArrow) {
@@ -747,21 +710,13 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, spotifyC
return;
}
- if (key.backspace || key.delete) {
- const del = backspaceAt(input, cursorPos);
- setInput(del.input);
- setCursorPos(del.cursorPos);
- return;
- }
-
- if (key.ctrl || key.meta) return;
-
- if (ch && ch.length > 0 && !key.escape) {
- // Shared composer char-insert (clean + cursor + flood guard in one
- // place — same pipeline as the attach TUI and Mercury Code mode).
- const next = insertInputChunk(input, cursorPos, ch);
- setInput(next.input);
- setCursorPos(next.cursorPos);
+ // Shared editing reducer: paste, newline (Ctrl+N / Shift+Enter),
+ // grapheme-aware cursor moves and deletes, word moves, Ctrl+W/U/K —
+ // one pipeline for the attach TUI, chat mode and Mercury Code.
+ const edited = applyEditKey(input, cursorPos, ch, key as EditorKey);
+ if (edited) {
+ setInput(edited.input);
+ setCursorPos(edited.cursorPos);
}
});
@@ -2126,12 +2081,12 @@ function InputBox({
<Text color={promptColor} bold>{i === 0 ? '> ' : ' '}</Text>
{i === cursorLine ? (
<>
- <Text>{line.slice(0, cursorCol)}</Text>
- <Text inverse>{cursorCol < line.length ? line[cursorCol] : ' '}</Text>
- <Text>{cursorCol < line.length ? line.slice(cursorCol + 1) : ''}</Text>
+ <Text>{expandTabs(line.slice(0, cursorCol))}</Text>
+ <Text inverse>{cursorCol < line.length ? expandTabs(graphemeAt(line, cursorCol)) : ' '}</Text>
+ <Text>{cursorCol < line.length ? expandTabs(line.slice(nextGraphemeBoundary(line, cursorCol))) : ''}</Text>
</>
) : (
- <Text>{line}</Text>
+ <Text>{expandTabs(line)}</Text>
)}
</Box>
))}
@@ -2426,12 +2381,12 @@ function MercuryCodeInput({ input, cursorPos, mode, boxWidth }: { input: string;
<Text bold color={color}>{i === 0 ? '> ' : ' '}</Text>
{i === cursorLine ? (
<>
- <Text>{line.slice(0, cursorCol)}</Text>
- <Text inverse>{cursorCol < line.length ? line[cursorCol] : ' '}</Text>
- <Text>{cursorCol < line.length ? line.slice(cursorCol + 1) : ''}</Text>
+ <Text>{expandTabs(line.slice(0, cursorCol))}</Text>
+ <Text inverse>{cursorCol < line.length ? expandTabs(graphemeAt(line, cursorCol)) : ' '}</Text>
+ <Text>{cursorCol < line.length ? expandTabs(line.slice(nextGraphemeBoundary(line, cursorCol))) : ''}</Text>
</>
) : (
- <Text>{line}</Text>
+ <Text>{expandTabs(line)}</Text>
)}
</Box>
))}
diff --git a/src/ui/attach-tui.tsx b/src/ui/attach-tui.tsx
index 3b634963..de35ee84 100644
--- a/src/ui/attach-tui.tsx
+++ b/src/ui/attach-tui.tsx
@@ -13,8 +13,12 @@ import {
pushHistoryLine,
historyPrev,
historyNext,
- insertInputChunk,
- backspaceAt,
+ applyEditKey,
+ isPasteChunk,
+ graphemeAt,
+ nextGraphemeBoundary,
+ expandTabs,
+ type EditorKey,
SuggestionList,
type BotRosterEntry,
type SkillEntry,
@@ -364,7 +368,7 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
return;
}
- if (key.return) {
+ if (key.return && !isPasteChunk(ch)) {
const trimmed = input.trim();
if (!trimmed) return;
// Same Enter-fill contract as the main TUI: when the slash picker is
@@ -393,8 +397,6 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
void sendInput(trimmed);
return;
}
- if (key.leftArrow) { setCursorPos((p) => Math.max(0, p - 1)); return; }
- if (key.rightArrow) { setCursorPos((p) => Math.min(input.length, p + 1)); return; }
// ↑/↓ navigate suggestions when a picker is visible, else input history
// (shell-style, same helpers as the main TUI).
if (key.upArrow) {
@@ -442,17 +444,12 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
}
return;
}
- if (key.backspace || key.delete) {
- const next = backspaceAt(input, cursorPos);
- setInput(next.input);
- setCursorPos(next.cursorPos);
- return;
- }
- if (key.ctrl || key.meta) return;
- if (ch && ch.length > 0 && !key.escape) {
- const next = insertInputChunk(input, cursorPos, ch);
- setInput(next.input);
- setCursorPos(next.cursorPos);
+ // Shared editing reducer (same pipeline as the main TUI): paste,
+ // newline, grapheme-aware cursor moves and deletes, word moves.
+ const edited = applyEditKey(input, cursorPos, ch, key as EditorKey);
+ if (edited) {
+ setInput(edited.input);
+ setCursorPos(edited.cursorPos);
}
});
@@ -535,9 +532,9 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:
<Box borderStyle="round" borderColor="gray" flexDirection="column" paddingX={1} width={inputWidth}>
<Box>
<Text bold color="cyan">&gt; </Text>
- <Text>{input.slice(0, cursorPos)}</Text>
- <Text inverse>{cursorPos < input.length ? input[cursorPos] : ' '}</Text>
- <Text>{input.slice(cursorPos + 1)}</Text>
+ <Text>{expandTabs(input.slice(0, cursorPos))}</Text>
+ <Text inverse>{cursorPos < input.length ? expandTabs(graphemeAt(input, cursorPos)) : ' '}</Text>
+ <Text>{expandTabs(input.slice(nextGraphemeBoundary(input, cursorPos)))}</Text>
</Box>
</Box>
</Box>
diff --git a/src/ui/input-composer-keys.test.ts b/src/ui/input-composer-keys.test.ts
new file mode 100644
index 00000000..c4efd14e
--- /dev/null
+++ b/src/ui/input-composer-keys.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it } from 'vitest';
+import {
+ applyEditKey,
+ backspaceAt,
+ cleanPrintableInput,
+ ctrlCAction,
+ cursorColumn,
+ deleteForwardAt,
+ insertInputChunk,
+ isPasteChunk,
+ prevGraphemeBoundary,
+ nextGraphemeBoundary,
+ wordBoundaryLeft,
+ wordBoundaryRight,
+ CTRL_C_EXIT_WINDOW_MS,
+ FORWARD_DELETE_KEY,
+ PASTE_SENTINEL,
+ type EditorKey,
+} from './input-composer.js';
+
+const K = (k: Partial<EditorKey> = {}): EditorKey => k;
+
+/** Drive the reducer with a sequence of (ch, key) pairs. */
+function type(start: { input: string; cursorPos: number }, keys: Array<[string | undefined, EditorKey]>) {
+ let state = start;
+ for (const [ch, key] of keys) {
+ const next = applyEditKey(state.input, state.cursorPos, ch, key);
+ if (next) state = next;
+ }
+ return state;
+}
+
+describe('composer key handling — paste', () => {
+ it('cleanPrintableInput keeps newlines and tabs, normalises CRLF, drops control bytes', () => {
+ expect(cleanPrintableInput('a\r\nb\rc\td\x00\x07e\x1b[31m')).toBe('a\nb\nc\td' + 'e' + '[31m');
+ });
+
+ it('a multi-line paste (plain useInput chunk) inserts every line at the cursor', () => {
+ const r = insertInputChunk('xy', 1, 'one\ntwo\nthree');
+ expect(r.input).toBe('xone\ntwo\nthreey');
+ expect(r.cursorPos).toBe(1 + 'one\ntwo\nthree'.length);
+ });
+
+ it('a bracketed-paste chunk is a literal multi-line insert and never submits', () => {
+ const chunk = PASTE_SENTINEL + 'first\nsecond\n';
+ expect(isPasteChunk(chunk)).toBe(true);
+ // Ink reports a chunk ending in "\n" with no return flag; a chunk that
+ // IS "\n" would carry key.return — the reducer still inserts it.
+ const r = applyEditKey('', 0, chunk, K({ return: true }));
+ expect(r).toEqual({ input: 'first\nsecond\n', cursorPos: 13 });
+ const lone = applyEditKey('ab', 1, PASTE_SENTINEL + '\n', K({ return: true, name: 'enter' }));
+ expect(lone).toEqual({ input: 'a\nb', cursorPos: 2 });
+ });
+
+ it('the paste sentinel never lands in the buffer', () => {
+ const r = insertInputChunk('', 0, PASTE_SENTINEL + 'x' + PASTE_SENTINEL);
+ expect(r.input).toBe('x');
+ });
+
+ it('Shift+Enter (rewritten to Ctrl+N by the stdin filter) inserts a newline', () => {
+ const r = type({ input: 'ab', cursorPos: 1 }, [['n', K({ ctrl: true })], ['\x0e', K({ ctrl: true })]]);
+ expect(r).toEqual({ input: 'a\n\nb', cursorPos: 3 });
+ });
+
+ it('plain Enter is not an editing key (caller submits)', () => {
+ expect(applyEditKey('abc', 3, '', K({ return: true }))).toBeNull();
+ expect(applyEditKey('abc', 3, '\n', K({ name: 'enter' }))).toBeNull();
+ });
+
+ it('flood guard clamps without splitting a surrogate pair', () => {
+ const big = 'a'.repeat(7999);
+ const r = insertInputChunk(big, big.length, '😀😀');
+ expect(r.input.length).toBeLessThanOrEqual(8000);
+ expect(r.input.endsWith('a')).toBe(true); // the emoji could not fit whole
+ expect(/[\uD800-\uDBFF]$/.test(r.input)).toBe(false);
+ });
+});
+
+describe('composer key handling — Ctrl+C semantics', () => {
+ it('clears a non-empty input', () => {
+ expect(ctrlCAction('hello', null, 1000)).toBe('clear');
+ expect(ctrlCAction('hello', 900, 1000)).toBe('clear');
+ });
+
+ it('arms on an empty input and exits only on a second tap within the window', () => {
+ expect(ctrlCAction('', null, 1000)).toBe('arm');
+ expect(ctrlCAction('', 1000, 1000 + CTRL_C_EXIT_WINDOW_MS)).toBe('exit');
+ expect(ctrlCAction('', 1000, 1000 + CTRL_C_EXIT_WINDOW_MS + 1)).toBe('arm');
+ });
+});
+
+describe('composer key handling — grapheme-aware cursor', () => {
+ const family = '👨‍👩‍👧';
+ const flag = '🇯🇵';
+ const text = `a${family}b${flag}c`;
+
+ it('backspace removes a whole emoji ZWJ sequence, not a code unit', () => {
+ const pos = 1 + family.length;
+ expect(backspaceAt(text, pos)).toEqual({ input: `ab${flag}c`, cursorPos: 1 });
+ });
+
+ it('forward delete removes the grapheme under the cursor', () => {
+ expect(deleteForwardAt(text, 1)).toEqual({ input: `ab${flag}c`, cursorPos: 1 });
+ expect(applyEditKey(text, 1, FORWARD_DELETE_KEY, K())).toEqual({ input: `ab${flag}c`, cursorPos: 1 });
+ });
+
+ it('← / → step by grapheme and never stop inside a surrogate pair', () => {
+ expect(nextGraphemeBoundary(text, 1)).toBe(1 + family.length);
+ expect(prevGraphemeBoundary(text, 1 + family.length)).toBe(1);
+ const r = type({ input: text, cursorPos: 0 }, [['', K({ rightArrow: true })], ['', K({ rightArrow: true })]]);
+ expect(r.cursorPos).toBe(1 + family.length);
+ const l = type({ input: text, cursorPos: text.length }, [['', K({ leftArrow: true })], ['', K({ leftArrow: true })]]);
+ expect(l.cursorPos).toBe(1 + family.length + 1);
+ });
+
+ it('combining marks stay attached to their base', () => {
+ const s = 'éx'; // é as e + combining acute
+ expect(backspaceAt(s, 2)).toEqual({ input: 'x', cursorPos: 0 });
+ expect(nextGraphemeBoundary(s, 0)).toBe(2);
+ });
+
+ it('cursor column uses display width: CJK and emoji are two cells wide', () => {
+ expect(cursorColumn('日本語x', 3)).toBe(6);
+ expect(cursorColumn(`${family}x`, family.length)).toBe(2);
+ expect(cursorColumn('a\tb', 2)).toBe(3); // tab expands to two spaces
+ });
+});
+
+describe('composer key handling — readline editing', () => {
+ it('Ctrl+W deletes the previous word, Ctrl+U to line start, Ctrl+K to line end', () => {
+ expect(applyEditKey('foo bar baz', 11, 'w', K({ ctrl: true }))).toEqual({ input: 'foo bar ', cursorPos: 8 });
+ expect(applyEditKey('one\ntwo three', 7, 'u', K({ ctrl: true }))).toEqual({ input: 'one\n three', cursorPos: 4 });
+ expect(applyEditKey('one\ntwo three', 7, 'k', K({ ctrl: true }))).toEqual({ input: 'one\ntwo', cursorPos: 7 });
+ });
+
+ it('Alt+← / Alt+→ (and Alt+B / Alt+F, Ctrl+arrows) move by word', () => {
+ const s = 'alpha beta gamma';
+ expect(wordBoundaryLeft(s, s.length)).toBe(12);
+ expect(wordBoundaryRight(s, 0)).toBe(5);
+ expect(applyEditKey(s, s.length, '', K({ meta: true, leftArrow: true }))!.cursorPos).toBe(12);
+ expect(applyEditKey(s, 12, 'b', K({ meta: true }))!.cursorPos).toBe(6);
+ expect(applyEditKey(s, 0, 'f', K({ meta: true }))!.cursorPos).toBe(5);
+ expect(applyEditKey(s, 5, '', K({ ctrl: true, rightArrow: true }))!.cursorPos).toBe(10);
+ });
+
+ it('Ctrl+A / Ctrl+E go to the start / end of the CURRENT line in multi-line input', () => {
+ expect(applyEditKey('ab\ncd', 4, 'a', K({ ctrl: true }))!.cursorPos).toBe(3);
+ expect(applyEditKey('ab\ncd', 3, 'e', K({ ctrl: true }))!.cursorPos).toBe(5);
+ });
+
+ it('unbound control / meta chords are left to the caller', () => {
+ expect(applyEditKey('x', 1, 'p', K({ ctrl: true }))).toBeNull();
+ expect(applyEditKey('x', 1, 'z', K({ meta: true }))).toBeNull();
+ });
+});
diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsx
index 3f85e8e3..ac6ab41a 100644
--- a/src/ui/input-composer.tsx
+++ b/src/ui/input-composer.tsx
@@ -1,5 +1,6 @@
import React from 'react';
import { Box, Text } from 'ink';
+import stringWidth from 'string-width';
/**
* Shared input composer — ONE source of truth for the interactive input
@@ -241,21 +242,47 @@ export function historyNext(state: InputHistoryState): { state: InputHistoryStat
// ─── Character cleaning / paste safety ──────────────────────────────────────
+/**
+ * Private-use sentinels the stdin filter (channels/cli.ts
+ * `MouseSequenceFilter`) prepends to text that must NOT go through Ink's
+ * key parser as keystrokes:
+ *
+ * • `PASTE_SENTINEL` — the chunk is bracketed-paste payload (`ESC[200~ …
+ * ESC[201~`). It is inserted literally: a pasted `\n` is a newline in
+ * the buffer, never Enter.
+ * • `FORWARD_DELETE_KEY` — the terminal's real Delete key (`ESC[3~`). Ink
+ * folds that AND `\x7f` (Backspace on macOS/Linux) into `key.delete`,
+ * so the filter rewrites `ESC[3~` to this sentinel to keep them apart.
+ *
+ * Both live in the Unicode private-use area, so no keyboard produces them.
+ */
+export const PASTE_SENTINEL = '';
+export const FORWARD_DELETE_KEY = '';
+
+/** True when the raw `ch` from `useInput` is a bracketed-paste chunk. */
+export function isPasteChunk(ch: string | undefined): boolean {
+ return typeof ch === 'string' && ch.startsWith(PASTE_SENTINEL);
+}
+
/**
* Strip control bytes and escape-sequence fragments from a raw `ch` payload.
* Mouse scroll in raw mode emits SGR sequences like `\x1b[<0;row;colM` — Ink
* partially consumes `\x1b[` and leaks the tail as individual chars, so every
* surface must filter non-printables before accepting input.
+ *
+ * Newlines and tabs are KEPT (`\r\n` and lone `\r` normalise to `\n`): a
+ * multi-line paste must land as multi-line text, not collapse to one line.
+ * Only the control bytes that are never text are dropped.
*/
export function cleanPrintableInput(ch: string): string {
- return ch
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '')
- .split('')
- .filter((c) => {
- const code = c.charCodeAt(0);
- return (code >= 0x20 && code <= 0x7e) || code >= 0xa0;
- })
- .join('');
+ let out = '';
+ for (const c of ch.replace(/\r\n?/g, '\n')) {
+ const code = c.codePointAt(0) ?? 0;
+ if (code === 0x0a || code === 0x09) { out += c; continue; }
+ if (code === PASTE_SENTINEL.codePointAt(0) || code === FORWARD_DELETE_KEY.codePointAt(0)) continue;
+ if ((code >= 0x20 && code <= 0x7e) || code >= 0xa0) out += c;
+ }
+ return out;
}
/** Flood guard: never let a corrupt stream grow the input unboundedly. */
@@ -263,7 +290,8 @@ export const MAX_INPUT_LEN = 8000;
/**
* Insert a cleaned chunk at the cursor position with the flood guard applied.
- * Returns the (possibly clamped) new input + new cursor position.
+ * Returns the (possibly clamped) new input + new cursor position. Paste
+ * sentinels are stripped, so a bracketed chunk inserts as plain text.
*/
export function insertInputChunk(
input: string,
@@ -276,19 +304,283 @@ export function insertInputChunk(
if (next.length > MAX_INPUT_LEN) {
if (input.length >= MAX_INPUT_LEN) return { input, cursorPos };
const accepted = MAX_INPUT_LEN - input.length;
- return { input: next.slice(0, MAX_INPUT_LEN), cursorPos: cursorPos + Math.max(0, accepted) };
+ // Never cut a surrogate pair in half at the clamp boundary.
+ let cut = MAX_INPUT_LEN;
+ if (cut > 0 && cut < next.length && /[\uD800-\uDBFF]/.test(next[cut - 1]) && /[\uDC00-\uDFFF]/.test(next[cut])) cut -= 1;
+ const clamped = next.slice(0, cut);
+ return { input: clamped, cursorPos: Math.min(clamped.length, cursorPos + Math.max(0, accepted)) };
}
return { input: next, cursorPos: cursorPos + clean.length };
}
+// ─── Grapheme-aware cursor math ─────────────────────────────────────────────
+//
+// The input buffer is a JS string, so `cursorPos` is a UTF-16 offset. Every
+// cursor move and deletion below steps by *grapheme cluster* (emoji with
+// modifiers/ZWJ, CJK, combining marks) instead of by code unit, so a
+// backspace over "👨‍👩‍👧" removes the whole family instead of leaving a
+// broken half, and ← / → never land inside a surrogate pair.
+
+type Segmenter = { segment(input: string): Iterable<{ segment: string; index: number }> };
+const graphemeSegmenter: Segmenter | null = (() => {
+ try {
+ const S = (Intl as unknown as { Segmenter?: new (locale?: string, opts?: { granularity: string }) => Segmenter }).Segmenter;
+ return S ? new S(undefined, { granularity: 'grapheme' }) : null;
+ } catch {
+ return null;
+ }
+})();
+
+/** Split a string into grapheme clusters (code-point fallback without Intl.Segmenter). */
+export function graphemes(text: string): string[] {
+ if (text.length === 0) return [];
+ if (graphemeSegmenter) {
+ const out: string[] = [];
+ for (const { segment } of graphemeSegmenter.segment(text)) out.push(segment);
+ return out;
+ }
+ return Array.from(text);
+}
+
+/** UTF-16 offset of the grapheme boundary immediately before `pos` (0 at start). */
+export function prevGraphemeBoundary(text: string, pos: number): number {
+ if (pos <= 0) return 0;
+ const head = text.slice(0, Math.min(pos, text.length));
+ if (head.length === 0) return 0;
+ const parts = graphemes(head);
+ const last = parts[parts.length - 1] ?? '';
+ return head.length - last.length;
+}
+
+/** UTF-16 offset of the grapheme boundary immediately after `pos` (text.length at end). */
+export function nextGraphemeBoundary(text: string, pos: number): number {
+ if (pos >= text.length) return text.length;
+ const tail = text.slice(Math.max(0, pos));
+ if (graphemeSegmenter) {
+ for (const { segment } of graphemeSegmenter.segment(tail)) return pos + segment.length;
+ }
+ const first = Array.from(tail)[0] ?? '';
+ return pos + first.length;
+}
+
+/** The grapheme cluster that starts at `pos` ('' at end of text). */
+export function graphemeAt(text: string, pos: number): string {
+ return text.slice(pos, nextGraphemeBoundary(text, pos));
+}
+
+/** Text as the input box draws it: tabs become two spaces (Ink measures a
+ * raw tab as zero width while the terminal jumps to the next tab stop, so
+ * the cursor cell would drift). */
+export function expandTabs(text: string): string {
+ return text.replace(/\t/g, ' ');
+}
+
+/** Terminal column width of one grapheme cluster (East-Asian wide + emoji = 2). */
+export function graphemeWidth(cluster: string): number {
+ if (cluster.length === 0) return 0;
+ return stringWidth(expandTabs(cluster));
+}
+
+/** Terminal column width of a string (grapheme-aware, via `string-width`). */
+export function displayWidth(text: string): number {
+ return stringWidth(expandTabs(text));
+}
+
+/**
+ * Column (0-based) at which the cursor sits on `line` when `cursorCol` is a
+ * UTF-16 offset into it — i.e. the display width of the text before it.
+ */
+export function cursorColumn(line: string, cursorCol: number): number {
+ return displayWidth(line.slice(0, Math.max(0, Math.min(cursorCol, line.length))));
+}
+
+/** Backspace: delete the grapheme before the cursor. */
export function backspaceAt(input: string, cursorPos: number): { input: string; cursorPos: number } {
if (cursorPos <= 0) return { input, cursorPos };
+ const start = prevGraphemeBoundary(input, cursorPos);
return {
- input: input.slice(0, cursorPos - 1) + input.slice(cursorPos),
- cursorPos: cursorPos - 1,
+ input: input.slice(0, start) + input.slice(cursorPos),
+ cursorPos: start,
};
}
+/** Forward delete: delete the grapheme under the cursor. */
+export function deleteForwardAt(input: string, cursorPos: number): { input: string; cursorPos: number } {
+ if (cursorPos >= input.length) return { input, cursorPos };
+ const end = nextGraphemeBoundary(input, cursorPos);
+ return { input: input.slice(0, cursorPos) + input.slice(end), cursorPos };
+}
+
+/** Delete a range [from, to) and put the cursor at `from`. */
+function deleteRange(input: string, from: number, to: number): { input: string; cursorPos: number } {
+ if (from >= to) return { input, cursorPos: from };
+ return { input: input.slice(0, from) + input.slice(to), cursorPos: from };
+}
+
+const WORD_CHAR = /[\p{L}\p{N}_]/u;
+
+/** Start of the word before `pos` (readline `backward-word`). */
+export function wordBoundaryLeft(text: string, pos: number): number {
+ let p = Math.min(pos, text.length);
+ // Skip separators, then the word.
+ while (p > 0) {
+ const prev = prevGraphemeBoundary(text, p);
+ const g = text.slice(prev, p);
+ if (WORD_CHAR.test(g) || g === '\n') break;
+ p = prev;
+ }
+ if (p > 0 && text.slice(prevGraphemeBoundary(text, p), p) === '\n') return prevGraphemeBoundary(text, p);
+ while (p > 0) {
+ const prev = prevGraphemeBoundary(text, p);
+ if (!WORD_CHAR.test(text.slice(prev, p))) break;
+ p = prev;
+ }
+ return p;
+}
+
+/** End of the word after `pos` (readline `forward-word`). */
+export function wordBoundaryRight(text: string, pos: number): number {
+ let p = Math.max(0, pos);
+ while (p < text.length) {
+ const next = nextGraphemeBoundary(text, p);
+ const g = text.slice(p, next);
+ if (WORD_CHAR.test(g) || g === '\n') break;
+ p = next;
+ }
+ if (p < text.length && text.slice(p, nextGraphemeBoundary(text, p)) === '\n') return nextGraphemeBoundary(text, p);
+ while (p < text.length) {
+ const next = nextGraphemeBoundary(text, p);
+ if (!WORD_CHAR.test(text.slice(p, next))) break;
+ p = next;
+ }
+ return p;
+}
+
+/** Start offset of the line containing `pos`. */
+export function lineStart(text: string, pos: number): number {
+ const i = text.lastIndexOf('\n', Math.max(0, pos - 1));
+ return i < 0 ? 0 : i + 1;
+}
+
+/** End offset (exclusive) of the line containing `pos`. */
+export function lineEnd(text: string, pos: number): number {
+ const i = text.indexOf('\n', pos);
+ return i < 0 ? text.length : i;
+}
+
+// ─── Key reducer (shared by every surface) ──────────────────────────────────
+
+/** The subset of Ink's `Key` the editor cares about. */
+export interface EditorKey {
+ upArrow?: boolean;
+ downArrow?: boolean;
+ leftArrow?: boolean;
+ rightArrow?: boolean;
+ return?: boolean;
+ escape?: boolean;
+ ctrl?: boolean;
+ shift?: boolean;
+ tab?: boolean;
+ backspace?: boolean;
+ delete?: boolean;
+ meta?: boolean;
+ home?: boolean;
+ end?: boolean;
+ /** Ink's internal keypress name (`enter` for a bare `\n`). */
+ name?: string;
+}
+
+export interface EditResult {
+ input: string;
+ cursorPos: number;
+}
+
+/**
+ * Pure text-editing reducer for ONE keystroke. Returns the next buffer and
+ * cursor, or `null` when the key is not an editing key (the caller then
+ * applies its own bindings: submit, history, suggestions, mode shortcuts).
+ *
+ * Bindings (readline-style, identical on the main TUI, Mercury Code and
+ * the attach TUI):
+ *
+ * paste chunk insert literally (newlines kept, never Enter)
+ * Ctrl+N / Shift+Enter insert newline (the stdin filter maps Shift+Enter
+ * sequences to Ctrl+N)
+ * ← / → move one grapheme
+ * Alt+← / Alt+→, move one word
+ * Ctrl+← / Ctrl+→,
+ * Alt+B / Alt+F
+ * Home / End, line start / line end
+ * Ctrl+A / Ctrl+E
+ * Backspace delete grapheme before cursor
+ * Delete delete grapheme under cursor
+ * Ctrl+W delete word before cursor
+ * Ctrl+U delete to line start
+ * Ctrl+K delete to line end
+ * printable text insert at cursor
+ */
+export function applyEditKey(input: string, cursorPos: number, ch: string | undefined, key: EditorKey): EditResult | null {
+ const pos = Math.max(0, Math.min(cursorPos, input.length));
+ const c = ch ?? '';
+
+ if (isPasteChunk(c)) return insertInputChunk(input, pos, c);
+ if (c === FORWARD_DELETE_KEY) return deleteForwardAt(input, pos);
+
+ if (key.ctrl) {
+ const letter = c.toLowerCase();
+ if (letter === 'n' || c === '\x0e') return insertInputChunk(input, pos, '\n');
+ if (letter === 'a') return { input, cursorPos: lineStart(input, pos) };
+ if (letter === 'e') return { input, cursorPos: lineEnd(input, pos) };
+ if (letter === 'w') return deleteRange(input, wordBoundaryLeft(input, pos), pos);
+ if (letter === 'u') return deleteRange(input, lineStart(input, pos), pos);
+ if (letter === 'k') return deleteRange(input, pos, lineEnd(input, pos));
+ if (key.leftArrow) return { input, cursorPos: wordBoundaryLeft(input, pos) };
+ if (key.rightArrow) return { input, cursorPos: wordBoundaryRight(input, pos) };
+ return null;
+ }
+
+ if (key.meta) {
+ if (key.leftArrow || c === 'b') return { input, cursorPos: wordBoundaryLeft(input, pos) };
+ if (key.rightArrow || c === 'f') return { input, cursorPos: wordBoundaryRight(input, pos) };
+ // Alt+Backspace (ESC DEL) also deletes the previous word in most shells.
+ if (key.backspace || key.delete) return deleteRange(input, wordBoundaryLeft(input, pos), pos);
+ return null;
+ }
+
+ if (key.leftArrow) return { input, cursorPos: prevGraphemeBoundary(input, pos) };
+ if (key.rightArrow) return { input, cursorPos: nextGraphemeBoundary(input, pos) };
+ if (key.home) return { input, cursorPos: lineStart(input, pos) };
+ if (key.end) return { input, cursorPos: lineEnd(input, pos) };
+ if (key.backspace || key.delete) return backspaceAt(input, pos);
+
+ if (key.return || key.escape || key.tab || key.upArrow || key.downArrow || key.name === 'enter') return null;
+ if (c.length > 0) return insertInputChunk(input, pos, c);
+ return null;
+}
+
+// ─── Ctrl+C semantics ───────────────────────────────────────────────────────
+
+/** Second Ctrl+C within this window (on an empty input) exits. */
+export const CTRL_C_EXIT_WINDOW_MS = 1500;
+
+export type CtrlCAction = 'clear' | 'arm' | 'exit';
+
+/**
+ * Ctrl+C never kills the process on a single tap:
+ * • input non-empty → `clear` the input
+ * • input empty, not armed (or armed too long ago) → `arm` and show the
+ * "Press Ctrl+C again to exit" hint
+ * • input empty, armed within the window → `exit`
+ */
+export function ctrlCAction(input: string, armedAt: number | null, now: number): CtrlCAction {
+ if (input.length > 0) return 'clear';
+ if (armedAt != null && now - armedAt <= CTRL_C_EXIT_WINDOW_MS) return 'exit';
+ return 'arm';
+}
+
+/** Hint shown while a Ctrl+C exit is armed. */
+export const CTRL_C_EXIT_HINT = 'Press Ctrl+C again to exit';
+
// ─── Suggestion popup rendering ─────────────────────────────────────────────
/**
diff --git a/src/ui/resilient-output.ts b/src/ui/resilient-output.ts
index 9a3554ad..eee0ec01 100644
--- a/src/ui/resilient-output.ts
+++ b/src/ui/resilient-output.ts
@@ -2,6 +2,9 @@ import { EventEmitter } from 'node:events';
type TtyWriteStream = NodeJS.WriteStream;
+/** DECRST 2004 — mirrors `bracketedPasteSequences(false)` in channels/cli.ts. */
+const BRACKETED_PASTE_OFF = '\x1b[?2004l';
+
/**
* Keeps Ink alive when its primary terminal stream is closed unexpectedly.
* stderr normally points at the same TTY through a separate descriptor, so it
@@ -48,6 +51,10 @@ export class ResilientTuiOutput extends EventEmitter {
this.primary.off('error', this.onPrimaryError);
this.fallback.off('error', this.onFallbackError);
this.primary.off('resize', this.onResize);
+ // Bracketed paste is enabled for the TUI's lifetime; a shell left in
+ // that mode shows `ESC[200~` around every paste. Always reset it here —
+ // this runs on every teardown path, crash handlers included.
+ try { this.active.write(BRACKETED_PASTE_OFF); } catch { /* stream gone */ }
}
/**