The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): stop raw CSI bytes from Shift+Space leaking into buffer (#88071)
webtecnica839de43d52eb
diff --git a/cli.py b/cli.pyindex 916d0c1e1a2..15928035584 100644--- a/cli.py+++ b/cli.py@@ -82,6 +82,7 @@ try:install_cmd_backspace_alias,install_ctrl_enter_alias,install_ignored_terminal_sequences,+ install_keypress_data_normalization,install_modify_other_keys_aliases,install_shift_enter_alias,)@@ -89,8 +90,9 @@ try:install_ctrl_enter_alias()install_cmd_backspace_alias()install_modify_other_keys_aliases()+ install_keypress_data_normalization()install_ignored_terminal_sequences()- del install_shift_enter_alias, install_ctrl_enter_alias, install_cmd_backspace_alias, install_modify_other_keys_aliases, install_ignored_terminal_sequences+ del install_shift_enter_alias, install_ctrl_enter_alias, install_cmd_backspace_alias, install_modify_other_keys_aliases, install_keypress_data_normalization, install_ignored_terminal_sequencesexcept Exception:passimport threadingdiff --git a/hermes_cli/pt_input_extras.py b/hermes_cli/pt_input_extras.pyindex 5f7fa6e9319..a9a39826391 100644--- a/hermes_cli/pt_input_extras.py+++ b/hermes_cli/pt_input_extras.py@@ -48,6 +48,60 @@ def _clear_vt100_prefix_cache() -> None:pass+def install_keypress_data_normalization() -> int:+ """Normalize KeyPress data for extended-key aliases that map to a+ single plain character (Shift+Space → ``' '``, Shift+letter → the+ uppercase letter, keypad digits → ``'0'``..``'9'``, keypad operators).++ Root cause of #88071: ``Vt100Parser._call_handler`` builds+ ``KeyPress(key, match.group(0))`` — the *key* is correctly remapped by+ ``ANSI_SEQUENCES``, but the *data* field still carries the full raw+ escape text (e.g. ``"\\x1b[32;2u"``). prompt_toolkit's default+ character-insert binding (``self-insert``, ``basic.py``) inserts+ ``event.data``, so the raw CSI bytes land in the prompt buffer. For a+ plain space both fields are ``' '`` so it is invisible; for any mapped+ extended sequence the escape text is what gets inserted.++ This patches ``Vt100Parser._call_handler`` so that when a sequence maps+ to a single plain character, the KeyPress data is that character rather+ than the raw sequence — the bytes never reach the buffer. Idempotent;+ repeated calls are no-ops.++ Returns 1 when the patch was applied, 0 when already applied or the+ import failed.+ """+ try:+ import prompt_toolkit.input.vt100_parser as _vt100_mod+ from prompt_toolkit.keys import Keys as _PtKeys+ except Exception:+ return 0++ if getattr(+ _vt100_mod.Vt100Parser._call_handler, "_hermes_char_data_normalized", False+ ):+ return 0++ _orig_call_handler = _vt100_mod.Vt100Parser._call_handler++ def _patched_call_handler(self, key, insert_text):+ # A single plain character (not a Keys member, not a tuple) mapped+ # from an extended sequence must carry the mapped character as its+ # data — self-insert inserts event.data and the raw CSI would leak.+ if (+ isinstance(key, str)+ and len(key) == 1+ and not isinstance(key, _PtKeys)+ and isinstance(insert_text, str)+ and insert_text.startswith("\x1b")+ ):+ insert_text = key+ return _orig_call_handler(self, key, insert_text)++ _patched_call_handler._hermes_char_data_normalized = True+ _vt100_mod.Vt100Parser._call_handler = _patched_call_handler+ return 1++def install_shift_enter_alias() -> int:"""Map Shift+Enter byte sequences to the (Escape, ControlM) key tuplethat Alt+Enter produces, so the existing Alt+Enter newline handlerdiff --git a/tests/cli/test_modify_other_keys_aliases.py b/tests/cli/test_modify_other_keys_aliases.pyindex 36e24fd0aef..bc042fea97b 100644--- a/tests/cli/test_modify_other_keys_aliases.py+++ b/tests/cli/test_modify_other_keys_aliases.py@@ -366,6 +366,128 @@ def test_shift_space_inserts_space():assert _parse("\x1b[27;2;32~") == [" "]+def _parse_presses(byte_seq: str):+ """Feed bytes through the VT100 parser and return the full KeyPress+ objects (key + data), so buffer-level data leakage is observable."""+ from prompt_toolkit.input.vt100_parser import Vt100Parser as _Vt100Parser+ from prompt_toolkit.key_binding.key_processor import KeyPress as _KeyPress++ out = []+ parser = _Vt100Parser(out.append)+ for ch in byte_seq:+ parser.feed(ch)+ parser.flush()+ assert all(isinstance(kp, _KeyPress) for kp in out)+ return out+++ "seq",+ ["\x1b[32;2u", "\x1b[27;2;32~"], # kitty CSI-u and xterm modifyOtherKeys+)+def test_shift_space_keypress_data_is_plain_space(seq):+ """The KeyPress data for Shift+Space must be ' ', not the raw CSI+ sequence — self-insert inserts event.data, so raw bytes would leak+ into the buffer even though the key is correctly mapped (#88071)."""+ from hermes_cli.pt_input_extras import install_keypress_data_normalization++ install_keypress_data_normalization()+ presses = _parse_presses(seq)+ assert [kp.key for kp in presses] == [" "]+ assert [kp.data for kp in presses] == [" "], (+ f"{seq!r} KeyPress data must be ' ', got {[kp.data for kp in presses]!r}"+ )++[email protected]("seq", ["\x1b[97;2u", "\x1b[27;2;97~"])+def test_shift_letter_keypress_data_is_uppercase(seq):+ """Shift+letter (modifier 2) maps to the uppercase letter; its KeyPress+ data must be that letter, not the raw escape text (#88071)."""+ from hermes_cli.pt_input_extras import install_keypress_data_normalization++ install_keypress_data_normalization()+ presses = _parse_presses(seq)+ assert [kp.key for kp in presses] == ["A"]+ assert [kp.data for kp in presses] == ["A"], (+ f"{seq!r} KeyPress data must be 'A', got {[kp.data for kp in presses]!r}"+ )+++def test_keypad_digit_keypress_data_is_digit():+ """Keypad digits (Kitty PUA) map to plain digits; their KeyPress data+ must be the digit, not the raw escape text (#88071)."""+ from hermes_cli.pt_input_extras import install_keypress_data_normalization++ install_keypress_data_normalization()+ presses = _parse_presses("\x1b[57404u")+ assert [kp.key for kp in presses] == ["5"]+ assert [kp.data for kp in presses] == ["5"], (+ f"keypad 5 KeyPress data must be '5', got {[kp.data for kp in presses]!r}"+ )+++def test_plain_space_keypress_data_unchanged():+ """A plain space must keep data == ' ' — normalization must not break+ the ordinary typing path."""+ from hermes_cli.pt_input_extras import install_keypress_data_normalization++ install_keypress_data_normalization()+ presses = _parse_presses(" ")+ assert [kp.key for kp in presses] == [" "]+ assert [kp.data for kp in presses] == [" "]+++def test_buffer_level_shift_space_no_raw_csi():+ """End-to-end: feeding Shift+Space through a real Application must put+ a space in the buffer, not raw CSI bytes (#88071).++ This is the regression the parser-only tests miss: Vt100Parser maps+ the key to ' ' but the KeyPress data still carried the raw sequence,+ and the default self-insert binding inserts event.data.+ """+ import asyncio++ from prompt_toolkit import Application+ from prompt_toolkit.buffer import Buffer+ from prompt_toolkit.input import create_pipe_input+ from prompt_toolkit.layout import HSplit, Layout, Window, BufferControl++ from hermes_cli.pt_input_extras import install_keypress_data_normalization++ install_keypress_data_normalization()++ async def _probe(payload: str) -> str:+ buf = Buffer()+ with create_pipe_input() as inp:+ app = Application(+ layout=Layout(HSplit([Window(BufferControl(buf))])), input=inp+ )+ run_task = asyncio.ensure_future(app.run_async())+ await asyncio.sleep(0.05)+ inp.send_text("ab")+ inp.send_text(payload)+ inp.send_text("cd")+ await asyncio.sleep(0.15)+ result = buf.text+ app.exit()+ try:+ await asyncio.wait_for(run_task, 2)+ except Exception:+ pass+ return result++ for label, payload in (+ ("Shift+Space xterm", "\x1b[27;2;32~"),+ ("Shift+Space kitty", "\x1b[32;2u"),+ ("plain space", " "),+ ):+ buffer = asyncio.run(_probe(payload))+ assert buffer == "ab cd", (+ f"{label}: buffer={buffer!r} — expected 'ab cd'; raw CSI bytes "+ f"must never land in the buffer"+ )++# ---------------------------------------------------------------------------# Multi-modifier combos (Ctrl+Shift / Ctrl+Alt / Shift+Alt / Ctrl+Alt+Shift)# ---------------------------------------------------------------------------