From ed1afb082eb3e46cf2edae9d8f68fb67b09ee4df Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:04:37 -0800 Subject: [PATCH] fix(cli): the prompt's parser drops an image-probe reply that arrives late probe_vscode_images stops reading after ~100 ms; a reply later than that (seen at 120 ms) reached prompt_toolkit and was typed into the prompt as "[?1;0;4096S[?62;4;9;22c". A longer wait only moves the edge. Parse XTSMGRAPHICS (ESC[?1;;S) and DA1 (ESC[?...c) replies as Keys.Ignore in prompt_toolkit's VT100 parser, beside the focus-report entries, the way it special-cases CPR. No key sends either sequence, so any late reply is now harmless whenever it arrives, and keys typed after it still land. The PTY test now feeds the leftover tty bytes through the CLI's parser and adds 300 ms replies past every wait. --- agent/terminal_image.py | 5 ++- hermes_cli/pt_input_extras.py | 42 ++++++++++++++++++- .../agent/test_terminal_image_vscode_probe.py | 27 +++++++++--- 3 files changed, 64 insertions(+), 10 deletions(-) diff --git a/agent/terminal_image.py b/agent/terminal_image.py index c3d283d3b6..b769fc6f05 100644 --- a/agent/terminal_image.py +++ b/agent/terminal_image.py @@ -74,8 +74,9 @@ _SIXEL_REPLY = b"\x1b[?1;0;" def probe_vscode_images() -> bool | None: """Whether VS Code's terminal will draw images; ``None`` outside a local VS Code terminal. - Run once before prompt_toolkit owns the tty (the reply is read from stdin). Skipped over SSH: - a reply slower than the deadline would reach the prompt as typed text. Cached. + Run once before prompt_toolkit owns the tty (the reply is read from stdin). Skipped over SSH, + where the reply often misses the deadline (the prompt's parser then drops it, see + ``hermes_cli.pt_input_extras``). Cached. """ global _VSCODE_IMAGES if _VSCODE_IMAGES is not None or os.environ.get("TERM_PROGRAM", "").lower() != "vscode": diff --git a/hermes_cli/pt_input_extras.py b/hermes_cli/pt_input_extras.py index 71826ea3b9..32127539b5 100644 --- a/hermes_cli/pt_input_extras.py +++ b/hermes_cli/pt_input_extras.py @@ -2,6 +2,8 @@ from __future__ import annotations +import re + # kitty CSI-u ORs lock-key state into the modifier parameter of every key event while a lock is # on: CapsLock=64, NumLock=128, both=192. Every fixed-modifier CSI-u (and legacy CSI-tilde / # CSI-letter) registration therefore needs lock-offset twins, or those events leak into the prompt @@ -316,10 +318,46 @@ def _modify_other_keys_aliases(ANSI_SEQUENCES: dict, Keys) -> dict[str, object]: return aliases +# Replies to the startup image probe (``agent.terminal_image.probe_vscode_images``): XTSMGRAPHICS +# ``ESC[?1;;S`` and DA1 ``ESC[?c``. No key sends either. One that lands +# after the probe stopped reading would otherwise be typed into the prompt. +_PROBE_REPLY_RE = re.compile(r"\x1b\[\?[\d;]*[Sc]\Z") +_PROBE_REPLY_PREFIX_RE = re.compile(r"\x1b\[\?[\d;]*\Z") + + +def _install_probe_reply_filter() -> int: + """Parse a probe reply as one ``Keys.Ignore``, whenever it arrives. ``ANSI_SEQUENCES`` holds + fixed strings only, so this wraps the parser's matcher the way prompt_toolkit special-cases CPR.""" + import prompt_toolkit.input.vt100_parser as vt100 + from prompt_toolkit.keys import Keys + + get_match = vt100.Vt100Parser._get_match + if getattr(get_match, "_hermes_probe_replies", False): + return 0 + is_prefix = vt100._IsPrefixOfLongerMatchCache.__missing__ + + def _get_match(self, prefix): + return Keys.Ignore if _PROBE_REPLY_RE.match(prefix) else get_match(self, prefix) + + def _missing(self, prefix): + if _PROBE_REPLY_PREFIX_RE.match(prefix): + self[prefix] = True + return True + return is_prefix(self, prefix) + + _get_match._hermes_probe_replies = True + vt100.Vt100Parser._get_match = _get_match + vt100._IsPrefixOfLongerMatchCache.__missing__ = _missing + _clear_vt100_prefix_cache() + return 1 + + def install_ignored_terminal_sequences() -> int: - """Map focus reports ``ESC[I`` / ``ESC[O`` (Ghostty, iTerm2, some xterms) to ``Keys.Ignore``. + """Parse terminal reports nobody typed as ``Keys.Ignore``: focus reports ``ESC[I`` / ``ESC[O`` + (Ghostty, iTerm2, some xterms) and the image probe's replies. Parser-level handling beats post-hoc regex stripping because the bytes never reach the buffer. ``setdefault`` lets user/downstream registrations win. """ - return _install(lambda _seqs, keys: {"\x1b[I": keys.Ignore, "\x1b[O": keys.Ignore}, overwrite=False) + focus = _install(lambda _seqs, keys: {"\x1b[I": keys.Ignore, "\x1b[O": keys.Ignore}, overwrite=False) + return focus + _install_probe_reply_filter() diff --git a/tests/agent/test_terminal_image_vscode_probe.py b/tests/agent/test_terminal_image_vscode_probe.py index b6dbf30202..2357dde99f 100644 --- a/tests/agent/test_terminal_image_vscode_probe.py +++ b/tests/agent/test_terminal_image_vscode_probe.py @@ -2,8 +2,9 @@ The far end of the PTY plays the terminal: it answers the probe the way VS Code's xterm.js was measured to answer with ``terminal.integrated.enableImages`` on (sixel reply + DA1) and off -(DA1 only), optionally late. After the probe the child reads its tty the way the prompt would: -any reply byte left there would have been typed into the user's prompt. +(DA1 only), optionally late, then types ``hi``. After the probe the child reads its tty and feeds +it to prompt_toolkit's parser with the CLI's input tables, as the prompt would: ``typed`` is what +would land in the user's prompt. """ from __future__ import annotations @@ -24,6 +25,9 @@ _REPO = str(Path(__file__).resolve().parents[2]) _CHILD = textwrap.dedent(""" import os, select, sys, termios, tty from agent import terminal_image + from hermes_cli.pt_input_extras import install_ignored_terminal_sequences + from prompt_toolkit.input.vt100_parser import Vt100Parser + from prompt_toolkit.keys import Keys result = terminal_image.probe_vscode_images() fd = sys.stdin.fileno() old = termios.tcgetattr(fd) @@ -32,8 +36,14 @@ _CHILD = textwrap.dedent(""" while select.select([fd], [], [], 0.3)[0]: leaked += os.read(fd, 256) termios.tcsetattr(fd, termios.TCSADRAIN, old) + install_ignored_terminal_sequences() + presses = [] + parser = Vt100Parser(presses.append) + parser.feed(leaked.decode()) + parser.flush() + typed = "".join(p.data for p in presses if p.key is not Keys.Ignore) print("RESULT", result, terminal_image.supports_iterm_images(), - terminal_image.resolve_inline_mode("auto", overlays=True), "leaked=%d" % len(leaked), flush=True) + terminal_image.resolve_inline_mode("auto", overlays=True), "typed=%r" % typed, flush=True) """) _ON = b"\x1b[?1;0;4096S\x1b[?62;4;9;22c" @@ -64,6 +74,8 @@ def _run(reply: bytes, delay: float) -> str: if not answered and b"\x1b[c" in out: time.sleep(delay) # health: allow HX013 -- the late reply IS the scenario under test os.write(master, reply) + time.sleep(0.02) # health: allow HX013 -- the user's keys arrive after the reply + os.write(master, b"hi") answered = True finally: os.close(master) @@ -76,9 +88,12 @@ def _run(reply: bytes, delay: float) -> str: @pytest.mark.parametrize( ("reply", "delay", "expected"), [ - (_ON, 0, "RESULT True True iterm leaked=0"), # enableImages on - (_OFF, 0, "RESULT False False unicode leaked=0"), # enableImages off: DA1 only - (_ON, 0.08, "RESULT True True iterm leaked=0"), # past the 50 ms deadline, inside the drain + (_ON, 0, "RESULT True True iterm typed='hi'"), # enableImages on + (_OFF, 0, "RESULT False False unicode typed='hi'"), # enableImages off: DA1 only + (_ON, 0.08, "RESULT True True iterm typed='hi'"), # past the 50 ms deadline, inside the drain + # Past every wait: the probe misses it, and the prompt's parser drops it. + (_ON, 0.3, "RESULT False False unicode typed='hi'"), + (_OFF, 0.3, "RESULT False False unicode typed='hi'"), ], ) def test_vscode_probe_reads_its_reply_and_leaves_nothing_for_the_prompt(reply, delay, expected):