Skip to content

The agent that grows with you

test(e2e): TUI modals/tool output under resize, CJK + Ctrl+C, compress + resume render-once

teknium12ccd6c261621
diff --git a/tests/e2e/core/tui_pty/_helpers.py b/tests/e2e/core/tui_pty/_helpers.py
index 73da9c2c5aa..06c6cb3464e 100644
--- a/tests/e2e/core/tui_pty/_helpers.py
+++ b/tests/e2e/core/tui_pty/_helpers.py
@@ -41,6 +41,8 @@ TITLE = "Scripted session title"
# Right-edge scrollbar glyphs the Ink TUI paints in the last column of its transcript viewport.
_SCROLLBAR = "│┃║▐▕█░▒▓"
_DIGITS = re.compile(r"\d")
+_SPINNER = re.compile(r"[\u2800-\u28ff]")
+_STATUS_BAR = re.compile(r"│ fake model")
# A quiet sandbox: no update probe, no title call eating scripted turns, no memory/skills noise.
BASE_CONFIG = (
@@ -257,10 +259,13 @@ class TmuxTui:
assert self.alive(), f"hermes exited while waiting for {what}\n{self.dump()}"
def wait_quiet(self, idle: float = 1.0, timeout: float = 45.0) -> None:
- """A settled frame: unchanged (ignoring ticking digits) for ``idle`` seconds."""
+ """A settled frame: unchanged for ``idle`` seconds, ignoring what ticks on its own while a
+ card waits for the human (digits of clocks, braille spinners, the status bar's rotating
+ verb)."""
def frame() -> str:
self.track()
- return _DIGITS.sub("#", "\n".join(self.rows()))
+ rows = [r for r in self.rows() if not _STATUS_BAR.search(r)]
+ return _SPINNER.sub("#", _DIGITS.sub("#", "\n".join(rows)))
state = {"frame": frame(), "since": time.monotonic()}
def settled() -> bool:
diff --git a/tests/e2e/core/tui_pty/test_modals_resize.py b/tests/e2e/core/tui_pty/test_modals_resize.py
new file mode 100644
index 00000000000..d0e391dd1e0
--- /dev/null
+++ b/tests/e2e/core/tui_pty/test_modals_resize.py
@@ -0,0 +1,166 @@
+"""Blocking modals and streaming tool output in the Ink TUI survive terminal resizes: the clarify
+and approval cards stay on screen exactly once while the window is resized, the answer given
+after the resize reaches the tool (read back from the next wire request the agent sends), and the
+transcript around them keeps every word exactly once.
+
+Real ``hermes --tui`` in a private tmux server, ``approvals.mode: manual`` (the shipped default,
+never yolo), local terminal backend, scripted fake provider issuing ``clarify`` /
+``terminal(rm -rf <victim>)`` / a slow printing ``terminal`` command.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import sys
+import time
+
+import pytest
+
+from tests.e2e.core.tui_pty._helpers import (
+ TmuxTui, cell_params, ledger_problems, require_tui, run_cells, words,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="tmux + /proc session scan"),
+ pytest.mark.live_system_guard_bypass,
+]
+
+CONFIG = ("approvals:\n mode: manual\n timeout: 180\nclarify:\n timeout: 180\n"
+ "terminal:\n backend: local\n")
+QUESTION = "Which colour for zeta?"
+TOOL_LINES = [f"tout{i:02d}" for i in range(1, 41)]
+REPLIES = {k: " ".join(words(k, 8)) for k in ("c1", "a1", "t1")}
+TOKEN = r"\b(?:c1|a1|t1)w\d{3}\b"
+
+CELLS = [
+ "clarify_card_survives_resize", "clarify_answer_reaches_tool", "clarify_tool_call_rendered_once",
+ "clarify_answer_not_a_user_turn",
+ "approval_card_survives_resize", "approval_deny_honoured",
+ "tool_output_reaches_model_in_order", "tool_output_rendered_at_most_once",
+ "transcript_ledger", "exits_clean",
+]
+# cell -> "#<issue> <symptom>"; each entry is a strict xfail that turns red once fixed.
+KNOWN: dict[str, str] = {
+ "clarify_tool_call_rendered_once": "#121267 answering clarify renders its tool call twice",
+}
+
+
+def _tool_results(llm: FakeLLMServer) -> list[str]:
+ out = []
+ for body in llm.main_requests():
+ msgs = body.get("messages") or []
+ if msgs and msgs[-1].get("role") == "tool":
+ out.append(str(msgs[-1].get("content") or ""))
+ return out
+
+
+def _visible_once(tui: TmuxTui, needles: list[str]) -> str:
+ text = "\n".join(tui.rows())
+ bad = {n: text.count(n) for n in needles if text.count(n) != 1}
+ return f"modal rows not visible exactly once after resize: {bad}" if bad else ""
+
+
+def _scenario(root, victim) -> object:
+ command = "for i in $(seq -w 1 40); do echo tout$i; sleep 0.08; done"
+ script = [
+ ToolCall("clarify", {"question": QUESTION, "choices": ["red", "blue"]}), Text(REPLIES["c1"]),
+ ToolCall("terminal", {"command": f"rm -rf {victim}"}), Text(REPLIES["a1"]),
+ ToolCall("terminal", {"command": command}), Text(REPLIES["t1"]),
+ ]
+
+ def body(cells) -> None:
+ with FakeLLMServer(script) as llm:
+ tui = TmuxTui(root, llm.base_url, cols=120, rows=70, extra_config=CONFIG, args=())
+ try:
+ _drive(tui, llm, cells)
+ cells.add("exits_clean", tui.exit_problem())
+ finally:
+ tui.close()
+
+ def _drive(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:
+ tui.wait_ready()
+ # 1. clarify card open across a shrink and a grow, answered afterwards.
+ tui.submit("pick a colour mq1")
+ tui.wait_for("quick pick")
+ for cols in (90, 130):
+ tui.resize(cols)
+ tui.wait_quiet(1.0)
+ cells.add("clarify_card_survives_resize",
+ _visible_once(tui, [f"ask {QUESTION}", "1. red", "2. blue"]), tui.dump())
+ tui.key("Down")
+ tui.wait_for(lambda t: "▸ 2. blue" in t, history=False)
+ tui.key("Enter")
+ tui.wait_replies(1)
+ results = _tool_results(llm)
+ answer = json.loads(results[0]).get("user_response") if results else None
+ cells.add("clarify_answer_reaches_tool", "" if answer == "blue" else f"tool result {results[:1]}")
+ tui.wait_quiet(1.0)
+ n = tui.text().count(f'Clarify("{QUESTION}")')
+ cells.add("clarify_tool_call_rendered_once", "" if n == 1 else f"clarify tool call rendered {n}x",
+ tui.dump())
+ # The answer is the tool's result, never a persisted user message (the TUI echoes it as a
+ # bubble by design; state.db and the next wire request must not grow a user turn).
+ users = [c for _s, r, c in tui.messages() if r == "user"]
+ wire_users = [m.get("content") for m in (llm.main_requests()[-1].get("messages") or [])
+ if m.get("role") == "user"]
+ cells.add("clarify_answer_not_a_user_turn",
+ "" if users == ["pick a colour mq1"] and wire_users == ["pick a colour mq1"]
+ else f"persisted user rows {users!r}; wire user messages {wire_users!r}")
+
+ # 2. approval card open across resizes, then denied with its quick-pick key.
+ tui.submit("remove the dir mq2")
+ tui.wait_for("approval required")
+ for cols in (140, 85):
+ tui.resize(cols)
+ tui.wait_quiet(1.0)
+ problem = _visible_once(tui, ["approval required", "1. Allow once", "4. Deny"])
+ if not victim.exists():
+ problem += " / the dangerous command ran before anyone answered"
+ cells.add("approval_card_survives_resize", problem, tui.dump())
+ tui.key("4")
+ tui.wait_replies(2)
+ denied = _tool_results(llm)[-1]
+ ok = victim.exists() and (victim / "keep.txt").exists() and "denied" in denied.lower()
+ cells.add("approval_deny_honoured", "" if ok else f"victim exists={victim.exists()} result={denied[:200]}")
+
+ # 3. a tool printing 40 lines while the window is dragged.
+ tui.resize(120)
+ tui.submit("print lines mq3")
+ llm.wait_for_requests(5, timeout=60)
+ for cols in (100, 80, 110, 95, 120):
+ tui.resize(cols)
+ time.sleep(0.3)
+ tui.wait_replies(3)
+ tui.wait_quiet(1.0)
+ result = _tool_results(llm)[-1]
+ try:
+ output = str(json.loads(result).get("output"))
+ except ValueError:
+ output = result
+ problem = ledger_problems(output, TOOL_LINES, r"\btout\d{2}\b")
+ cells.add("tool_output_reaches_model_in_order", problem and f"{problem}\nresult: {result[:400]}")
+ counts = {w: len(re.findall(rf"\b{w}\b", tui.text())) for w in TOOL_LINES}
+ cells.add("tool_output_rendered_at_most_once",
+ "; ".join(f"{w}x{c}" for w, c in counts.items() if c > 1), tui.dump())
+ cells.add("transcript_ledger",
+ ledger_problems(tui.text(), [w for k in ("c1", "a1", "t1") for w in words(k, 8)], TOKEN),
+ tui.dump())
+
+ return run_cells(body)
+
+
[email protected](scope="module")
+def run(tmp_path_factory):
+ require_tui()
+ root = tmp_path_factory.mktemp("modals")
+ victim = root / "victim"
+ victim.mkdir()
+ (victim / "keep.txt").write_text("precious", encoding="utf-8")
+ return _scenario(root, victim)
+
+
[email protected]("cell", cell_params(CELLS, KNOWN))
+def test_modals_and_tool_output_survive_resize(run, cell: str) -> None:
+ run.check(cell)
diff --git a/tests/e2e/core/tui_pty/test_resume_compress.py b/tests/e2e/core/tui_pty/test_resume_compress.py
new file mode 100644
index 00000000000..1b9d25e662e
--- /dev/null
+++ b/tests/e2e/core/tui_pty/test_resume_compress.py
@@ -0,0 +1,132 @@
+"""A long Ink TUI session renders every transcript word at most once after ``/compress`` and
+when it is resumed later (``hermes --tui --resume <id>`` and ``/resume <id>`` from a fresh TUI):
+a compressed-transcript block is never painted twice (#88906), and the protected tail is on
+screen exactly once.
+
+Real ``hermes --tui`` in tmux against the scripted fake provider (the compression summary is an
+auxiliary call answered by the fake). The session is compressed in place, then the TUI exits and
+two fresh TUI processes reopen it from the same state.db.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from collections import Counter
+
+import pytest
+
+from tests.e2e.core.tui_pty._helpers import (
+ TmuxTui, cell_params, poll, require_tui, run_cells, words,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="tmux + /proc session scan"),
+ pytest.mark.live_system_guard_bypass,
+]
+
+TURNS = 7
+WORDS_PER_REPLY = 200 # the replaced span must outweigh the summary template
+TOKEN = r"\bs\dw\d{3}\b"
+SUMMARY = "SUMMARYMARK compressed account of the earlier turns"
+CONFIG = ("compression:\n enabled: true\n protect_last_n: 2\n min_tail_user_messages: 1\n"
+ " threshold_tokens: 1000000\n")
+TAIL = [TURNS] # the protected tail: the last turn survives compression verbatim
+
+CELLS = [
+ "compress_happened", "after_compress_no_word_twice", "after_compress_tail_once",
+ "resume_flag_no_word_twice", "resume_flag_tail_once",
+ "slash_resume_no_word_twice", "slash_resume_tail_once", "summary_never_twice",
+]
+# cell -> "#<issue> <symptom>"; each entry is a strict xfail that turns red once fixed.
+KNOWN: dict[str, str] = {}
+
+
+def _reply(t: int) -> str:
+ return " ".join(words(f"s{t}", WORDS_PER_REPLY))
+
+
+def _twice(text: str) -> str:
+ dup = sorted(w for w, c in Counter(re.findall(TOKEN, text)).items() if c > 1)
+ return f"{len(dup)} words rendered more than once: {dup[:6]}" if dup else ""
+
+
+def _tail_once(text: str) -> str:
+ counts = Counter(re.findall(TOKEN, text))
+ bad = [w for t in TAIL for w in words(f"s{t}", WORDS_PER_REPLY) if counts[w] != 1]
+ return f"protected tail words not exactly once: {bad[:6]} ({len(bad)})" if bad else ""
+
+
+def _session_id(tui: TmuxTui) -> str:
+ rows = tui.db_rows("SELECT id FROM sessions ORDER BY started_at DESC LIMIT 1")
+ return str(rows[0][0]) if rows else ""
+
+
+def _compacted(tui: TmuxTui) -> int:
+ rows = tui.db_rows("SELECT COUNT(*) FROM messages WHERE compacted = 1")
+ return int(rows[0][0]) if rows else 0
+
+
+def _scenario(root) -> object:
+ script = [Text(_reply(t)) for t in range(1, TURNS + 1)]
+
+ def body(cells) -> None:
+ with FakeLLMServer(script, aux=lambda _r: Text(SUMMARY)) as llm:
+ first = TmuxTui(root / "a", llm.base_url, cols=140, rows=200, extra_config=CONFIG)
+ try:
+ first.wait_ready()
+ for t in range(1, TURNS + 1):
+ first.submit(f"long session turn zq{t}q")
+ first.wait_replies(t)
+ first.wait_quiet(1.0)
+ first.submit("/compress")
+ try:
+ poll(lambda: _compacted(first) > 0, timeout=60, what="compacted rows in state.db")
+ cells.add("compress_happened", "")
+ except AssertionError as exc:
+ cells.add("compress_happened", f"{exc}\n{first.dump()}")
+ return
+ first.wait_quiet(1.5)
+ text = first.text()
+ cells.add("after_compress_no_word_twice", _twice(text), first.dump())
+ cells.add("after_compress_tail_once", _tail_once(text), first.dump())
+ summaries = [text.count("SUMMARYMARK")]
+ sid = _session_id(first)
+ first.exit_problem()
+ finally:
+ first.close()
+
+ for how in ("resume_flag", "slash_resume"):
+ sub = root / how
+ sub.mkdir()
+ args = ("--yolo", "--resume", sid) if how == "resume_flag" else ("--yolo",)
+ tui = TmuxTui(sub, llm.base_url, cols=140, rows=200, args=args, write_home=False,
+ env_extra={"HOME": str(root / "a" / "home"),
+ "HERMES_HOME": str(root / "a" / "home" / ".hermes")})
+ try:
+ tui.wait_ready()
+ if how == "slash_resume":
+ tui.submit(f"/resume {sid}")
+ tui.wait_for(words(f"s{TURNS}", WORDS_PER_REPLY)[-1], timeout=60)
+ tui.wait_quiet(1.5)
+ text = tui.text()
+ cells.add(f"{how}_no_word_twice", _twice(text), tui.dump())
+ cells.add(f"{how}_tail_once", _tail_once(text), tui.dump())
+ summaries.append(text.count("SUMMARYMARK"))
+ finally:
+ tui.close()
+ cells.add("summary_never_twice", "" if max(summaries) <= 1 else f"summary counts {summaries}")
+
+ return run_cells(body)
+
+
[email protected](scope="module")
+def run(tmp_path_factory):
+ require_tui()
+ return _scenario(tmp_path_factory.mktemp("resume"))
+
+
[email protected]("cell", cell_params(CELLS, KNOWN))
+def test_long_session_compress_and_resume_render_once(run, cell: str) -> None:
+ run.check(cell)
diff --git a/tests/e2e/core/tui_pty/test_wide_chars_interrupt.py b/tests/e2e/core/tui_pty/test_wide_chars_interrupt.py
new file mode 100644
index 00000000000..fc5107ba989
--- /dev/null
+++ b/tests/e2e/core/tui_pty/test_wide_chars_interrupt.py
@@ -0,0 +1,161 @@
+"""Wide characters and Ctrl+C in the Ink TUI keep the transcript consistent.
+
+CJK / wide characters (#35272): the composer cursor sits exactly after the typed wide text
+(tmux's own cursor column, so a width miscount of one column per ideograph shows up), a streamed
+CJK reply wraps inside the terminal on every width and each token is on screen exactly once, and
+the frame settles after the resizes instead of scrolling forever.
+
+Ctrl+C mid-stream: the turn stops, the partially streamed prefix is on screen once and matches
+what state.db persisted, the next turn's wire request carries that same partial reply, and the
+next reply renders exactly once after it.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+
+import pytest
+
+from tests.e2e.core.tui_pty._helpers import (
+ TmuxTui, cell_params, display_width, ledger_problems, paragraph, require_tui, run_cells,
+ words,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="tmux + /proc session scan"),
+ pytest.mark.live_system_guard_bypass,
+]
+
+CJK_TYPED = ("今天天气很好", "我们一起去")
+CJK_TOKENS = [f"字{i:03d}漢字テスト" for i in range(90)]
+CJK_RE = r"字\d{3}漢字テスト"
+INTERRUPT_WORDS = 600
+
+CELLS = [
+ "cjk_cursor_after_typed_text", "cjk_prompt_submitted_verbatim",
+ "cjk_reply_ledger", "cjk_rows_fit_terminal", "cjk_frame_settles",
+ "interrupt_turn_stops", "interrupt_prefix_on_screen_once", "interrupt_screen_matches_db",
+ "interrupt_next_request_carries_partial", "interrupt_next_reply_once", "exits_clean",
+]
+# cell -> "#<issue> <symptom>"; each entry is a strict xfail that turns red once fixed.
+KNOWN: dict[str, str] = {}
+
+
+def _cursor_problem(tui: TmuxTui, typed: str) -> str:
+ """The cursor column equals the display width of the composer row up to the typed text."""
+ x, y = (int(v) for v in tui.fmt("#{cursor_x} #{cursor_y}").split())
+ row = tui.rows()[y] if y < len(tui.rows()) else ""
+ if typed not in row:
+ return f"typed text {typed!r} not on the cursor row {y}: {row!r}"
+ want = display_width(row[: row.index(typed) + len(typed)])
+ return "" if x == want else f"cursor at col {x}, typed text ends at col {want} (row {row!r})"
+
+
+def _cjk(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:
+ tui.wait_ready()
+ tui.type(CJK_TYPED[0])
+ tui.wait_for(CJK_TYPED[0], history=False)
+ first = _cursor_problem(tui, CJK_TYPED[0])
+ tui.type(CJK_TYPED[1])
+ both = "".join(CJK_TYPED)
+ tui.wait_for(both, history=False)
+ cells.add("cjk_cursor_after_typed_text", first or _cursor_problem(tui, both), tui.dump())
+ tui.key("Enter")
+ tui.wait_for(CJK_TOKENS[20])
+ tui.resize(61)
+ tui.wait_replies(1)
+ sent = [m.get("content") for m in (llm.main_requests()[0].get("messages") or []) if m.get("role") == "user"]
+ cells.add("cjk_prompt_submitted_verbatim", "" if sent and both in str(sent[-1]) else f"wire user {sent!r}")
+ for cols in (47, 88):
+ tui.resize(cols)
+ tui.wait_quiet(1.0)
+ cols_now = tui.size()[0]
+ cells.add("cjk_reply_ledger", ledger_problems(tui.text(), CJK_TOKENS, CJK_RE), tui.dump())
+ wide = [r for r in tui.rows() if display_width(r) > cols_now]
+ cells.add("cjk_rows_fit_terminal", f"{len(wide)} rows wider than {cols_now}: {wide[:2]}" if wide else "",
+ tui.dump())
+ if cells.results["cjk_reply_ledger"][0] is False or wide:
+ return
+ # An infinite scroll loop keeps repainting: the frame must hold still for several seconds.
+ try:
+ tui.wait_quiet(3.0, timeout=20)
+ cells.add("cjk_frame_settles", "")
+ except AssertionError as exc:
+ cells.add("cjk_frame_settles", str(exc)[:2000])
+
+
+def _interrupt(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:
+ tui.wait_ready()
+ tui.submit("stream then stop ix1")
+ tui.wait_for("i1w060")
+ tui.key("C-c")
+ try:
+ tui.wait_for("[interrupted]", timeout=30)
+ tui.wait_quiet(1.0)
+ cells.add("interrupt_turn_stops", "" if tui.alive() else "Ctrl+C mid-stream exited the TUI")
+ except AssertionError as exc:
+ cells.add("interrupt_turn_stops", str(exc)[:2000])
+ return
+ shown = [w for w in re.findall(r"\bi1w\d{3}\b", tui.text())]
+ prefix = words("i1", len(set(shown)))
+ cells.add("interrupt_prefix_on_screen_once",
+ "" if shown == prefix and len(shown) < INTERRUPT_WORDS
+ else f"{len(shown)} words shown, not a once-each prefix: {shown[:3]}…{shown[-3:]}", tui.dump())
+ rows = tui.messages()
+ partial = [c for _s, r, c in rows if r == "assistant"]
+ db_words = re.findall(r"\bi1w\d{3}\b", partial[0]) if partial else []
+ cells.add("interrupt_screen_matches_db",
+ "" if db_words and db_words == shown
+ else f"state.db assistant words {len(db_words)} vs screen {len(shown)}: {partial[:1]!r:.200}")
+
+ tui.submit("carry on ix2")
+ tui.wait_replies(2)
+ tui.wait_quiet(1.0)
+ history = llm.main_requests()[-1].get("messages") or []
+ carried = [m for m in history if m.get("role") == "assistant" and "i1w000" in str(m.get("content"))]
+ carried_words = re.findall(r"\bi1w\d{3}\b", str(carried[0].get("content"))) if carried else []
+ cells.add("interrupt_next_request_carries_partial",
+ "" if len(carried) == 1 and carried_words == db_words
+ else f"{len(carried)} assistant messages with the partial; words {len(carried_words)} vs db {len(db_words)}")
+ cells.add("interrupt_next_reply_once",
+ ledger_problems(tui.text(), words("n1", 12), r"\bn1w\d{3}\b")
+ or ("" if re.findall(r"\bi1w\d{3}\b", tui.text()) == shown else "the partial reply re-rendered"),
+ tui.dump())
+
+
+def _scenario(kind: str, root) -> object:
+ scripts = {
+ "cjk": [Text(" ".join(CJK_TOKENS), chunk_chars=5, delay_per_chunk=0.02)],
+ "interrupt": [Text(paragraph("i1", INTERRUPT_WORDS), chunk_chars=4, delay_per_chunk=0.03),
+ Text(" ".join(words("n1", 12)))],
+ }
+ drive = {"cjk": _cjk, "interrupt": _interrupt}[kind]
+
+ def body(cells) -> None:
+ with FakeLLMServer(scripts[kind]) as llm:
+ # Tall enough that the whole conversation stays inside the viewport at 47 cols.
+ tui = TmuxTui(root, llm.base_url, cols=100, rows=130)
+ try:
+ drive(tui, llm, cells)
+ if kind == "interrupt":
+ cells.add("exits_clean", tui.exit_problem())
+ finally:
+ tui.close()
+
+ return run_cells(body)
+
+
[email protected](scope="module")
+def runs() -> dict:
+ require_tui()
+ return {}
+
+
[email protected]("cell", cell_params(CELLS, KNOWN))
+def test_wide_chars_and_interrupt(runs: dict, cell: str, tmp_path_factory) -> None:
+ kind = "cjk" if cell.startswith("cjk") else "interrupt"
+ if kind not in runs:
+ runs[kind] = _scenario(kind, tmp_path_factory.mktemp(kind))
+ runs[kind].check(cell)