The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli,tui): keep the draft and split pastes intact in the burst-Enter submit
Teknium488936121550
diff --git a/hermes_cli/cli_enter_burst.py b/hermes_cli/cli_enter_burst.pyindex aa644896f28..7c5a10af510 100644--- a/hermes_cli/cli_enter_burst.py+++ b/hermes_cli/cli_enter_burst.py@@ -14,7 +14,7 @@ keeps the newline.from __future__ import annotations-import time+from time import monotonicRAPID_INPUT_ENTER_WINDOW_S = 0.05# Long enough for the next read of a paste split across reads (slow SSH links), short enough@@ -29,25 +29,25 @@ def handle_burst_enter(cli, event, buf) -> bool:``cli._tui_submit_buffer(event, buf)`` is called later when this Enter turns out to end theburst."""- if time.monotonic() - getattr(cli, "_tui_last_text_change", 0.0) >= RAPID_INPUT_ENTER_WINDOW_S:+ now = monotonic()+ if now - 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_Scli._tui_burst_newline_at = now+ before = buf.document # the newline lands at the cursor, not necessarily at the endbuf.insert_text("\n")app = event.appkey_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+ with_newline = buf.documentchanged_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:+ if not app.is_running or buf.document != with_newline 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)+ buf.document = beforecli._tui_submit_buffer(event, buf)app.invalidate()diff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.pyindex 54b194ba162..f4fa0af2cd7 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 PTStylefrom prompt_toolkit.widgets import TextAreafrom typing import Optional+from hermes_cli import cli_enter_burst as _enter_burstfrom hermes_cli.cli_enter_burst import RAPID_INPUT_ENTER_WINDOW_S as _RAPID_INPUT_ENTER_WINDOW_Sfrom hermes_cli.cli_footer_split import FooterSplitfrom hermes_cli.cli_panel import _Panel@@ -1722,7 +1723,7 @@ class CLITuiMixin:tick), or the newline count jumped by 4+ (terminals that feed characters individuallybut batch newlines; Alt+Enter adds 1 newline per event so never trips it)."""- self._tui_last_text_change = time.monotonic()+ self._tui_last_text_change = _enter_burst.monotonic() # same clock as the burst checkfrom cli import _strip_leaked_bracketed_paste_wrappers, _strip_leaked_terminal_responses_with_metatext = _strip_leaked_bracketed_paste_wrappers(buf.text)text, _had_mouse_reports = _strip_leaked_terminal_responses_with_meta(text)diff --git a/tests/hermes_cli/test_cli_enter_burst.py b/tests/hermes_cli/test_cli_enter_burst.pyindex e3e0126bbce..0fb4eee181e 100644--- a/tests/hermes_cli/test_cli_enter_burst.py+++ b/tests/hermes_cli/test_cli_enter_burst.py@@ -3,7 +3,8 @@ submits, while Enters inside an unbracketed multi-line paste stay newlines (#109The real prompt_toolkit Buffer carries the text; the app exposes the two things the handler readsfrom 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.+the event loop, whose ``call_later`` is captured so the quiet-window callback runs on demand. The+burst clock is a controlled one, advanced explicitly, so a slow runner cannot change the verdict."""from __future__ import annotations@@ -11,22 +12,48 @@ import queuefrom collections import dequefrom types import SimpleNamespace+import pytestfrom prompt_toolkit.buffer import Buffer+from prompt_toolkit.document import Document+from hermes_cli import cli_enter_burst+from hermes_cli.cli_enter_burst import BURST_END_QUIET_S, RAPID_INPUT_ENTER_WINDOW_S-class _Loop:++class _Clock:def __init__(self):+ self.now = 1000.0++ def __call__(self):+ return self.now++ def advance(self, seconds):+ self.now += seconds+++class _Loop:+ def __init__(self, clock):+ self.clock = clockself.scheduled = []def call_later(self, delay, callback):- self.scheduled.append(callback)+ self.scheduled.append((delay, callback))def run_scheduled(self):+ """Let the quiet window elapse with no input, then fire what was scheduled."""pending, self.scheduled = self.scheduled, []- for callback in pending:+ for delay, callback in pending:+ self.clock.advance(delay)callback()+def clock(monkeypatch):+ fake = _Clock()+ monkeypatch.setattr(cli_enter_burst, "monotonic", fake)+ return fake++def _shell():from cli import HermesCLIshell = object.__new__(HermesCLI)@@ -44,8 +71,8 @@ def _shell():return shell-def _rig():- shell, buf, loop = _shell(), Buffer(), _Loop()+def _rig(clock):+ shell, buf, loop = _shell(), Buffer(), _Loop(clock)buf.on_text_changed += shell._tui_on_text_changedapp = SimpleNamespace(current_buffer=buf, invalidate=lambda: None, is_running=True,loop=loop, key_processor=SimpleNamespace(input_queue=deque()))@@ -64,19 +91,46 @@ def _submitted(shell):return items-def test_text_and_enter_in_one_write_submits():- shell, buf, loop, app = _rig()+def test_text_and_enter_in_one_write_submits_after_the_quiet_window(clock):+ shell, buf, loop, app = _rig(clock)buf.insert_text("/help")- _enter(shell, app, more_keys_in_read=False) # same read, within the rapid window+ _enter(shell, app, more_keys_in_read=False) # same read, same instant as the text+ # Not an ordinary submit: a provisional newline waits for the quiet window.+ assert _submitted(shell) == []+ assert buf.text == "/help\n"+ assert [delay for delay, _ in loop.scheduled] == [BURST_END_QUIET_S]loop.run_scheduled() # input stayed quietassert _submitted(shell) == ["/help"]assert buf.text == ""-def test_unbracketed_multiline_paste_keeps_newlines_and_never_submits():+def test_scripted_edit_inside_a_draft_submits_the_whole_draft(clock):+ """A script moves the cursor into an existing draft and writes text + Enter: the provisional+ newline lands at the cursor, so settling must restore the pre-Enter draft, not drop its last+ character."""+ shell, buf, loop, app = _rig(clock)+ buf.document = Document("hello world", cursor_position=5)+ clock.advance(10) # the draft was typed long ago+ buf.insert_text(", big") # the scripted write: text...+ _enter(shell, app, more_keys_in_read=False) # ...+ Enter in the same read+ assert buf.text == "hello, big\n world"+ loop.run_scheduled()+ assert _submitted(shell) == ["hello, big world"]+++def test_enter_after_a_pause_is_an_ordinary_submit(clock):+ shell, buf, loop, app = _rig(clock)+ buf.insert_text("hi")+ clock.advance(RAPID_INPUT_ENTER_WINDOW_S * 2) # a human-scale gap before Enter+ _enter(shell, app, more_keys_in_read=False)+ assert _submitted(shell) == ["hi"]+ assert loop.scheduled == []+++def test_unbracketed_multiline_paste_keeps_newlines_and_never_submits(clock):"""One read: line + Enter + line + Enter + line + Enter (tmux paste-buffer without -p, witha trailing newline), then a paste split across reads; nothing is submitted in either."""- shell, buf, loop, app = _rig()+ shell, buf, loop, app = _rig(clock)buf.insert_text("line one")_enter(shell, app, more_keys_in_read=True)buf.insert_text("line two")@@ -87,9 +141,10 @@ def test_unbracketed_multiline_paste_keeps_newlines_and_never_submits():assert buf.text == "line one\nline two\nline three\n"assert _submitted(shell) == []- shell, buf, loop, app = _rig()+ shell, buf, loop, app = _rig(clock)buf.insert_text("chunk one")_enter(shell, app, more_keys_in_read=False) # the read ended right after this Enter...+ clock.advance(BURST_END_QUIET_S / 5)buf.insert_text("chunk two") # ...and the next read arrived in the windowloop.run_scheduled()assert buf.text == "chunk one\nchunk two"diff --git a/ui-tui/packages/hermes-ink/src/ink/components/App.tsx b/ui-tui/packages/hermes-ink/src/ink/components/App.tsxindex 136f08903d8..ecf18b8f88d 100644--- a/ui-tui/packages/hermes-ink/src/ink/components/App.tsx+++ b/ui-tui/packages/hermes-ink/src/ink/components/App.tsx@@ -11,6 +11,7 @@ import { InputEvent } from '../events/input-event.js'import { TerminalFocusEvent } from '../events/terminal-focus-event.js'import instances from '../instances.js'import {+ BURST_END_QUIET_MS,DECRPM_STATUS,INITIAL_STATE,type ParsedInput,@@ -511,7 +512,7 @@ export default class App extends PureComponent<Props, State> {// Only proceed if we have an incomplete escape sequence or an unterminated// bracketed paste. Missing paste-end markers otherwise leave every later// keystroke trapped in the paste buffer.- if (!this.keyParseState.incomplete && this.keyParseState.mode !== 'IN_PASTE') {+ if (!this.keyParseState.incomplete && this.keyParseState.mode !== 'IN_PASTE' && !this.keyParseState.pendingReturn) {return}@@ -524,10 +525,7 @@ export default class App extends PureComponent<Props, State> {// drain stdin next and clear this timer. Prevents both the spurious// Escape key and the lost scroll event.if (this.props.stdin.readableLength > 0) {- this.incompleteEscapeTimer = setTimeout(- this.flushIncomplete,- this.keyParseState.mode === 'IN_PASTE' ? this.PASTE_TIMEOUT : this.NORMAL_TIMEOUT- )+ this.incompleteEscapeTimer = setTimeout(this.flushIncomplete, this.flushTimeout())return}@@ -555,18 +553,23 @@ export default class App extends PureComponent<Props, State> {// If we have incomplete escape sequences or an unterminated paste, set a// timer to flush/reset them. Paste starts are complete CSI sequences, so// checking only `incomplete` would never arm the watchdog.- if (this.keyParseState.incomplete || this.keyParseState.mode === 'IN_PASTE') {+ // A held trailing CR (scripted `text` + Enter) is released by the same flush.+ if (this.keyParseState.incomplete || this.keyParseState.mode === 'IN_PASTE' || this.keyParseState.pendingReturn) {// Cancel any existing timer firstif (this.incompleteEscapeTimer) {clearTimeout(this.incompleteEscapeTimer)}- this.incompleteEscapeTimer = setTimeout(- this.flushIncomplete,- this.keyParseState.mode === 'IN_PASTE' ? this.PASTE_TIMEOUT : this.NORMAL_TIMEOUT- )+ this.incompleteEscapeTimer = setTimeout(this.flushIncomplete, this.flushTimeout())}}+ flushTimeout = (): number => {+ if (this.keyParseState.mode === 'IN_PASTE') {+ return this.PASTE_TIMEOUT+ }++ return this.keyParseState.pendingReturn ? BURST_END_QUIET_MS : this.NORMAL_TIMEOUT+ }handleReadable = (): void => {// Detect long stdin gaps (tmux attach, ssh reconnect, laptop wake).// The terminal may have reset DEC private modes; re-assert mousediff --git a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.ts b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.test.tsindex 99b97362640..4d8ecef95c8 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@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { INITIAL_STATE, parseMultipleKeypresses } from './parse-keypress.js'+import { BURST_END_QUIET_MS, INITIAL_STATE, parseMultipleKeypresses } from './parse-keypress.js'import { PASTE_END, PASTE_START } from './termio/csi.js'describe('legacy modified return parsing', () => {@@ -135,11 +135,39 @@ 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)', () => {+ it('submits a single-line read ending in CR once input stays quiet (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')+ const [keys, held] = parseMultipleKeypresses(INITIAL_STATE, '/help\r', 1_000)- expect(keys).toEqual([expect.objectContaining({ raw: '/help' }), expect.objectContaining({ name: 'return' })])+ expect(keys).toEqual([expect.objectContaining({ raw: '/help' })])+ expect(held.pendingReturn).toBe(true)++ const [flushed, after] = parseMultipleKeypresses(held, null, 1_000 + BURST_END_QUIET_MS)++ expect(flushed).toEqual([expect.objectContaining({ name: 'return' })])+ expect(after.pendingReturn).toBe(false)+ })++ it('keeps every CR of a non-bracketed paste split across reads as content', () => {+ // Tail read: 'line one\rline ' then 'two\r' inside the quiet window.+ const [first, mid] = parseMultipleKeypresses(INITIAL_STATE, 'line one\rline ', 1_000)+ const [second, end] = parseMultipleKeypresses(mid, 'two\r', 1_010)+ const [flushed] = parseMultipleKeypresses(end, null, 1_010 + BURST_END_QUIET_MS)++ expect([...first, ...second, ...flushed]).toEqual([+ expect.objectContaining({ raw: 'line one\rline ' }),+ expect.objectContaining({ raw: 'two\r' })+ ])++ // Head read: 'line one\r' then 'line two' inside the quiet window.+ const [a, held] = parseMultipleKeypresses(INITIAL_STATE, 'line one\r', 2_000)+ const [b, rest] = parseMultipleKeypresses(held, 'line two', 2_010)+ const [c] = parseMultipleKeypresses(rest, null, 2_010 + BURST_END_QUIET_MS)++ expect([...a, ...b, ...c]).toEqual([+ expect.objectContaining({ raw: 'line one' }),+ expect.objectContaining({ raw: '\rline two' })+ ])})it('keeps the trailing CR of a multi-line non-bracketed paste inside the text token', () => {diff --git a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.tsindex f6f73f0f11b..a021b6bd895 100644--- a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts+++ b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts@@ -216,11 +216,6 @@ 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)@@ -232,12 +227,6 @@ 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@@ -267,6 +256,10 @@ export type KeyParseState = {mode: 'NORMAL' | 'IN_PASTE'incomplete: stringpasteBuffer: string+ // CR held back from the end of a single-line read; see BURST_END_QUIET_MS.+ pendingReturn?: boolean+ // When a read last carried a line break as text (non-bracketed paste).+ lastPastedBreakAt?: number// Internal tokenizer instance_tokenizer?: Tokenizer}@@ -277,6 +270,49 @@ export const INITIAL_STATE: KeyParseState = {pasteBuffer: ''}+// A read that is one line of text ending in CR is either a scripted `text` ++// Enter write (`tmux send-keys 'text' Enter`, a PTY write of `text\r`) or the+// first chunk of a non-bracketed paste split across reads. The CR is held for+// this long: a flush with nothing else read turns it into `return` (submit);+// any read inside the window makes it paste content. A read ending in CR within+// this window of another read that carried a pasted line break is the tail of+// that paste and stays content. Mirrors hermes_cli/cli_enter_burst.py.+export const BURST_END_QUIET_MS = 250++interface TextBurst {+ pendingReturn: boolean+ lastPastedBreakAt: number+}++// A CR held from the previous read: a flush (or an escape sequence, which is+// no paste chunk) releases it as `return`; text read inside the window takes+// it as the line break of a split paste.+function resumeHeldReturn(prevState: KeyParseState, input: string, isFlush: boolean): [ParsedKey[], string] {+ if (!prevState.pendingReturn) {+ return [[], input]+ }++ return isFlush || input.startsWith('\x1b') ? [[parseKeypress('\r')], input] : [[], '\r' + input]+}++// `tailOfRead`: the last token of the read, with no escape sequence buffered.+function parseTextToken(text: string, burst: TextBurst, tailOfRead: boolean, now: number): ParsedKey[] {+ const body = text.slice(0, -1)+ const singleLineEndingInCr = Boolean(body) && text.endsWith('\r') && !/[\r\n]/.test(body)++ if (tailOfRead && singleLineEndingInCr && now - burst.lastPastedBreakAt >= BURST_END_QUIET_MS) {+ burst.pendingReturn = true++ return parseTextKeypresses(body)+ }++ if (text.length > 1 && /[\r\n]/.test(text)) {+ burst.lastPastedBreakAt = now+ }++ return parseTextKeypresses(text)+}+function inputToString(input: Buffer | string): string {if (Buffer.isBuffer(input)) {if (input[0]! > 127 && input[1] === undefined) {@@ -297,10 +333,13 @@ function inputToString(input: Buffer | string): string {export function parseMultipleKeypresses(prevState: KeyParseState,- input: Buffer | string | null = ''+ input: Buffer | string | null = '',+ now: number = Date.now()): [ParsedInput[], KeyParseState] {const isFlush = input === null- const inputString = isFlush ? '' : inputToString(input)+ const [held, inputString] = resumeHeldReturn(prevState, isFlush ? '' : inputToString(input), isFlush)+ const keys: ParsedInput[] = [...held]+ const burst: TextBurst = { pendingReturn: false, lastPastedBreakAt: prevState.lastPastedBreakAt ?? -Infinity }// Get or create tokenizerconst tokenizer = prevState._tokenizer ?? createTokenizer({ x10Mouse: true, legacyAltEnter: true })@@ -309,11 +348,10 @@ export function parseMultipleKeypresses(const tokens = isFlush ? tokenizer.flush() : tokenizer.feed(inputString)// Convert tokens to parsed keys, handling paste mode- const keys: ParsedInput[] = []let inPaste = prevState.mode === 'IN_PASTE'let pasteBuffer = prevState.pasteBuffer- for (const token of tokens) {+ for (const [index, token] of tokens.entries()) {if (token.type === 'sequence') {if (token.value === PASTE_START) {inPaste = true@@ -357,7 +395,7 @@ export function parseMultipleKeypresses(const resynthesized = '\x1b' + token.valuekeys.push(parseKeypress(resynthesized))} else {- keys.push(...parseTextKeypresses(token.value))+ keys.push(...parseTextToken(token.value, burst, index === tokens.length - 1 && !tokenizer.buffer(), now))}}}@@ -379,6 +417,8 @@ export function parseMultipleKeypresses(mode: inPaste ? 'IN_PASTE' : 'NORMAL',incomplete: tokenizer.buffer(),pasteBuffer,+ pendingReturn: burst.pendingReturn,+ lastPastedBreakAt: burst.lastPastedBreakAt,_tokenizer: tokenizer}diff --git a/ui-tui/src/components/textInput.tsx b/ui-tui/src/components/textInput.tsxindex f650e926fba..daca6ae643f 100644--- a/ui-tui/src/components/textInput.tsx+++ b/ui-tui/src/components/textInput.tsx@@ -796,11 +796,6 @@ 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()@@ -963,7 +958,7 @@ export function TextInput({lineWidthRef.current = stringWidth(value.includes('\n') ? value.slice(value.lastIndexOf('\n') + 1) : value)undo.current = []redo.current = []- }, [value, submitSeq])+ }, [value])// The composer unmounts while full-screen monitors own input. Keep its// insertion point with the shell, not with transient steer/secret inputs.@@ -1460,7 +1455,6 @@ export function TextInput({if (insertNewline) {commit(ins(pending.value, pending.cursor, '\n'), pending.cursor + 1)} else {- setSubmitSeq(n => n + 1)cbSubmit.current?.(pending.value)}