Skip to content

The agent that grows with you

fix(cli,tui): text + Enter in one write submits instead of inserting a newline

Teknium2432e31e2b54
diff --git a/hermes_cli/cli_enter_burst.py b/hermes_cli/cli_enter_burst.py
new file mode 100644
index 00000000000..aa644896f28
--- /dev/null
+++ b/hermes_cli/cli_enter_burst.py
@@ -0,0 +1,55 @@
+"""Enter arriving inside a fast input burst: pasted newline or scripted submit.
+
+Paste without bracketed paste (tmux ``paste-buffer`` without ``-p``) and IME/voice dictation
+deliver every newline as its own Enter key right behind the text, so an Enter within
+``RAPID_INPUT_ENTER_WINDOW_S`` of the last buffer change is a line break, not a submit (#10994).
+A script typing ``text`` + Enter in ONE write (``tmux send-keys 'text' Enter``, a PTY write of
+``text\\r``) looks identical up to that Enter, except nothing follows it and no other Enter came
+before it. So an Enter with more keys of the same read still queued stays a newline, and so does
+the last Enter of a burst that already held one (the tail of a multi-line paste). The lone Enter
+that ends a burst inserts a provisional newline and submits once input has stayed quiet for
+``BURST_END_QUIET_S``; any input in that window (the next chunk of a paste split across reads)
+keeps the newline.
+"""
+
+from __future__ import annotations
+
+import time
+
+RAPID_INPUT_ENTER_WINDOW_S = 0.05
+# Long enough for the next read of a paste split across reads (slow SSH links), short enough
+# that a scripted submit still feels immediate. Humans never reach this path: their Enter comes
+# more than RAPID_INPUT_ENTER_WINDOW_S after the last keystroke.
+BURST_END_QUIET_S = 0.25
+
+
+def handle_burst_enter(cli, event, buf) -> bool:
+ """Handle an Enter that arrived mid-burst; False when it is an ordinary (human) Enter.
+
+ ``cli._tui_submit_buffer(event, buf)`` is called later when this Enter turns out to end the
+ burst.
+ """
+ if time.monotonic() - getattr(cli, "_tui_last_text_change", 0.0) >= RAPID_INPUT_ENTER_WINDOW_S:
+ return False
+ now = time.monotonic()
+ pasted_newline_before = now - getattr(cli, "_tui_burst_newline_at", 0.0) < BURST_END_QUIET_S
+ cli._tui_burst_newline_at = now
+ buf.insert_text("\n")
+ app = event.app
+ key_processor = getattr(app, "key_processor", None)
+ loop = getattr(app, "loop", None)
+ if key_processor is None or loop is None or key_processor.input_queue or pasted_newline_before:
+ return True # inside (or the tail of) a multi-line paste
+ snapshot = buf.text
+ changed_at = getattr(cli, "_tui_last_text_change", 0.0)
+
+ def _settle() -> None:
+ if not app.is_running or buf.text != snapshot or cli._tui_last_text_change != changed_at:
+ return # more input arrived (or the buffer was edited): the newline stays
+ buf.text = snapshot[:-1]
+ buf.cursor_position = len(buf.text)
+ cli._tui_submit_buffer(event, buf)
+ app.invalidate()
+
+ loop.call_later(BURST_END_QUIET_S, _settle)
+ return True
diff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.py
index 47fd6bc1cea..54b194ba162 100644
--- a/hermes_cli/cli_tui_mixin.py
+++ b/hermes_cli/cli_tui_mixin.py
@@ -39,6 +39,7 @@ from prompt_toolkit.styles import Style as PTStyle
from prompt_toolkit.widgets import TextArea
from typing import Optional
+from hermes_cli.cli_enter_burst import RAPID_INPUT_ENTER_WINDOW_S as _RAPID_INPUT_ENTER_WINDOW_S
from hermes_cli.cli_footer_split import FooterSplit
from hermes_cli.cli_panel import _Panel
from hermes_cli.cli_tui_wrap import _prefix_wrapped_rows, _wrap_rows
@@ -46,8 +47,6 @@ from hermes_cli.cli_tui_wrap import _prefix_wrapped_rows, _wrap_rows
# Rows below an overlay panel taken by spinner/tool-progress, status bar, input, separators and
# prompt symbol (measured ~6 during live PTY approval prompts) — shared by every panel budget.
_PANEL_RESERVED_BELOW = 6
-# Enter within this many seconds of the last buffer change is a pasted/dictated newline, not a submit.
-_RAPID_INPUT_ENTER_WINDOW_S = 0.05
_TYPING_CHARS = string.digits + string.ascii_letters + "-_.:/ "
# Approval-choice identifiers (protocol tokens, never translated) → catalog keys for their labels.
@@ -1396,10 +1395,7 @@ class CLITuiMixin:
redirect / interrupt queue / next-turn queue); idle → ``_pending_input``. Slash and bang
commands always take the local-dispatch path (never steer/interrupt text to the model).
"""
- from cli import (
- _apply_backslash_line_continuation,
- _is_backslash_line_continuation,
- _looks_like_slash_command)
+ from cli import _apply_backslash_line_continuation, _is_backslash_line_continuation
if self._tui_enter_overlay(event):
return
buf = event.app.current_buffer
@@ -1415,14 +1411,15 @@ class CLITuiMixin:
buf.cursor_position = len(continued)
event.app.invalidate()
return
- # Paste without bracketed-paste (tmux strips it) and IME/voice dictation deliver each
- # newline as its own Enter key event; the buffer collapse in _tui_on_text_changed only
- # sees whole-chunk pastes. Text still arriving (<50 ms since the last change) means this
- # Enter is a line break inside one message, not a submit (#10994).
- if time.monotonic() - getattr(self, "_tui_last_text_change", 0.0) < _RAPID_INPUT_ENTER_WINDOW_S:
- buf.insert_text("\n")
- return
- text = raw_text.strip()
+ # Enter mid-burst: a pasted newline (#10994), or the end of a scripted `text`+Enter write.
+ from hermes_cli.cli_enter_burst import handle_burst_enter
+ if not handle_burst_enter(self, event, buf):
+ self._tui_submit_buffer(event, buf)
+
+ def _tui_submit_buffer(self, event, buf):
+ """Submit the composer: inline commands, busy routing or ``_pending_input``."""
+ from cli import _looks_like_slash_command
+ text = buf.text.strip()
has_images = bool(self._attached_images)
if not (text or has_images):
return
diff --git a/tests/hermes_cli/test_cli_enter_burst.py b/tests/hermes_cli/test_cli_enter_burst.py
new file mode 100644
index 00000000000..e3e0126bbce
--- /dev/null
+++ b/tests/hermes_cli/test_cli_enter_burst.py
@@ -0,0 +1,96 @@
+"""Text + Enter arriving in ONE read (``tmux send-keys 'text' Enter``, a PTY write of ``text\\r``)
+submits, while Enters inside an unbracketed multi-line paste stay newlines (#10994).
+
+The real prompt_toolkit Buffer carries the text; the app exposes the two things the handler reads
+from prompt_toolkit: the key processor's queue (keys of the same read still to be processed) and
+the event loop, whose ``call_later`` is captured so the quiet-window callback runs on demand.
+"""
+from __future__ import annotations
+
+import queue
+from collections import deque
+from types import SimpleNamespace
+
+from prompt_toolkit.buffer import Buffer
+
+
+class _Loop:
+ def __init__(self):
+ self.scheduled = []
+
+ def call_later(self, delay, callback):
+ self.scheduled.append(callback)
+
+ def run_scheduled(self):
+ pending, self.scheduled = self.scheduled, []
+ for callback in pending:
+ callback()
+
+
+def _shell():
+ from cli import HermesCLI
+ shell = object.__new__(HermesCLI)
+ shell._tui_enter_overlay = lambda event: False
+ shell._tui_multiline_shortcuts = False
+ shell._attached_images = []
+ shell._agent_running = False
+ shell._pending_input = queue.Queue()
+ shell._tui_enter_inline_command = lambda *a, **k: False
+ shell._inline_pastes = lambda buffer: None
+ shell._tui_paste_counter = 0
+ shell.config = {}
+ shell._tui_prev_text_len = shell._tui_prev_newline_count = 0
+ shell._tui_paste_just_collapsed = shell._skip_paste_collapse = False
+ return shell
+
+
+def _rig():
+ shell, buf, loop = _shell(), Buffer(), _Loop()
+ buf.on_text_changed += shell._tui_on_text_changed
+ app = SimpleNamespace(current_buffer=buf, invalidate=lambda: None, is_running=True,
+ loop=loop, key_processor=SimpleNamespace(input_queue=deque()))
+ return shell, buf, loop, app
+
+
+def _enter(shell, app, *, more_keys_in_read: bool):
+ app.key_processor.input_queue = deque(["next-key"] if more_keys_in_read else [])
+ shell._tui_handle_enter(SimpleNamespace(app=app))
+
+
+def _submitted(shell):
+ items = []
+ while not shell._pending_input.empty():
+ items.append(shell._pending_input.get_nowait())
+ return items
+
+
+def test_text_and_enter_in_one_write_submits():
+ shell, buf, loop, app = _rig()
+ buf.insert_text("/help")
+ _enter(shell, app, more_keys_in_read=False) # same read, within the rapid window
+ loop.run_scheduled() # input stayed quiet
+ assert _submitted(shell) == ["/help"]
+ assert buf.text == ""
+
+
+def test_unbracketed_multiline_paste_keeps_newlines_and_never_submits():
+ """One read: line + Enter + line + Enter + line + Enter (tmux paste-buffer without -p, with
+ a trailing newline), then a paste split across reads; nothing is submitted in either."""
+ shell, buf, loop, app = _rig()
+ buf.insert_text("line one")
+ _enter(shell, app, more_keys_in_read=True)
+ buf.insert_text("line two")
+ _enter(shell, app, more_keys_in_read=True)
+ buf.insert_text("line three")
+ _enter(shell, app, more_keys_in_read=False) # trailing newline of the paste
+ loop.run_scheduled()
+ assert buf.text == "line one\nline two\nline three\n"
+ assert _submitted(shell) == []
+
+ shell, buf, loop, app = _rig()
+ buf.insert_text("chunk one")
+ _enter(shell, app, more_keys_in_read=False) # the read ended right after this Enter...
+ buf.insert_text("chunk two") # ...and the next read arrived in the window
+ loop.run_scheduled()
+ assert buf.text == "chunk one\nchunk two"
+ assert _submitted(shell) == []
diff --git a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts
index aab69e53851..99b97362640 100644
--- a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts
+++ b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts
@@ -134,6 +134,19 @@ describe('parseMultipleKeypresses text control splitting', () => {
expect(keys).toEqual([expect.objectContaining({ raw: 'a\rb' })])
})
+
+ it('peels the CR ending a single-line read into return (scripted text + Enter in one write)', () => {
+ // `tmux send-keys '/help' Enter` and a PTY write of `/help\r` arrive as one read.
+ const [keys] = parseMultipleKeypresses(INITIAL_STATE, '/help\r')
+
+ expect(keys).toEqual([expect.objectContaining({ raw: '/help' }), expect.objectContaining({ name: 'return' })])
+ })
+
+ it('keeps the trailing CR of a multi-line non-bracketed paste inside the text token', () => {
+ const [keys] = parseMultipleKeypresses(INITIAL_STATE, 'line one\rline two\r')
+
+ expect(keys).toEqual([expect.objectContaining({ raw: 'line one\rline two\r' })])
+ })
})
describe('parseMultipleKeypresses CSI u (Kitty keyboard protocol)', () => {
diff --git a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts
index 63165643d81..f6f73f0f11b 100644
--- a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts
+++ b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts
@@ -216,6 +216,11 @@ function splitNumericParams(params: string): number[] {
// token only happens for non-bracketed paste, where peeling it into a
// `return` keypress would prematurely submit the composer. Leaving them in
// the token preserves the existing paste/return handling byte-for-byte.
+// The one exception is a single-line token ENDING in CR: nothing follows the
+// CR in the read and no other line break precedes it, so it is the Enter of a
+// scripted `text` + Enter write (`tmux send-keys 'text' Enter`, a PTY write of
+// `text\r`) and is peeled into its own `return`. A multi-line token keeps its
+// trailing CR as paste content, exactly as before.
function isControlChar(ch: string): boolean {
const code = ch.charCodeAt(0)
@@ -227,6 +232,12 @@ function isControlChar(ch: string): boolean {
}
function parseTextKeypresses(text: string): ParsedKey[] {
+ const body = text.slice(0, -1)
+
+ if (body && text.endsWith('\r') && !/[\r\n]/.test(body)) {
+ return [...parseTextKeypresses(body), parseKeypress('\r')]
+ }
+
const keys: ParsedKey[] = []
let textStart = 0
diff --git a/ui-tui/src/components/textInput.tsx b/ui-tui/src/components/textInput.tsx
index daca6ae643f..f650e926fba 100644
--- a/ui-tui/src/components/textInput.tsx
+++ b/ui-tui/src/components/textInput.tsx
@@ -796,6 +796,11 @@ export function TextInput({
)
const [sel, setSel] = useState<null | { end: number; start: number }>(null)
+ // Bumped on every submit so the value-sync effect below re-runs even when the parent's value
+ // ends where it started: text + Return in ONE stdin read (`tmux send-keys 'text' Enter`) emits
+ // the text and the submit's clear in the same React batch, so `value` never visibly changes and
+ // the submitted text would stay in the composer.
+ const [submitSeq, setSubmitSeq] = useState(0)
const fwdDel = useFwdDelete(focus)
const termFocus = useTerminalFocus()
const { stdout } = useStdout()
@@ -958,7 +963,7 @@ export function TextInput({
lineWidthRef.current = stringWidth(value.includes('\n') ? value.slice(value.lastIndexOf('\n') + 1) : value)
undo.current = []
redo.current = []
- }, [value])
+ }, [value, submitSeq])
// The composer unmounts while full-screen monitors own input. Keep its
// insertion point with the shell, not with transient steer/secret inputs.
@@ -1455,6 +1460,7 @@ export function TextInput({
if (insertNewline) {
commit(ins(pending.value, pending.cursor, '\n'), pending.cursor + 1)
} else {
+ setSubmitSeq(n => n + 1)
cbSubmit.current?.(pending.value)
}