The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e): harden Ink TUI tmux suite per review
teknium1f0640122e494
diff --git a/tests/e2e/core/tui_pty/_helpers.py b/tests/e2e/core/tui_pty/_helpers.pyindex 3d9ffef792b..c5f6543d873 100644--- a/tests/e2e/core/tui_pty/_helpers.py+++ b/tests/e2e/core/tui_pty/_helpers.py@@ -2,7 +2,7 @@tmux is the terminal emulator here: it owns the grid, reflows it on resize and keeps thescrollback, exactly as it does for a user running the TUI inside tmux. We read it back with-``capture-pane`` (``-S -`` for scrollback, ``-J`` to join rows tmux re-wrapped) and ask tmux for+``capture-pane`` (``-S -`` for scrollback) and ask tmux forthe cursor position, the alternate-screen flag and the scrollback size.Every transcript word the fake provider streams is a unique token (``<tag>w<NNN>``), so a@@ -15,6 +15,7 @@ the tmux server and every process of the pane's session by session id, never byfrom __future__ import annotations+import contextlibimport osimport reimport shutil@@ -22,16 +23,17 @@ import signalimport sqlite3import subprocessimport sys+import tempfileimport termiosimport timeimport unicodedata-import uuidfrom collections import Counterfrom pathlib import Pathfrom typing import Callable, Iterableimport pytest+from tests.e2e.core._pending_fixes import known_failurefrom tests.e2e.core.terminal._pty import cmdline, poll, session_membersfrom tests.fakes.fake_llm_provider import write_hermes_home@@ -43,6 +45,12 @@ _SCROLLBAR = "│┃║▐▕█░▒▓"_DIGITS = re.compile(r"\d")_SPINNER = re.compile(r"[\u2800-\u28ff]")_STATUS_BAR = re.compile(r"│ fake model")+# The status bar's first cell once the startup session is live: "─ ready │ fake model │ …". Before+# that it reads "summoning hermes…" / "forging session…" / "starting agent…" / "resuming…".+_READY = re.compile(r"─ ready │")+_STATUS_ROW = re.compile(r"^ ─ (.+?) │")+# AF_UNIX sun_path is 108 bytes; stay well inside it.+_SOCK_MAX = 100# A quiet sandbox: no update probe, no title call eating scripted turns, no memory/skills noise.BASE_CONFIG = (@@ -117,55 +125,92 @@ def ledger_problems(text: str, expected: Iterable[str], pattern: str) -> str:return "; ".join(f"{k}={v[:8]}{'…' if len(v) > 8 else ''} ({len(v)})" for k, v in report.items() if v)+class CellFailed(AssertionError):+ """A cell's verdict is a failure. Raised ONLY by ``Cells.check`` for an evaluated cell, so a+ KNOWN cell (``known_failure(..., raises=CellFailed)``) never swallows a harness failure+ (timeout, crash, precondition), which ``Cells.check`` raises as ``RuntimeError``."""++class Cells:"""Named verdicts of one scenario run. Each becomes its own test id so a known bug can be- marked ``xfail(strict=True)`` on exactly the cell it breaks while the rest stay enforced."""+ pinned (``known_failure``) on exactly the cell it breaks while the rest stay enforced."""def __init__(self) -> None:self.results: dict[str, tuple[bool, str]] = {}self.error: str | None = None+ self.errors: dict[str, str] = {}+ self.phase = "setup"def add(self, name: str, problem: str, screen: str = "") -> None:self.results[name] = (not problem, f"{problem}\n--- screen ---\n{screen}" if problem else "")- def check(self, name: str) -> None:+ def harness_error(self, name: str, detail: str) -> None:+ """The cell could not be judged (its precondition never held): a real failure, never a+ KNOWN xfail, and it leaves the scenario's other cells alone."""+ self.errors[name] = f"PHASE={self.phase}: {detail}"++ def check(self, name: str, known: dict[str, tuple[str, str]] | None = None) -> None:+ """Enforce one cell. ``known`` maps a cell to ``(pattern, "#<issue> …")``: while the cell+ fails with a message matching ``pattern`` it XFAILs; once the fix lands it passes; any+ other failure (including every harness error) stays a failure."""if self.error is not None:raise RuntimeError(f"scenario failed before its cells could be evaluated:\n{self.error}")+ if name in self.errors:+ raise RuntimeError(f"cell {name!r} could not be evaluated:\n{self.errors[name]}")if name not in self.results:raise RuntimeError(f"cell {name!r} was never evaluated (scenario ended early)")ok, detail = self.results[name]- assert ok, f"[{name}] {detail}"+ entry = (known or {}).get(name)+ guard = known_failure(*entry, raises=CellFailed) if entry else contextlib.nullcontext()+ with guard:+ if not ok:+ raise CellFailed(f"[{name}] {detail}")-def cell_params(names: Iterable[str], known: dict[str, str]) -> list:- """pytest params for ``names``; a KNOWN cell is a strict xfail that turns red once fixed."""- return [pytest.param(n, id=n, marks=[pytest.mark.xfail(strict=True, raises=AssertionError,- reason=known[n])] if n in known else [])- for n in names]+def cell_params(names: Iterable[str]) -> list:+ return [pytest.param(n, id=n) for n in names]def run_cells(body: Callable[[Cells], None]) -> Cells:- """Run one scenario; a harness failure (timeout, crash) is kept and re-raised by every cell."""+ """Run one scenario; a harness failure (timeout, crash) is kept, tagged with the phase it hit+ (``cells.phase``), and re-raised by every cell."""cells = Cells()try:body(cells)except Exception as exc: # noqa: BLE001 - surfaced verbatim by Cells.check- cells.error = f"{type(exc).__name__}: {exc}"+ cells.error = f"PHASE={cells.phase}: {type(exc).__name__}: {exc}"return cells-def reply_rows_width(rows: list[str], token_re: str) -> int:- """Widest rendered row (in columns) holding a token of the given paragraph."""- return max((display_width(r) for r in rows if re.search(token_re, r)), default=0)-+def layout_problem(rows: list[str], cols: int, tag: str, slack: int | None = 12) -> str:+ """The paragraph of ``<tag>wNNN`` words on the visible frame is laid out for the current width+ (#35804). tmux never shows a row wider than the pane, so "fits" alone proves nothing; instead:-def width_problem(rows: list[str], token_re: str, cols: int, slack: int = 12) -> str:- """Content width follows the terminal: the paragraph wraps within ``slack`` of the edge and- never past it (#35804)."""- widest = reply_rows_width(rows, token_re)- if widest > cols:- return f"reply rows are {widest} cols wide on a {cols}-col terminal"- if widest < cols - slack:+ * every row holding its words is only those words: a blank/``┊`` gutter, then whole words+ separated by single spaces. A frame painted for another width leaves fragments, box rules+ or words of other rows spliced into a row;+ * the rows read on from one another: each row starts with the word after the previous row's+ last one (no word missing, repeated or moved between rows);+ * the widest row reaches within ``slack`` columns of the edge (a narrower stale layout);+ ``slack=None`` skips this (and tolerates the paragraph being scrolled off) for a paragraph+ too short to fill a row.+ """+ word = rf"{tag}w\d{{3}}"+ clean = re.compile(rf"^[ ┊]*({word}(?: {word})*)$")+ para = [r for r in rows if re.search(rf"{tag}w\d", r)]+ if not para:+ return f"no row of the {tag} paragraph on screen" if slack is not None else ""+ seq: list[int] = []+ for r in para:+ m = clean.match(r)+ if not m:+ return f"a {tag} paragraph row is not whole words at this width: {r!r}"+ idx = [int(w[len(tag) + 1:]) for w in m.group(1).split(" ")]+ if (seq and idx[0] != seq[-1] + 1) or idx != list(range(idx[0], idx[0] + len(idx))):+ return f"{tag} paragraph rows do not read on (after {tag}w{seq[-1] if seq else -1:03d}): {r!r}"+ seq += idx+ widest = max(display_width(r) for r in para)+ if slack is not None and widest < cols - slack:return f"reply wraps at {widest} cols on a {cols}-col terminal (content width did not follow)"return ""@@ -175,11 +220,19 @@ class TmuxTui:def __init__(self, root: Path, base_url: str, *, cols: int = 120, rows: int = 50,extra_config: str = "", args: Iterable[str] = ("--yolo",), inline: bool = False,- env_extra: dict[str, str] | None = None, write_home: bool = True) -> None:+ env_extra: dict[str, str] | None = None, write_home: bool = True,+ tui_dir: Path | None = None) -> None:self.root = rootself.home = root / "home"self.hermes_home = self.home / ".hermes"- self.sock = f"hermes-tui-e2e-{uuid.uuid4().hex[:10]}"+ # A socket path of our own (never the shared default dir tmux-<uid> under the system temp+ # dir, where a crashed run would leave it behind); close() removes it.+ self._sock_dir: str | None = None+ sock = root / "tmux.sock"+ if len(str(sock)) > _SOCK_MAX:+ self._sock_dir = tempfile.mkdtemp(prefix="htui-")+ sock = Path(self._sock_dir) / "s"+ self.sock = str(sock)if write_home:write_hermes_home(self.hermes_home, base_url, extra_config=BASE_CONFIG + extra_config)for sub in ("tmp", "work"):@@ -194,10 +247,10 @@ class TmuxTui:env.update(HOME=str(self.home), HERMES_HOME=str(self.hermes_home), PYTHONPATH=str(REPO_ROOT),TMPDIR=str(root / "tmp"), LANG="C.UTF-8", LC_ALL="C.UTF-8", PYTHONUNBUFFERED="1",HERMES_STATE_DB_GUARD_BYPASS="1", HERMES_TUI_INLINE="1" if inline else "0",- HERMES_TUI_DIR=str(private_tui_dir(root)))+ HERMES_TUI_DIR=str(tui_dir or private_tui_dir(root)))env.update(env_extra or {})argv = [sys.executable, "-m", "hermes_cli.main", "--tui", *args]- subprocess.run(["tmux", "-L", self.sock, "-f", str(conf), "new-session", "-d", "-s", "p",+ subprocess.run(["tmux", "-S", self.sock, "-f", str(conf), "new-session", "-d", "-s", "p","-x", str(cols), "-y", str(rows), "-c", str(root / "work"), *argv],env=env, check=True, timeout=30)self.tmux("set", "-g", "window-size", "manual")@@ -208,7 +261,7 @@ class TmuxTui:# -- tmux ------------------------------------------------------------------------------------def tmux(self, *args: str) -> str:- return subprocess.run(["tmux", "-L", self.sock, *args], capture_output=True, text=True,+ return subprocess.run(["tmux", "-S", self.sock, *args], capture_output=True, text=True,timeout=30).stdoutdef fmt(self, spec: str) -> str:@@ -246,11 +299,6 @@ class TmuxTui:out.append(line.rstrip())return out- def joined(self, *, history: bool = False) -> str:- """Rows tmux re-wrapped on a resize joined back into logical lines (``-J``)."""- span = ("-S", "-", "-E", "-") if history else ()- return self.tmux("capture-pane", "-p", "-J", "-t", "p", *span)-def text(self) -> str:return "\n".join(self.rows(history=True))@@ -317,8 +365,15 @@ class TmuxTui:os.close(fd)return not (lflag & (termios.ICANON | termios.ECHO) or iflag & termios.ICRNL)- def wait_ready(self, timeout: float = 120.0) -> None:- """The Ink UI owns the terminal (raw mode) and its composer frame has settled."""+ def status(self) -> str:+ """The status bar's first cell (``ready``, ``summoning hermes…``, ``running…``), or ''."""+ for row in reversed(self.rows()):+ if m := _STATUS_ROW.match(row):+ return m.group(1)+ return ""++ def wait_raw(self, timeout: float = 120.0) -> None:+ """The Ink UI owns the terminal (raw mode): keys typed from now on reach the composer."""try:poll(lambda: not self.alive() or self._raw_mode(), timeout=timeout,what="the TUI to take the terminal (raw mode)")@@ -328,6 +383,18 @@ class TmuxTui:assert state.startswith("0 "), (f"hermes --tui exited during startup (pane_dead pid status={state!r}, "f"tmux server {'up' if state else 'gone'})\n{self.dump()}")++ def wait_ready(self, timeout: float = 120.0) -> None:+ """Raw mode, the startup session is live (status bar ``ready`` -- the composer accepts+ input long before: a slash command sent while the gateway still starts races the startup+ session and loses), and the frame has settled."""+ self.wait_raw(timeout)+ try:+ poll(lambda: not self.alive() or _READY.search("\n".join(self.rows())), timeout=timeout,+ what="the startup session (status bar 'ready')")+ except AssertionError as exc:+ raise AssertionError(f"{exc} (status {self.status()!r})\n{self.dump()}") from None+ assert self.alive(), f"hermes --tui exited during startup\n{self.dump()}"self.wait_quiet(1.5, timeout=timeout)# -- processes -------------------------------------------------------------------------------@@ -357,6 +424,9 @@ class TmuxTui:that needed a SIGKILL (pid: cmdline) for diagnostics."""self.track()self.tmux("kill-server")+ Path(self.sock).unlink(missing_ok=True)+ if self._sock_dir:+ shutil.rmtree(self._sock_dir, ignore_errors=True)survivors = []deadline = time.monotonic() + 10while time.monotonic() < deadline:diff --git a/tests/e2e/core/tui_pty/test_modals_resize.py b/tests/e2e/core/tui_pty/test_modals_resize.pyindex d0e391dd1e0..f4a09008d1a 100644--- a/tests/e2e/core/tui_pty/test_modals_resize.py+++ b/tests/e2e/core/tui_pty/test_modals_resize.py@@ -5,7 +5,8 @@ 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.+``terminal(rm -rf <victim>)`` / a slow printing ``terminal`` command whose output the TUI shows+once ``/verbose verbose`` is on: every printed line is on screen exactly once after the drags."""from __future__ import annotations@@ -30,7 +31,10 @@ pytestmark = [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)]+# Few and short enough that the verbose Result block shows them all on one unbroken row at 120+# cols (the block is capped at 12 lines / 800 chars; a longer word is hard-wrapped mid-token).+TOOL_LINES = [f"tout{i:02d}" for i in range(1, 11)]+TOOL_RE = r"tout\d{2}(?!\d)" # the Result block is JSON: lines arrive as "\ntout02"REPLIES = {k: " ".join(words(k, 8)) for k in ("c1", "a1", "t1")}TOKEN = r"\b(?:c1|a1|t1)w\d{3}\b"@@ -38,12 +42,14 @@ 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",+ "tool_output_reaches_model_in_order", "tool_output_rendered_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",+# cell -> (regex on the bug's own failure message, "#<issue> <symptom>"): XFAILs only while the cell+# fails exactly that way, passes once the fix lands, and any other failure stays red.+KNOWN: dict[str, tuple[str, str]] = {+ "clarify_tool_call_rendered_once": (r"clarify tool call rendered [2-9]x",+ "#121267 answering clarify renders its tool call twice"),}@@ -63,7 +69,7 @@ def _visible_once(tui: TmuxTui, needles: list[str]) -> str:def _scenario(root, victim) -> object:- command = "for i in $(seq -w 1 40); do echo tout$i; sleep 0.08; done"+ command = f"for i in $(seq -w 1 {len(TOOL_LINES)}); do echo tout$i; sleep 0.3; done"script = [ToolCall("clarify", {"question": QUESTION, "choices": ["red", "blue"]}), Text(REPLIES["c1"]),ToolCall("terminal", {"command": f"rm -rf {victim}"}), Text(REPLIES["a1"]),@@ -75,12 +81,14 @@ def _scenario(root, victim) -> object:tui = TmuxTui(root, llm.base_url, cols=120, rows=70, extra_config=CONFIG, args=())try:_drive(tui, llm, cells)+ cells.phase = "exit"cells.add("exits_clean", tui.exit_problem())finally:tui.close()def _drive(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:tui.wait_ready()+ cells.phase = "clarify"# 1. clarify card open across a shrink and a grow, answered afterwards.tui.submit("pick a colour mq1")tui.wait_for("quick pick")@@ -110,6 +118,7 @@ def _scenario(root, victim) -> object: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.+ cells.phase = "approval"tui.submit("remove the dir mq2")tui.wait_for("approval required")for cols in (140, 85):@@ -125,25 +134,31 @@ def _scenario(root, victim) -> object: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.+ # 3. a slow printing tool while the window is dragged, its output rendered (verbose tool+ # progress: the default mode shows no tool output at all) and dragged again once shown.+ cells.phase = "tool_output"tui.resize(120)+ tui.submit("/verbose verbose")+ tui.wait_for("verbose: verbose")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_for(lambda t: len(re.findall(TOOL_RE, t)) >= len(TOOL_LINES), timeout=30)+ for cols in (90, 70, 130, 120):+ tui.resize(cols)+ tui.wait_quiet(0.5)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")+ problem = ledger_problems(output, TOOL_LINES, TOOL_RE)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("tool_output_rendered_once", ledger_problems(tui.text(), TOOL_LINES, TOOL_RE), 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())@@ -161,6 +176,6 @@ def run(tmp_path_factory):return _scenario(root, victim)[email protected]("cell", cell_params(CELLS, KNOWN))[email protected]("cell", cell_params(CELLS))def test_modals_and_tool_output_survive_resize(run, cell: str) -> None:- run.check(cell)+ run.check(cell, KNOWN)diff --git a/tests/e2e/core/tui_pty/test_resize_ledger.py b/tests/e2e/core/tui_pty/test_resize_ledger.pyindex 1674054edea..511e184d43e 100644--- a/tests/e2e/core/tui_pty/test_resize_ledger.py+++ b/tests/e2e/core/tui_pty/test_resize_ledger.py@@ -15,13 +15,14 @@ token as lost / duplicated / misordered.from __future__ import annotations+import reimport sysimport timeimport pytestfrom tests.e2e.core.tui_pty._helpers import (- TITLE, TmuxTui, cell_params, ledger_problems, paragraph, require_tui, run_cells, width_problem,+ TITLE, TmuxTui, cell_params, layout_problem, ledger_problems, paragraph, require_tui, run_cells,words,)from tests.fakes.fake_llm_provider import FakeLLMServer, Text@@ -50,6 +51,41 @@ def _expected(upto: int) -> list[str]:return [w for t in range(1, upto + 1) for w in words(f"r{t}", N[t])]+def _frame_problem(tui: TmuxTui, upto: int, para: int) -> str:+ """The settled frame is laid out for the current width: the newest long reply reaches the+ edge, every reply on screen is whole words reading on row to row, and every prompt echo row+ reads exactly its prompt (a frame painted for another width splices rules and other rows'+ cells into them)."""+ rows, cols = tui.rows(), tui.size()[0]+ for t in range(1, upto + 1):+ if problem := layout_problem(rows, cols, f"r{t}", slack=12 if t == para else None):+ return problem+ history = tui.rows(history=True) # inline mode scrolls earlier prompts off the pane+ for t in range(1, upto + 1):+ echo = [r for r in history if f"zq{t}q" in r]+ if [r.strip() for r in echo] != [f"❯ {PROMPTS[t]}"]:+ return f"prompt {t} echo rows are {echo!r}, want one row reading '❯ {PROMPTS[t]}'"+ return ""+++def _persisted_problem(persisted: list[tuple[str, str, str]], screen: str) -> str:+ """state.db holds exactly the conversation, in one session, and the reply words it persisted+ are the reply words on screen, in the same order."""+ users = [c for _s, r, c in persisted if r == "user"]+ replies = [c for _s, r, c in persisted if r == "assistant" and c.strip()]+ if users != list(PROMPTS.values()) or replies != list(REPLY.values()):+ return f"state.db rows differ from the conversation: users={users!r} replies={[r[:30] for r in replies]}"+ if len({s for s, _r, _c in persisted}) != 1:+ return "turns split across sessions"+ db_words = re.findall(TOKEN, " ".join(replies))+ shown = re.findall(TOKEN, screen)+ if shown != db_words:+ first = next((i for i, (a, b) in enumerate(zip(shown, db_words)) if a != b), min(len(shown), len(db_words)))+ return (f"screen shows {len(shown)} reply words, state.db persisted {len(db_words)}; first difference "+ f"at #{first}: screen {shown[first:first + 3]} vs db {db_words[first:first + 3]}")+ return ""++def _scenario(mode: str, root) -> object:rows = 30 if mode == "inline" else 120@@ -66,16 +102,17 @@ def _scenario(mode: str, root) -> object:tui.close()def step(tui: TmuxTui, cells, name: str, upto: int, para: int) -> None:+ cells.phase = nametui.wait_quiet(1.0)- text, cols = tui.text(), tui.size()[0]- cells.add(f"{name}_ledger", ledger_problems(text, _expected(upto), TOKEN), tui.dump())- cells.add(f"{name}_width", width_problem(tui.rows(history=True), rf"\br{para}w\d{{3}}\b", cols),- tui.dump())+ cells.add(f"{name}_ledger", ledger_problems(tui.text(), _expected(upto), TOKEN), tui.dump())+ cells.add(f"{name}_width", _frame_problem(tui, upto, para), tui.dump())def _drive(tui: TmuxTui, cells) -> None:tui.wait_ready()+ cells.phase = "turn1"tui.submit(PROMPTS[1])tui.wait_replies(1)+ cells.phase = "midstream_drag"tui.submit(PROMPTS[2])tui.wait_for("r2w030")for cols in DRAG: # a window drag: 7 SIGWINCHes in ~0.35 s while the reply streams@@ -87,6 +124,7 @@ def _scenario(mode: str, root) -> object:step(tui, cells, "idle_shrink", 2, 2)tui.resize(150)step(tui, cells, "idle_grow", 2, 2)+ cells.phase = "midstream_two_step_shrink"tui.submit(PROMPTS[3])tui.wait_for("r3w020")tui.resize(110)@@ -95,18 +133,12 @@ def _scenario(mode: str, root) -> object:tui.wait_replies(3)step(tui, cells, "midstream_two_step_shrink", 3, 3)+ cells.phase = "persisted"text = tui.text()counts = {t: text.count(f"zq{t}q") for t in N}cells.add("prompts_once", "" if set(counts.values()) == {1} else f"prompt echo counts {counts}", tui.dump())- persisted = tui.messages()- users = [c for _s, r, c in persisted if r == "user"]- replies = [c for _s, r, c in persisted if r == "assistant" and c.strip()]- problem = ""- if users != list(PROMPTS.values()) or replies != list(REPLY.values()):- problem = f"state.db rows differ from the conversation: users={users!r} replies={[r[:30] for r in replies]}"- elif len({s for s, _r, _c in persisted}) != 1:- problem = "turns split across sessions"- cells.add("persisted_matches_screen", problem)+ cells.add("persisted_matches_screen", _persisted_problem(tui.messages(), text), tui.dump())+ cells.phase = "exit"return run_cells(body)@@ -117,11 +149,9 @@ def runs() -> dict:return {}-# "<mode>:<cell>" -> "#<issue> <symptom>"; each entry is a strict xfail that turns red once fixed.-KNOWN: dict[str, str] = {}[email protected]("case", cell_params([f"{m}:{c}" for m in ("alt", "inline") for c in CELLS], KNOWN))[email protected]("case", cell_params([f"{m}:{c}" for m in ("alt", "inline") for c in CELLS]))def test_resize_transcript_ledger(runs: dict, case: str, tmp_path_factory) -> None:mode, cell = case.split(":")if mode not in runs:diff --git a/tests/e2e/core/tui_pty/test_resume_compress.py b/tests/e2e/core/tui_pty/test_resume_compress.pyindex 1b9d25e662e..c254d125003 100644--- a/tests/e2e/core/tui_pty/test_resume_compress.py+++ b/tests/e2e/core/tui_pty/test_resume_compress.py@@ -1,23 +1,27 @@"""A long Ink TUI session renders every transcript word at most once after ``/compress`` andwhen 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.+a compressed-transcript block is never painted twice (#88906), the protected tail is on screen+exactly once, the compaction summary is persisted exactly once (the TUI folds it away instead of+painting it) and never painted twice, and ``/compress`` reports once. A ``/resume`` typed while a+fresh TUI is still starting keeps the resumed transcript instead of losing it to the startup+session (#121456).Real ``hermes --tui`` in tmux against the scripted fake provider (the compression summary is anauxiliary 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.+fresh TUI processes reopen it from the same state.db."""from __future__ import annotationsimport reimport sys+import timefrom collections import Counterimport pytestfrom tests.e2e.core.tui_pty._helpers import (- TmuxTui, cell_params, poll, require_tui, run_cells, words,+ TmuxTui, cell_params, poll, private_tui_dir, require_tui, run_cells, words,)from tests.fakes.fake_llm_provider import FakeLLMServer, Text@@ -33,14 +37,26 @@ 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+# Fresh TUIs that must each keep a /resume typed during startup. The race loses roughly a third+# to two thirds of landed attempts (it is decided on the gateway's RPC pool), so the pinned bug+# almost always shows within these; a lucky run just passes, which the known-failure pin allows.+STARTUP_TRIES = 8+STARTING = "summoning hermes…" # status bar before the gateway is upCELLS = [- "compress_happened", "after_compress_no_word_twice", "after_compress_tail_once",+ "compress_happened", "compress_reported_once", "summary_persisted_once", "first_exits_clean",+ "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",+ "slash_resume_at_startup_survives",]-# cell -> "#<issue> <symptom>"; each entry is a strict xfail that turns red once fixed.-KNOWN: dict[str, str] = {}+# cell -> (regex on the bug's own failure message, "#<issue> <symptom>"): XFAILs only while the cell+# fails exactly that way, passes once the fix lands, and any other failure stays red.+KNOWN: dict[str, tuple[str, str]] = {+ "slash_resume_at_startup_survives": (+ r"the resumed transcript is gone after startup: protected tail words not exactly once",+ "#121456 /resume typed while the TUI starts is replaced by the startup session"),+}def _reply(t: int) -> str:@@ -58,6 +74,11 @@ def _tail_once(text: str) -> str:return f"protected tail words not exactly once: {bad[:6]} ({len(bad)})" if bad else ""+def _summary_persisted(tui: TmuxTui) -> str:+ n = sum(c.count("SUMMARYMARK") for _s, _r, c in tui.messages())+ return "" if n == 1 else f"compaction summary in the active state.db transcript {n}x (want exactly 1)"++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 ""@@ -68,55 +89,117 @@ def _compacted(tui: TmuxTui) -> int:return int(rows[0][0]) if rows else 0+def _judge(cells, how: str, tui: TmuxTui) -> int:+ """Word cells for one surface; returns how often the summary text is painted there."""+ 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())+ return text.count("SUMMARYMARK")+++def _first_tui(root, llm, cells, summaries: list[int]) -> str:+ """Run the long session, compress it, exit; return its session id ('' if it never compressed)."""+ first = TmuxTui(root / "a", llm.base_url, cols=140, rows=200, extra_config=CONFIG)+ try:+ first.wait_ready()+ cells.phase = "long_session"+ 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)+ cells.phase = "compress"+ 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_for("Compressed:", timeout=60)+ first.wait_quiet(1.5)+ n = first.text().count("Compressed:")+ cells.add("compress_reported_once", "" if n == 1 else f"/compress reported {n}x", first.dump())+ cells.add("summary_persisted_once", _summary_persisted(first))+ summaries.append(_judge(cells, "after_compress", first))+ sid = _session_id(first)+ cells.phase = "first_exit"+ cells.add("first_exits_clean", first.exit_problem())+ return sid+ finally:+ first.close()+++def _startup_resume(root, llm, home_env: dict[str, str], sid: str, cells) -> None:+ """/resume typed while the status bar still reads 'summoning hermes…' must stick."""+ cells.phase = "slash_resume_at_startup"+ tui_dir = private_tui_dir(root / "startup")+ landed = 0+ last = ""+ for i in range(STARTUP_TRIES * 3):+ tui = TmuxTui(root / "startup" / str(i), llm.base_url, cols=140, rows=200, write_home=False,+ env_extra=home_env, tui_dir=tui_dir)+ try:+ tui.wait_raw()+ try: # the status bar paints a moment after raw mode+ status = poll(lambda: tui.status(), timeout=3, interval=0.02, what="status bar")+ except AssertionError:+ status = ""+ if status != STARTING:+ continue # the gateway came up before we could type: not an attempt+ tui.type(f"/resume {sid}")+ time.sleep(0.15) # input pacing: text and Enter in one write is a paste+ tui.key("Enter")+ if tui.status() != STARTING:+ continue+ landed += 1+ tui.wait_ready()+ tui.wait_quiet(1.5)+ last = _tail_once(tui.text())+ if last:+ cells.add("slash_resume_at_startup_survives",+ f"attempt {landed}: the resumed transcript is gone after startup: {last}",+ tui.dump())+ return+ if landed == STARTUP_TRIES:+ cells.add("slash_resume_at_startup_survives", "")+ return+ finally:+ tui.close()+ if landed:+ cells.add("slash_resume_at_startup_survives", "")+ else:+ cells.harness_error("slash_resume_at_startup_survives",+ f"no /resume keystroke landed while any of {STARTUP_TRIES * 3} TUIs was starting")++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()-+ summaries: list[int] = []+ sid = _first_tui(root, llm, cells, summaries)+ if not sid:+ return+ home_env = {"HOME": str(root / "a" / "home"), "HERMES_HOME": str(root / "a" / "home" / ".hermes")}for how in ("resume_flag", "slash_resume"):+ cells.phase = howsub = root / howsub.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")})+ env_extra=home_env)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"))+ summaries.append(_judge(cells, how, tui))finally:tui.close()- cells.add("summary_never_twice", "" if max(summaries) <= 1 else f"summary counts {summaries}")+ cells.add("summary_never_twice", "" if max(summaries) <= 1 else f"summary painted {summaries}x")+ _startup_resume(root, llm, home_env, sid, cells)return run_cells(body)@@ -127,6 +210,6 @@ def run(tmp_path_factory):return _scenario(tmp_path_factory.mktemp("resume"))[email protected]("cell", cell_params(CELLS, KNOWN))[email protected]("cell", cell_params(CELLS))def test_long_session_compress_and_resume_render_once(run, cell: str) -> None:- run.check(cell)+ run.check(cell, KNOWN)diff --git a/tests/e2e/core/tui_pty/test_wide_chars_interrupt.py b/tests/e2e/core/tui_pty/test_wide_chars_interrupt.pyindex fc5107ba989..c8e8c6570a3 100644--- a/tests/e2e/core/tui_pty/test_wide_chars_interrupt.py+++ b/tests/e2e/core/tui_pty/test_wide_chars_interrupt.py@@ -39,8 +39,6 @@ CELLS = ["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:@@ -54,7 +52,9 @@ def _cursor_problem(tui: TmuxTui, typed: str) -> str:def _cjk(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:+ cells.phase = "cjk_startup"tui.wait_ready()+ cells.phase = "cjk_typing"tui.type(CJK_TYPED[0])tui.wait_for(CJK_TYPED[0], history=False)first = _cursor_problem(tui, CJK_TYPED[0])@@ -63,6 +63,7 @@ def _cjk(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:tui.wait_for(both, history=False)cells.add("cjk_cursor_after_typed_text", first or _cursor_problem(tui, both), tui.dump())tui.key("Enter")+ cells.phase = "cjk_reply"tui.wait_for(CJK_TOKENS[20])tui.resize(61)tui.wait_replies(1)@@ -86,8 +87,25 @@ def _cjk(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:cells.add("cjk_frame_settles", str(exc)[:2000])+def _screen_partial(rows: list[str]) -> str:+ """The interrupted reply as the screen shows it, character for character (a trailing+ half-streamed word included): the rows from its first word up to the ``[interrupted]`` mark,+ gutter stripped, joined on single spaces."""+ start = next((i for i, r in enumerate(rows) if "i1w000" in r), None)+ if start is None:+ return ""+ text = " ".join(rows[start:]).split("[interrupted]")[0]+ return " ".join(tok for tok in text.split() if tok != "┊")+++def _norm(text: str) -> str:+ return " ".join(str(text).split())++def _interrupt(tui: TmuxTui, llm: FakeLLMServer, cells) -> None:+ cells.phase = "interrupt_startup"tui.wait_ready()+ cells.phase = "interrupt_stream"tui.submit("stream then stop ix1")tui.wait_for("i1w060")tui.key("C-c")@@ -105,20 +123,25 @@ def _interrupt(tui: TmuxTui, llm: FakeLLMServer, cells) -> None: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 []+ db_raw = _norm(partial[0]) if partial else ""+ screen_raw = _screen_partial(tui.rows(history=True))+ # Raw text, not whole tokens: the cut lands mid-word, and that half word counts too.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}")+ "" if db_raw and db_raw == screen_raw+ else f"state.db partial ends {db_raw[-60:]!r} ({len(db_raw)} chars), screen shows "+ f"{screen_raw[-60:]!r} ({len(screen_raw)} chars)", tui.dump())+ cells.phase = "interrupt_next_turn"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 []+ carried_raw = _norm(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)}")+ "" if len(carried) == 1 and carried_raw == db_raw+ else f"{len(carried)} assistant messages with the partial; wire ends {carried_raw[-60:]!r} "+ f"vs state.db {db_raw[-60:]!r}")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"),@@ -140,6 +163,7 @@ def _scenario(kind: str, root) -> object:try:drive(tui, llm, cells)if kind == "interrupt":+ cells.phase = "exit"cells.add("exits_clean", tui.exit_problem())finally:tui.close()@@ -153,7 +177,7 @@ def runs() -> dict:return {}[email protected]("cell", cell_params(CELLS, KNOWN))[email protected]("cell", cell_params(CELLS))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: