The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e): dashboard sessions/profiles/config, PTY websocket, and #120527/#120937 strict-xfail cells
teknium168ab8bc48e56
diff --git a/tests/e2e/core/dashboard/_issue_helpers.py b/tests/e2e/core/dashboard/_issue_helpers.pynew file mode 100644index 00000000000..9c39bcc4e01--- /dev/null+++ b/tests/e2e/core/dashboard/_issue_helpers.py@@ -0,0 +1,231 @@+"""Shared bits for the dashboard lane's open-issue cells (#120527, #120937).++* ``PtyDashboard``: the lane's ``Dashboard`` harness, but spawned with a pseudo-terminal slave as+ stdin — the shape of ``hermes serve`` / ``hermes dashboard`` launched from an interactive+ terminal. The master end is held open and never written to (nobody watches that console).+ Teardown SIGKILLs the whole process group: a server wedged in a worker thread never finishes+ a graceful shutdown (the default executor is joined on exit).+* ``GatewayApiServer``: a real ``python -m gateway.run`` with the API-server platform enabled via+ the profile ``.env`` exactly as a user configures it (``API_SERVER_ENABLED``/``_KEY``/``_HOST``/+ ``_PORT``), retrying the pick-then-bind port race like the parity lane's driver.+* ``KnownIssue`` assertion subclasses: a strict xfail cell declares ``raises=<its subclass>`` so+ only the bug's own signature is excused; a boot failure or any other assertion stays red.+"""++from __future__ import annotations++import contextlib+import json+import os+import secrets+import signal+import subprocess+import sys+import threading+import time+import urllib.error+import urllib.request+from pathlib import Path+from typing import Any++import httpx++from tests.e2e.core.dashboard._helpers import (+ _READY_RE, _TOKEN_RE, Dashboard, Sandbox, group_pids, kill_group, poll,+)+++class KnownIssue(AssertionError):+ """Base for assertions that encode an OPEN issue's user-visible signature."""+++class Issue120527(KnownIssue):+ """#120527: a dashboard MCP catalog install wedges the serve process (interactive prompt)."""+++class Issue120937(KnownIssue):+ """#120937: /api/sessions/{id}/chat silently truncates a long message."""+++def xfail_known(known: dict[str, tuple[str, type[KnownIssue]]], name: str):+ """``pytest.mark.xfail(strict=True)`` for a KNOWN entry, excusing ONLY its issue's exception."""+ import pytest++ reason, exc = known[name]+ return pytest.mark.xfail(strict=True, raises=exc, reason=reason)+++# Dashboard with a TTY stdin -----------------------------------------------------------------------+++class PtyDashboard(Dashboard):+ """``hermes dashboard`` whose stdin is a pty slave (interactive-terminal launch); ``tty=False``+ gives the same process with stdin=/dev/null (service / desktop-spawned launch) as a control."""++ def __init__(self, sb: Sandbox, log_path: Path, extra_env: dict[str, str] | None = None,+ tty: bool = True) -> None:+ self.sb = sb+ self.log_path = log_path+ self._log = open(log_path, "a", encoding="utf-8") # noqa: SIM115 - closed in close()+ if tty:+ self.pty_master, slave = os.openpty()+ else:+ self.pty_master, slave = -1, os.open(os.devnull, os.O_RDONLY)+ env = sb.env({"HERMES_WEB_DIST": str(sb.root / "web_dist"), "TERM": "xterm-256color",+ **(extra_env or {})})+ try:+ self.proc = subprocess.Popen(+ [sys.executable, "-m", "hermes_cli.main", "dashboard", "--no-open", "--skip-build",+ "--host", "127.0.0.1", "--port", "0"],+ cwd=str(sb.home), env=env, stdin=slave, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, bufsize=1, start_new_session=True,+ )+ finally:+ os.close(slave)+ port_box: list[int] = []++ def pump() -> None:+ assert self.proc.stdout is not None+ for line in self.proc.stdout:+ self._log.write(line)+ self._log.flush()+ m = _READY_RE.search(line)+ if m and not port_box:+ port_box.append(int(m.group(1)))+ threading.Thread(target=pump, daemon=True, name="dash-pty-stdout").start()+ try:+ self.port = poll(lambda: port_box[0] if port_box else (self.proc.poll() is not None and -1), 120,+ "hermes dashboard (tty stdin) to report its port")+ assert self.port > 0, f"hermes dashboard exited rc={self.proc.returncode}:\n{self.log_tail()}"+ self.base = f"http://127.0.0.1:{self.port}"+ self.http = httpx.Client(base_url=self.base, timeout=30.0, trust_env=False)+ index = self.http.get("/")+ m = _TOKEN_RE.search(index.text)+ assert index.status_code == 200 and m, f"index.html carried no session token: {index.status_code}"+ self.token = m.group(1)+ except BaseException:+ self.close()+ raise++ def stdin_target(self) -> str:+ """What the child's fd 0 really is (read from the child itself): /dev/pts/N or /dev/null."""+ try:+ return os.readlink(f"/proc/{self.proc.pid}/fd/0")+ except OSError as exc:+ return f"unreadable: {exc}"++ def close(self) -> None:+ with contextlib.suppress(Exception):+ self.http.close()+ pids = group_pids(self.proc.pid)+ kill_group(self.proc) # SIGKILL: a wedged worker thread blocks any graceful exit+ with contextlib.suppress(Exception):+ self.proc.wait(timeout=15)+ for pid in pids: # anything that left the group (setsid'd MCP children) but was ours+ with contextlib.suppress(ProcessLookupError, PermissionError):+ os.kill(pid, signal.SIGKILL)+ if self.pty_master >= 0:+ with contextlib.suppress(OSError):+ os.close(self.pty_master)+ with contextlib.suppress(Exception):+ self._log.close()+++# Gateway API server ------------------------------------------------------------------------------+++PORT_ATTEMPTS = 3+++def _free_port() -> int:+ import socket+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def http_json(method: str, url: str, *, key: str | None = None, body: Any = None,+ timeout: float = 10.0) -> tuple[int, Any]:+ data = json.dumps(body).encode() if body is not None else None+ req = urllib.request.Request(url, data=data, method=method)+ if data is not None:+ req.add_header("Content-Type", "application/json")+ if key:+ req.add_header("Authorization", f"Bearer {key}")+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ raw = resp.read().decode("utf-8", "replace")+ status = resp.status+ except urllib.error.HTTPError as exc:+ raw, status = exc.read().decode("utf-8", "replace"), exc.code+ try:+ return status, json.loads(raw)+ except ValueError:+ return status, {"raw": raw}+++class GatewayApiServer:+ """``python -m gateway.run`` serving the API-server platform on 127.0.0.1:<port>."""++ def __init__(self, sb: Sandbox, hermes_home: Path, log_path: Path, ready_timeout: float = 120.0) -> None:+ self.sb, self.hermes_home, self.log_path = sb, hermes_home, log_path+ self.key = secrets.token_hex(32)+ env_path = hermes_home / ".env"+ env_before = env_path.read_text(encoding="utf-8") if env_path.exists() else ""+ for _ in range(PORT_ATTEMPTS):+ port = _free_port()+ env_path.write_text(env_before + "".join(f"{k}={v}\n" for k, v in {+ "API_SERVER_ENABLED": "true", "API_SERVER_KEY": self.key,+ "API_SERVER_HOST": "127.0.0.1", "API_SERVER_PORT": str(port)}.items()), encoding="utf-8")+ self._log = open(log_path, "a", encoding="utf-8") # noqa: SIM115 - closed in stop()+ self.proc = subprocess.Popen(+ [sys.executable, "-m", "gateway.run"], cwd=str(sb.home), env=sb.env({"HERMES_HOME": str(hermes_home)}),+ stdin=subprocess.DEVNULL, stdout=self._log, stderr=subprocess.STDOUT, start_new_session=True,+ )+ self.base = f"http://127.0.0.1:{port}"+ try:+ ready = self._await_ready(ready_timeout)+ except BaseException:+ self.stop()+ raise+ if ready:+ return+ self.stop()+ raise AssertionError(f"api server lost the port race {PORT_ATTEMPTS} times\n{self.log_tail()}")++ def log_tail(self, n: int = 4000) -> str:+ try:+ return self.log_path.read_text(encoding="utf-8", errors="replace")[-n:]+ except OSError:+ return ""++ def _await_ready(self, timeout: float) -> bool:+ deadline = time.monotonic() + timeout+ while True:+ if "already in use" in self.log_tail(20000):+ return False+ if self.proc.poll() is not None:+ raise AssertionError(f"gateway exited {self.proc.returncode} before ready\n{self.log_tail()}")+ if time.monotonic() >= deadline:+ raise AssertionError(f"api server never became ready on {self.base}\n{self.log_tail()}")+ with contextlib.suppress(OSError, urllib.error.URLError, ValueError):+ status, body = http_json("GET", f"{self.base}/health/detailed", key=self.key, timeout=2.0)+ if status == 200 and isinstance(body, dict) and body.get("pid") == self.proc.pid:+ return True+ time.sleep(0.2)++ def call(self, method: str, path: str, body: Any = None, timeout: float = 60.0) -> tuple[int, Any]:+ return http_json(method, f"{self.base}{path}", key=self.key, body=body, timeout=timeout)++ def stop(self) -> None:+ if self.proc.poll() is None:+ kill_group(self.proc, signal.SIGTERM)+ try:+ self.proc.wait(timeout=20)+ except subprocess.TimeoutExpired:+ pass+ kill_group(self.proc)+ with contextlib.suppress(Exception):+ self.proc.wait(timeout=10)+ with contextlib.suppress(Exception):+ self._log.close()diff --git a/tests/e2e/core/dashboard/_pty_helpers.py b/tests/e2e/core/dashboard/_pty_helpers.pynew file mode 100644index 00000000000..87bf104ab1c--- /dev/null+++ b/tests/e2e/core/dashboard/_pty_helpers.py@@ -0,0 +1,243 @@+"""Client side of the dashboard's embedded-TUI WebSocket (``/api/pty``), as the browser xterm speaks it.++Frames are raw PTY bytes both ways; the only control frame the client sends is the resize escape+``\\x1b[RESIZE:<cols>;<rows>]`` (consumed by the server, never written to the child). The server+may send one JSON text frame (``{"type": "resume", ...}``) before the byte stream; it is recorded,+never rendered. Output is rendered through the terminal suite's VT emulator so assertions read what+the user sees, independent of how Ink split its repaints across frames.++Input follows the terminal suite's rule for Ink: the typed text and the submitting ``\\r`` are+separate writes, and the CR is only sent once the text is echoed in the composer.++Process bookkeeping (``ProcessLedger``) records every descendant of the dashboard by (pid, start+time) plus the session ids they lead: ``ptyprocess`` makes each TUI a session leader outside the+dashboard's process group, so a group kill does not reach it and only the dashboard's own shutdown+path can.+"""++from __future__ import annotations++import json+import os+import re+import signal+import threading+import time+from pathlib import Path+from typing import Any, Callable++from websockets.exceptions import ConnectionClosed+from websockets.sync.client import connect++from tests.e2e.core.terminal._vt import Screen++_WS = re.compile(r"\s+")+_DIGITS = re.compile(r"\d")+_SCROLLBAR = "│┃║▐▕█░▒▓"+++def canon(text: str) -> str:+ """Whitespace-free form: independent of where the terminal (or Ink) wrapped a line."""+ return _WS.sub("", text)+++def poll(fn: Callable[[], Any], timeout: float, what: str, interval: float = 0.05) -> Any:+ deadline = time.monotonic() + timeout+ while True:+ value = fn()+ if value:+ return value+ if time.monotonic() >= deadline:+ raise AssertionError(f"timed out after {timeout:.0f}s waiting for {what}")+ time.sleep(interval)+++class WsTerm:+ """One browser-side xterm attached to ``/api/pty``."""++ def __init__(self, url: str, *, rows: int = 40, cols: int = 120) -> None:+ self.url = url+ self.screen = Screen(rows, cols)+ self.raw = bytearray()+ self.control: list[dict[str, Any]] = []+ self.first_frames: list[bytes] = [] # the first few binary frames, verbatim (replay proof)+ self.close_code: int | None = None+ self._lock = threading.Lock()+ self._closed = threading.Event()+ self.ws = connect(url, open_timeout=30, max_size=None, close_timeout=5)+ self.ws.send(f"\x1b[RESIZE:{cols};{rows}]")+ self._reader = threading.Thread(target=self._read_loop, name="ws-pty-reader", daemon=True)+ self._reader.start()++ # -- io -----------------------------------------------------------------------------------------++ def _read_loop(self) -> None:+ try:+ while True:+ frame = self.ws.recv()+ if isinstance(frame, str):+ try:+ payload = json.loads(frame)+ except ValueError:+ payload = None+ if isinstance(payload, dict) and "type" in payload:+ self.control.append(payload)+ continue+ frame = frame.encode("utf-8")+ elif len(self.first_frames) < 4:+ self.first_frames.append(bytes(frame))+ with self._lock:+ self.raw.extend(frame)+ self.screen.feed(frame)+ except ConnectionClosed as exc:+ self.close_code = exc.rcvd.code if exc.rcvd else None+ except Exception: # noqa: BLE001 - socket torn down under us by close()+ pass+ finally:+ self._closed.set()++ def write(self, data: str) -> None:+ self.ws.send(data.encode("utf-8"))++ def close(self) -> None:+ """Client-side close (a browser tab refresh / transient drop)."""+ try:+ self.ws.close()+ except Exception: # noqa: BLE001+ pass+ self._closed.wait(10)++ @property+ def closed(self) -> bool:+ return self._closed.is_set()++ # -- screen views -------------------------------------------------------------------------------++ def lines(self) -> list[str]:+ with self._lock:+ rows = self.screen.display() if self.screen.alt_active else self.screen.transcript()+ cols = self.screen.cols+ return [ln[: cols - 1] if len(ln) >= cols and ln[cols - 1] in _SCROLLBAR else ln for ln in rows]++ def text(self) -> str:+ return canon("".join(self.lines()))++ def raw_text(self) -> str:+ with self._lock:+ return bytes(self.raw).decode("utf-8", "replace")++ def dump(self) -> str:+ return "\n".join(self.lines()[-60:])++ def wait_for(self, needle: str, timeout: float = 60.0) -> None:+ try:+ poll(lambda: canon(needle) in self.text() or self.closed, timeout, f"{needle[:60]!r} on the xterm")+ except AssertionError as exc:+ raise AssertionError(f"{exc}\n--- screen ---\n{self.dump()}") from None+ assert canon(needle) in self.text(), (+ f"/api/pty closed (code={self.close_code}) before {needle[:60]!r} rendered\n--- screen ---\n{self.dump()}")++ def wait_quiet(self, idle: float = 1.0, timeout: float = 60.0) -> None:+ """A settled frame: nothing but digits (status-bar clocks) changed for ``idle`` seconds."""+ state = {"frame": "", "since": time.monotonic()}++ def settled() -> bool:+ cur = _DIGITS.sub("#", "\n".join(self.lines()))+ now = time.monotonic()+ if cur != state["frame"]:+ state["frame"], state["since"] = cur, now+ return bool(cur.strip()) and now - state["since"] >= idle+ try:+ poll(settled, timeout, "a settled TUI frame", interval=0.1)+ except AssertionError as exc:+ raise AssertionError(f"{exc}\n--- screen ---\n{self.dump()}\n--- tail ---\n{bytes(self.raw[-600:])!r}") from None++ def submit(self, text: str, timeout: float = 30.0) -> None:+ """Type ``text``; once the composer echoes it, press Enter in a separate write."""+ before = self.text().count(canon(text))+ self.write(text)+ try:+ poll(lambda: self.text().count(canon(text)) > before or self.closed, timeout, f"echo of {text!r}")+ except AssertionError as exc:+ raise AssertionError(f"{exc}\n--- screen ---\n{self.dump()}") from None+ assert not self.closed, f"/api/pty closed (code={self.close_code}) while typing\n{self.dump()}"+ self.write("\r")+++# -- process bookkeeping ---------------------------------------------------------------------------+++def _stat(pid: int) -> list[str] | None:+ """Fields after ``comm`` of a live, non-zombie process (state is index 0)."""+ try:+ fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()+ except (OSError, IndexError):+ return None+ return None if fields[0] in ("Z", "X") else fields+++def _start_time(pid: int) -> int | None:+ fields = _stat(pid)+ return int(fields[19]) if fields else None+++def cmdline(pid: int) -> str:+ try:+ return Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace").strip()+ except OSError:+ return "?"+++def _all_stats() -> dict[int, list[str]]:+ out = {}+ for entry in os.listdir("/proc"):+ if entry.isdigit() and (fields := _stat(int(entry))) is not None:+ out[int(entry)] = fields+ return out+++class ProcessLedger:+ """Every process the dashboard (transitively) spawned, keyed by (pid, start time)."""++ def __init__(self, root_pid: int) -> None:+ self.root_pid = root_pid+ self.seen: dict[tuple[int, int], str] = {}+ self.sids: set[int] = set()++ def snapshot(self) -> list[int]:+ stats = _all_stats()+ children: dict[int, list[int]] = {}+ for pid, fields in stats.items():+ children.setdefault(int(fields[1]), []).append(pid)+ found, todo = set(), [self.root_pid]+ while todo:+ for child in children.get(todo.pop(), ()):+ if child not in found:+ found.add(child)+ todo.append(child)+ # A PTY child is a session leader: anything in its session is ours even after reparenting.+ self.sids |= {pid for pid in found if int(stats[pid][3]) == pid}+ found |= {pid for pid, fields in stats.items() if int(fields[3]) in self.sids}+ for pid in found:+ self.seen.setdefault((pid, int(stats[pid][19])), cmdline(pid))+ return sorted(found)++ def survivors(self) -> list[str]:+ live = {pid for pid, started in self.seen if _start_time(pid) == started}+ live |= {pid for pid, fields in _all_stats().items() if int(fields[3]) in self.sids}+ return [f"{pid}: {cmdline(pid)[:160]}" for pid in sorted(live)]++ def kill_survivors(self) -> list[str]:+ """Hard cleanup of exactly the processes recorded here (identity-checked, never by pattern).+ Uses the real ``kill(2)``: a survivor reparented to init is outside pytest's subtree, which+ the suite-wide live-system guard would otherwise refuse, yet it is provably ours (same pid+ AND kernel start time as recorded while it descended from the dashboard)."""+ import posix+ left = self.survivors()+ for (pid, started) in list(self.seen):+ if _start_time(pid) == started:+ try:+ posix.kill(pid, signal.SIGKILL)+ except (ProcessLookupError, PermissionError):+ pass+ return leftdiff --git a/tests/e2e/core/dashboard/fixture_catalog_mcp.py b/tests/e2e/core/dashboard/fixture_catalog_mcp.pynew file mode 100644index 00000000000..462ac0bd744--- /dev/null+++ b/tests/e2e/core/dashboard/fixture_catalog_mcp.py@@ -0,0 +1,30 @@+"""Tiny offline stdio MCP server installed through the dashboard's MCP catalog (#120527 cell).++Two tools, so the catalog install's tool probe SUCCEEDS with a non-empty list: that is the branch+of ``hermes_cli.mcp_catalog._apply_tool_selection`` that decides between the non-interactive+default and the interactive tool checklist. Nothing here touches the network.+"""++from __future__ import annotations+++def main() -> None:+ from mcp.server import MCPServer++ server = MCPServer("dash-catalog-fixture")++ @server.tool()+ def catalog_alpha(text: str = "") -> str:+ """Echo the input (fixture tool one)."""+ return f"alpha:{text}"++ @server.tool()+ def catalog_beta(text: str = "") -> str:+ """Reverse the input (fixture tool two)."""+ return text[::-1]++ server.run(transport="stdio")+++if __name__ == "__main__":+ main()diff --git a/tests/e2e/core/dashboard/test_api_session_chat_limits.py b/tests/e2e/core/dashboard/test_api_session_chat_limits.pynew file mode 100644index 00000000000..82105207902--- /dev/null+++ b/tests/e2e/core/dashboard/test_api_session_chat_limits.py@@ -0,0 +1,145 @@+"""#120937: session chat on the gateway API server must never silently truncate a long message.++Real ``python -m gateway.run`` with the API-server platform enabled through the profile ``.env``+(``API_SERVER_ENABLED``/``API_SERVER_KEY``/host/port, as a user configures it), sandboxed+HOME/HERMES_HOME, the model routed to ``FakeLLMServer`` — which records every request, so the cell+reads exactly what the model was sent.++Contract for ``POST /api/sessions/{id}/chat``: a message either reaches the model whole (length+kept, tail canary present) or the API answers an explicit 4xx — never a 200 on a cut prompt.+Controls (enforced, separate test): a 60,000-char message through the same ``/chat`` and a+100,000-char ``input`` through ``/v1/runs`` both reach the model whole.+"""++from __future__ import annotations++import secrets+import time+from pathlib import Path+from typing import Any, Iterator++import pytest++from tests.e2e.core.dashboard._helpers import Sandbox, make_sandbox+from tests.e2e.core.dashboard._issue_helpers import GatewayApiServer, Issue120937, xfail_known++TURN_TIMEOUT = 90.0++KNOWN: dict[str, tuple[str, type]] = {+ "test_session_chat_100k_message_reaches_model_whole_or_is_rejected": (+ "#120937 POST /api/sessions/{id}/chat silently truncates a string message to 65,536 chars "+ "(200, no error, no flag)", Issue120937),+}++[email protected](scope="module")+def gateway(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[Sandbox, GatewayApiServer]]:+ root = tmp_path_factory.mktemp("gw120937")+ sb = make_sandbox(root)+ gw = None+ try:+ gw = GatewayApiServer(sb, sb.hermes_home, root / "gateway.log")+ yield sb, gw+ finally:+ if gw is not None:+ gw.stop()+ sb.stop()+++def _long_message(n: int) -> tuple[str, str, str]:+ """``(message, head, tail)``: exactly ``n`` chars, a unique head marker and a unique tail canary."""+ head, tail = f"HEAD-{secrets.token_hex(6)}::", f"::TAIL-CANARY-{secrets.token_hex(8)}"+ body = ("lorem ipsum dolor sit amet " * (n // 27 + 1))[: n - len(head) - len(tail)]+ msg = head + body + tail+ assert len(msg) == n+ return msg, head, tail+++def _text(content: Any) -> str:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "".join(p.get("text", "") for p in content if isinstance(p, dict))+ return ""+++def _model_saw(sb: Sandbox, head: str, timeout: float = TURN_TIMEOUT) -> str:+ """The user message (containing ``head``) of the provider's recorded main request."""+ srv = sb.profiles["default"].srv+ assert srv is not None+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ for body in reversed(srv.main_requests()):+ for m in reversed(body.get("messages") or []):+ if m.get("role") == "user" and head in _text(m.get("content")):+ return _text(m.get("content"))+ time.sleep(0.1)+ raise AssertionError(f"the model never received a user message carrying {head!r}")+++def _new_session(gw: GatewayApiServer) -> str:+ sid = f"e2e120937-{secrets.token_hex(5)}"+ status, body = gw.call("POST", "/api/sessions", {"id": sid})+ assert status == 201, f"POST /api/sessions -> {status}: {body}\n{gw.log_tail()}"+ return sid+++def _stored_user_len(gw: GatewayApiServer, sid: str, head: str) -> int | None:+ status, body = gw.call("GET", f"/api/sessions/{sid}/messages")+ if status != 200:+ return None+ for m in body.get("messages") or body.get("data") or []:+ if m.get("role") == "user" and head in _text(m.get("content")):+ return len(_text(m.get("content")))+ return None+++def _chat(gw: GatewayApiServer, sid: str, message: str) -> tuple[int, Any]:+ return gw.call("POST", f"/api/sessions/{sid}/chat", {"message": message}, timeout=TURN_TIMEOUT)+++def test_session_chat_60k_and_runs_100k_reach_model_whole(gateway: tuple[Sandbox, GatewayApiServer]) -> None:+ """Controls (enforced): under the session-chat cap, and on /v1/runs above it, nothing is cut."""+ sb, gw = gateway+ msg, head, tail = _long_message(60_000)+ sid = _new_session(gw)+ status, body = _chat(gw, sid, msg)+ assert status == 200, f"/chat 60k -> {status}: {str(body)[:500]}\n{gw.log_tail()}"+ seen = _model_saw(sb, head)+ assert len(seen) >= len(msg) and tail in seen, (+ f"/api/sessions/{{id}}/chat delivered {len(seen)} of {len(msg)} chars (tail canary "+ f"{'present' if tail in seen else 'MISSING'})")++ msg, head, tail = _long_message(100_000)+ status, body = gw.call("POST", "/v1/runs", {"input": msg}, timeout=TURN_TIMEOUT)+ assert status == 202, f"/v1/runs -> {status}: {str(body)[:500]}"+ seen = _model_saw(sb, head)+ assert len(seen) >= len(msg) and tail in seen, (+ f"/v1/runs delivered {len(seen)} of {len(msg)} chars (tail canary {'present' if tail in seen else 'MISSING'})")+ run_id = body["run_id"]+ deadline, run = time.monotonic() + TURN_TIMEOUT, {}+ while time.monotonic() < deadline: # settle the run so the module teardown stops an idle gateway+ st, run = gw.call("GET", f"/v1/runs/{run_id}")+ if st == 200 and run.get("status") in {"completed", "failed", "cancelled"}:+ break+ time.sleep(0.2)+ assert run.get("status") == "completed", f"/v1/runs/{run_id} -> {run}"+++@xfail_known(KNOWN, "test_session_chat_100k_message_reaches_model_whole_or_is_rejected")+def test_session_chat_100k_message_reaches_model_whole_or_is_rejected(+ gateway: tuple[Sandbox, GatewayApiServer]) -> None:+ sb, gw = gateway+ msg, head, tail = _long_message(100_000)+ sid = _new_session(gw)+ status, body = _chat(gw, sid, msg)+ if 400 <= status < 500: # an explicit rejection honours the contract+ assert isinstance(body, dict) and body.get("error"), f"{status} without an error body: {body}"+ return+ assert status == 200, f"/chat 100k -> {status}: {str(body)[:500]}\n{gw.log_tail()}"+ seen = _model_saw(sb, head)+ if len(seen) < len(msg) or tail not in seen:+ raise Issue120937(+ f"#120937 /api/sessions/{{id}}/chat answered 200 but the model received {len(seen)} of "+ f"{len(msg)} chars (tail canary {'present' if tail in seen else 'MISSING'}; stored user "+ f"message length {_stored_user_len(gw, sid, head)}; response keys {sorted(body)[:12]})")diff --git a/tests/e2e/core/dashboard/test_dashboard_mcp_install.py b/tests/e2e/core/dashboard/test_dashboard_mcp_install.pynew file mode 100644index 00000000000..d61baac86cf--- /dev/null+++ b/tests/e2e/core/dashboard/test_dashboard_mcp_install.py@@ -0,0 +1,141 @@+"""#120527: a dashboard MCP catalog install must never wedge the web server.++Real ``hermes dashboard`` launched the way the reporter launched ``hermes serve``: from an+interactive terminal, so the process's stdin IS a TTY (a pty slave here; the master is held open and+never written — nobody is watching that console). The MCP catalog is sourced through its supported+package-manager override (``HERMES_OPTIONAL_MCPS``) from a directory holding one manifest for a+local offline stdio MCP server (``fixture_catalog_mcp.py``), whose tool probe succeeds.++User-visible contract (what the Connectors page needs):+* ``POST /api/mcp/catalog/install`` answers — success or a clear 4xx — within a bounded deadline;+* afterwards an unrelated profile-scoped request (``GET /api/config``) and a ``/api/ws`` upgrade+ still complete within a few seconds.++Before the fix the install reaches the interactive tool checklist on the serve worker thread, blocks+forever on a console read, and keeps holding the process-global ``_SKILLS_PROFILE_LOCK``, so every+later profile-scoped request parks behind it.+"""++from __future__ import annotations++import concurrent.futures+import os+import sys+import time+from pathlib import Path++import pytest+import yaml++from tests.e2e.core.dashboard._helpers import make_sandbox+from tests.e2e.core.dashboard._issue_helpers import Issue120527, PtyDashboard, xfail_known++INSTALL_DEADLINE_S = 30.0 # a healthy install (write config + spawn/probe a local server) takes ~2 s+FOLLOWUP_DEADLINE_S = 5.0+FIXTURE = Path(__file__).with_name("fixture_catalog_mcp.py")++# Open issues this file encodes. A strict xfail XPASSes (and fails) the moment the fix lands, so the+# entry is removed with the fix; ``raises`` excuses only the issue's own assertion class.+KNOWN: dict[str, tuple[str, type]] = {+ "test_catalog_install_from_tty_launched_dashboard_never_wedges_the_server": (+ "#120527 dashboard MCP catalog install reaches the interactive tool checklist on the serve "+ "worker thread when stdin is a TTY and wedges _SKILLS_PROFILE_LOCK", Issue120527),+}+++def _write_catalog(root: Path, name: str) -> Path:+ catalog = root / "optional-mcps"+ (catalog / name).mkdir(parents=True)+ (catalog / name / "manifest.yaml").write_text(yaml.safe_dump({+ "manifest_version": 1,+ "name": name,+ "description": "Offline stdio fixture MCP for the dashboard e2e lane.",+ "source": "tests/e2e/core/dashboard/fixture_catalog_mcp.py",+ "transport": {"type": "stdio", "command": sys.executable, "args": [str(FIXTURE)]},+ "auth": {"type": "none"},+ }, sort_keys=False), encoding="utf-8")+ return catalog+++def _ws_opens(url: str, timeout: float) -> str:+ from websockets.sync.client import connect+ try:+ with connect(url, open_timeout=timeout, max_size=None):+ return "accepted"+ except TimeoutError:+ return f"timed out after {timeout}s"+ except Exception as exc: # noqa: BLE001 - reported verbatim in the assertion+ return f"{type(exc).__name__}: {exc}"+++def _install_and_probe(tmp_path: Path, *, tty: bool, wedge_exc: type[AssertionError]) -> dict:+ """Install the fixture entry through the dashboard, then probe the server's liveness.++ Raises ``wedge_exc`` when the install misses its deadline or a follow-up request stalls;+ returns the installed ``mcp_servers.<name>`` block when the install answered 200."""+ sb = make_sandbox(tmp_path)+ name = f"dashfix-{sb.profiles['default'].tag}"+ catalog = _write_catalog(tmp_path, name)+ dash = PtyDashboard(sb, tmp_path / "dashboard.log", extra_env={"HERMES_OPTIONAL_MCPS": str(catalog)}, tty=tty)+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=3, thread_name_prefix="e2e-120527")+ try:+ stdin = dash.stdin_target()+ assert stdin.startswith("/dev/pts/") if tty else stdin == os.devnull, f"precondition: stdin is {stdin}"+ listed = dash.ok("GET", "/api/mcp/catalog")+ entries = {e["name"]: e for e in listed["entries"]}+ assert name in entries and not entries[name]["installed"], f"fixture entry not listed: {sorted(entries)}"+ # Sanity before the install: the follow-up probe is fast on an idle server.+ assert dash.request("GET", "/api/config", timeout=FOLLOWUP_DEADLINE_S * 4).status_code == 200++ t0 = time.monotonic()+ install = pool.submit(dash.request, "POST", "/api/mcp/catalog/install",+ json={"name": name, "enable": True}, timeout=INSTALL_DEADLINE_S)+ try:+ resp = install.result(timeout=INSTALL_DEADLINE_S + 5)+ install_outcome = f"HTTP {resp.status_code} {resp.text[:300]}"+ except Exception as exc: # noqa: BLE001 - httpx.ReadTimeout on the bug+ resp, install_outcome = None, f"{type(exc).__name__} after {time.monotonic() - t0:.1f}s"++ # Both follow-ups run concurrently, after the install either answered or timed out.+ config = pool.submit(dash.request, "GET", "/api/config", timeout=FOLLOWUP_DEADLINE_S)+ ws = pool.submit(_ws_opens, dash.ws_url("/api/ws", token=dash.token), FOLLOWUP_DEADLINE_S)+ try:+ config_outcome = f"HTTP {config.result(timeout=FOLLOWUP_DEADLINE_S + 5).status_code}"+ except Exception as exc: # noqa: BLE001+ config_outcome = type(exc).__name__+ ws_outcome = ws.result(timeout=FOLLOWUP_DEADLINE_S + 10)++ if resp is None or config_outcome != "HTTP 200" or ws_outcome != "accepted":+ raise wedge_exc(+ f"dashboard wedged by an MCP catalog install (stdin={stdin}): "+ f"install -> {install_outcome} (deadline {INSTALL_DEADLINE_S}s); "+ f"GET /api/config -> {config_outcome}; /api/ws -> {ws_outcome}\n"+ f"--- dashboard log tail ---\n{dash.log_tail(1500)}")+ # The install answered: success installs the entry, an error must be a clear 4xx (never 5xx).+ assert resp.status_code == 200 or 400 <= resp.status_code < 500, install_outcome+ if resp.status_code != 200:+ assert resp.json().get("detail"), f"4xx without a detail message: {install_outcome}"+ return {}+ servers = sb.profiles["default"].config().get("mcp_servers") or {}+ assert name in servers, f"install reported ok but config.yaml has no {name}: {sorted(servers)}"+ listed = {e["name"]: e for e in dash.ok("GET", "/api/mcp/catalog")["entries"]}+ assert listed[name]["installed"] and listed[name]["enabled"], listed[name]+ return servers[name]+ finally:+ pool.shutdown(wait=False, cancel_futures=True)+ dash.close()+ sb.stop()+++def test_catalog_install_from_headless_dashboard_completes_with_all_probed_tools(tmp_path: Path) -> None:+ """Control (enforced): the same install from a stdin=/dev/null dashboard answers 200 promptly,+ leaves the server responsive, and — the manifest declaring no default_enabled — writes no tool+ filter, so both probed fixture tools stay enabled."""+ block = _install_and_probe(tmp_path, tty=False, wedge_exc=AssertionError)+ assert block, "headless install did not answer 200"+ assert block.get("enabled") is True and "tools" not in block, f"unexpected tool filter: {block}"+++@xfail_known(KNOWN, "test_catalog_install_from_tty_launched_dashboard_never_wedges_the_server")+def test_catalog_install_from_tty_launched_dashboard_never_wedges_the_server(tmp_path: Path) -> None:+ _install_and_probe(tmp_path, tty=True, wedge_exc=Issue120527)diff --git a/tests/e2e/core/dashboard/test_dashboard_profiles.py b/tests/e2e/core/dashboard/test_dashboard_profiles.pynew file mode 100644index 00000000000..6e03f0462d7--- /dev/null+++ b/tests/e2e/core/dashboard/test_dashboard_profiles.py@@ -0,0 +1,167 @@+"""Profile switching through the dashboard API never crosses profiles, and a Config-page save+round-trips the user's file.++Users hit the first as "I switched the dashboard to profile B and saw A's sessions / saved B's key+into A's .env" (one dashboard process serves every profile; the SPA's switcher appends+``?profile=<name>`` to each call, ``web/src/lib/api.ts``). Each profile owns random canaries (model+id, provider key, a config marker, session ids); the invariant after every step of an A -> B -> A ->+default -> B walk, and under concurrent interleaved requests, is that a response for profile X+carries only X's canaries and a write addressed to X changes only X's files.++The second is the Config page's save: it GETs the defaulted record, edits one field and PUTs the+whole record back. The file on disk must change in exactly that field: unknown keys (a newer+version's settings, hand-added blocks) and explicit ``null``s survive, and defaults are not+materialised into the user's sparse YAML.+"""++from __future__ import annotations++import json+import sys+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Any++import pytest+import yaml++from . import _helpers as H++pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="POSIX dashboard process")++NAMES = ("default", "alpha", "beta")+WALK = ("alpha", "beta", "alpha", "default", "beta")+SEEDS = {"default": 3, "alpha": 5, "beta": 7} # distinct counts: a wrong-profile list is visible++[email protected](scope="module")+def fleet(tmp_path_factory: pytest.TempPathFactory):+ sb = H.make_sandbox(tmp_path_factory.mktemp("dash-profiles"), NAMES)+ for name, p in sb.profiles.items():+ H.seed_sessions(sb, p, f"{name}-{p.tag}", SEEDS[name])+ d = H.Dashboard(sb, sb.root / "dashboard.log")+ try:+ yield sb, d+ finally:+ d.close()+ sb.stop()+++def _files(sb: H.Sandbox) -> dict[str, bytes]:+ return {f"{p.name}/{n}": (p.home / n).read_bytes() for p in sb.profiles.values() for n in ("config.yaml", ".env")}+++def _foreign(sb: H.Sandbox, owner: str, blob: str) -> list[str]:+ return [f"{u.name}'s {kind}" for u in sb.profiles.values() if u.name != owner+ for kind, value in {**u.canaries(), "session prefix": f"{u.name}-{u.tag}-"}.items() if value in blob]+++def _check_reads(sb: H.Sandbox, d: H.Dashboard, name: str) -> list[str]:+ p = sb.profiles[name]+ out: list[str] = []+ listing = d.ok("GET", "/api/sessions", name, params={"limit": 100})+ ids = sorted(s["id"] for s in listing["sessions"])+ want = sorted(f"{name}-{p.tag}-{i:04d}" for i in range(SEEDS[name]))+ if ids != want or listing["total"] != SEEDS[name]:+ out.append(f"{name}: session list {ids} (total {listing['total']}), expected {want}")+ if any(s.get("profile") != name for s in listing["sessions"]):+ out.append(f"{name}: rows stamped {sorted({s.get('profile') for s in listing['sessions']})}")+ for other in sb.profiles.values():+ if other.name != name:+ r = d.request("GET", f"/api/sessions/{other.name}-{other.tag}-0000", name)+ if r.status_code != 404:+ out.append(f"{name}: detail of {other.name}'s session -> {r.status_code}")+ cfg = d.ok("GET", "/api/config", name)+ model = cfg.get("model") # the web shape flattens model to its id string+ model = model.get("default") if isinstance(model, dict) else model+ if cfg.get("dash_canary", {}).get("marker") != p.marker or model != p.model:+ out.append(f"{name}: /api/config served marker={cfg.get('dash_canary')} model={model}")+ env = d.ok("GET", "/api/env", name)+ if not env.get(H.PROVIDER_KEY_ENV, {}).get("is_set"):+ out.append(f"{name}: /api/env lost its own {H.PROVIDER_KEY_ENV}")+ blob = json.dumps(listing) + json.dumps(cfg) + json.dumps(env)+ if p.provider_key in json.dumps(env):+ out.append(f"{name}: /api/env returned the raw provider key")+ return out + [f"{name} read carries {leak}" for leak in _foreign(sb, name, blob)]+++def test_profile_walk_reads_and_writes_only_the_selected_profile(fleet) -> None:+ sb, d = fleet+ problems: list[str] = []+ for step, name in enumerate(WALK):+ problems += _check_reads(sb, d, name)+ p = sb.profiles[name]+ before = _files(sb)+ d.ok("PUT", "/api/config", name, json={"config": {"dash_canary": {"marker": p.marker, "step": f"{name}-{step}"}}})+ d.ok("PUT", "/api/env", name, json={"key": "DASH_EXTRA", "value": f"extra-{name}-{p.tag}-{step}"})+ changed = {k for k, v in _files(sb).items() if before[k] != v}+ if changed != {f"{name}/config.yaml", f"{name}/.env"}:+ problems.append(f"step {step} ({name}): writes changed {sorted(changed)}")+ if p.config().get("dash_canary", {}).get("step") != f"{name}-{step}":+ problems.append(f"step {step} ({name}): config write did not land in {name}/config.yaml")+ if f"DASH_EXTRA=extra-{name}-{p.tag}-{step}" not in (p.home / ".env").read_text():+ problems.append(f"step {step} ({name}): env write did not land in {name}/.env")+ assert not problems, "profile crossing during the A->B->A walk:\n " + "\n ".join(problems)+++def test_interleaved_profile_requests_never_cross(fleet) -> None:+ """Two tabs on different profiles, requests racing: each response is the asked profile's."""+ sb, d = fleet++ def hammer(name: str) -> list[str]:+ p = sb.profiles[name]+ out = []+ for _ in range(25):+ cfg = d.ok("GET", "/api/config", name)+ if cfg.get("dash_canary", {}).get("marker") != p.marker:+ out.append(f"{name}: got marker {cfg.get('dash_canary', {}).get('marker')}")+ total = d.ok("GET", "/api/sessions", name, params={"limit": 1})["total"]+ if total != SEEDS[name]:+ out.append(f"{name}: session total {total} != {SEEDS[name]}")+ return out++ with ThreadPoolExecutor(max_workers=6) as pool:+ problems = [x for f in [pool.submit(hammer, n) for n in NAMES * 2] for x in f.result(timeout=240)]+ assert not problems, "interleaved profile requests crossed:\n " + "\n ".join(problems[:30])+ leaks = [f"{p.name}: {path.relative_to(p.home)} carries {leak}"+ for p in sb.profiles.values() for path in p.home.rglob("*")+ if path.is_file() and not (p.name == "default" and path.relative_to(p.home).parts[:1] == ("profiles",))+ for leak in _foreign(sb, p.name, path.read_bytes().decode("utf-8", "replace"))]+ assert not leaks, "profile files carry another profile's canaries:\n " + "\n ".join(leaks)+++def _flatten(d: Any, prefix: str = "") -> dict[str, Any]:+ if not isinstance(d, dict) or not d:+ return {prefix: d}+ out: dict[str, Any] = {}+ for k, v in d.items():+ out.update(_flatten(v, f"{prefix}.{k}" if prefix else str(k)))+ return out+++def test_config_page_save_changes_only_the_edited_field(fleet) -> None:+ sb, d = fleet+ p = sb.profiles["alpha"]+ path: Path = p.home / "config.yaml"+ cfg = p.config()+ cfg["zz_future_block"] = {"nested": [1, {"deep": "x"}], "flag": True} # a newer version's setting+ cfg["zz_cleared"] = None+ cfg.setdefault("display", {})["zz_future_leaf"] = "keep-me"+ cfg["display"]["skin"] = None # explicit null on a key that HAS a default+ cfg["timezone"] = None+ path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+ before = _flatten(yaml.safe_load(path.read_text(encoding="utf-8")))++ record = d.ok("GET", "/api/config", "alpha") # defaulted record, what the Config page renders+ assert record["zz_future_block"] == cfg["zz_future_block"] and "zz_cleared" in record, record.keys()+ record.setdefault("agent", {})["max_turns"] = 77+ d.ok("PUT", "/api/config", "alpha", json={"config": record})++ after = _flatten(yaml.safe_load(path.read_text(encoding="utf-8")))+ changed = {k for k in before.keys() | after.keys() if before.get(k, "<absent>") != after.get(k, "<absent>")}+ assert changed == {"agent.max_turns"}, (+ f"a one-field Config-page save changed {sorted(changed)}:\n"+ + "\n".join(f" {k}: {before.get(k, '<absent>')!r} -> {after.get(k, '<absent>')!r}" for k in sorted(changed)))+ assert after["agent.max_turns"] == 77+ again = d.ok("GET", "/api/config", "alpha")+ assert again["zz_future_block"] == cfg["zz_future_block"] and again["display"]["skin"] is Nonediff --git a/tests/e2e/core/dashboard/test_dashboard_pty.py b/tests/e2e/core/dashboard/test_dashboard_pty.pynew file mode 100644index 00000000000..17cf174bfb7--- /dev/null+++ b/tests/e2e/core/dashboard/test_dashboard_pty.py@@ -0,0 +1,285 @@+"""Dashboard embedded chat: the ``/api/pty`` WebSocket drives a REAL ``hermes --tui`` end to end.++Issue class: the dashboard Chat tab talking to the wrong profile, or losing the conversation on a+reconnect. Every cell runs the real ``hermes dashboard``, which+spawns the real Ink TUI (``ui-tui/dist/entry.js``) and its ``tui_gateway`` under a real PTY; the+client is what the browser's xterm does (raw PTY bytes, the ``\\x1b[RESIZE:c;r]`` control frame, the+SPA's ``?attach=`` keep-alive token, ``?profile=`` and a per-(profile) ``?channel=``). Each profile+has its own fake provider that only accepts that profile's key and echoes the prompt's canary, so+every recorded request proves which profile's TUI sent it, and state.db proves where it landed.++Contract under test (``hermes_cli/web_routers/chat_ws.py::pty_ws`` + ``hermes_cli/pty_session.py``):+ * ``?profile=<name>`` scopes the whole chat to that profile (HERMES_HOME=<profile dir>);+ * with ``?attach=T`` the PTY outlives the socket; reconnecting with the same T + profile replays+ the buffer and forces a redraw of the SAME TUI/session;+ * the registry key includes the profile, so the same T under another profile gets a fresh TUI.++Not a cell: "dashboard shutdown leaves no TUI behind". It holds, but it cannot be made red from the+dashboard side: with ``PtySessionRegistry.close_all`` disabled (and even with the child ignoring+SIGHUP) the TUI still exits when the dying dashboard's PTY master closes (kernel hangup / EIO) and+its ``tui_gateway`` exits on stdin EOF. The fixture still waits for, reports and reaps any+descendant that outlives the dashboard, so a leak cannot poison later tests.+"""++from __future__ import annotations++import os+import re+import secrets+import shutil+import subprocess+import sys+from pathlib import Path+from typing import Any++import pytest++from tests.e2e.core.terminal._vt import Screen+from tests.fakes.fake_llm_provider import Text++from . import _helpers as H+from ._pty_helpers import ProcessLedger, WsTerm, canon, poll++pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="POSIX PTY dashboard")++_CANARY = re.compile(r"canary-[0-9a-f]{12}")+ROWS, COLS = 40, 120+TURN_TIMEOUT = 90.0+++def _require_tui() -> None:+ if shutil.which("node") and (H.REPO_ROOT / "ui-tui" / "dist" / "entry.js").is_file():+ return+ if os.environ.get("HERMES_E2E_REQUIRE_TUI") == "1":+ pytest.fail("ui-tui/dist/entry.js or node missing but HERMES_E2E_REQUIRE_TUI=1")+ pytest.skip("Ink TUI not built (cd ui-tui && npm run build) or node missing")+++def _text_of(content: Any) -> str:+ if isinstance(content, list):+ return " ".join(str(part.get("text", "")) for part in content if isinstance(part, dict))+ return str(content or "")+++def _last_user(body: dict) -> str:+ users = [m for m in body.get("messages", []) if m.get("role") == "user"]+ return _text_of(users[-1].get("content")) if users else ""+++def _echo_responder(p: H.Profile):+ """Main turns answer ``reply-from-<profile>-<tag> ack-<canary of the prompt>``."""+ def respond(record: dict) -> Text:+ m = _CANARY.search(_last_user(record["body"]))+ return Text(f"reply-from-{p.name}-{p.tag} ack-{m.group(0) if m else 'none'}")+ return respond+++def _reply(p: H.Profile, canary: str) -> str:+ return f"reply-from-{p.name}-{p.tag} ack-{canary}"+++def _main_requests(p: H.Profile) -> list[dict]:+ assert p.srv is not None+ return [r for r in list(p.srv.requests) if r["kind"] == "main"]+++def _user_rows(p: H.Profile, needle: str) -> list[tuple[str, str]]:+ if not p.db.exists():+ return []+ return [(str(s), str(c)) for s, c in H.db_rows(+ p.db, "SELECT session_id, COALESCE(content, '') FROM messages WHERE role = 'user' AND content LIKE ?",+ (f"%{needle}%",))]+++def _user_sessions(p: H.Profile) -> set[str]:+ if not p.db.exists():+ return set()+ return {str(s) for (s,) in H.db_rows(p.db, "SELECT DISTINCT session_id FROM messages WHERE role = 'user'")}+++class Chat:+ """The dashboard + one tag-scoped attach token, as a single browser tab would hold them."""++ def __init__(self, dash: H.Dashboard, ledger: ProcessLedger) -> None:+ self.dash = dash+ self.ledger = ledger+ self.attach = f"e2e-attach-{secrets.token_hex(6)}"+ self.terms: list[WsTerm] = []++ def open(self, profile: str) -> WsTerm:+ url = self.dash.ws_url("/api/pty", token=self.dash.token, profile=profile, attach=self.attach,+ channel=f"e2e-{profile}-{self.attach}")+ term = WsTerm(url, rows=ROWS, cols=COLS)+ self.terms.append(term)+ return term++ def wait_composer(self, term: WsTerm) -> None:+ """The TUI painted its composer prompt and session banner, and its status bar no longer+ reports a boot phase ("summoning hermes…", "starting agent…"). Profile-agnostic on purpose:+ which profile answered is judged by the provider/state.db assertions, not by this wait."""+ def ready() -> bool:+ s = term.text()+ return term.closed or ("❯" in s and "Session:" in s+ and "startingagent" not in s and "summoninghermes" not in s)+ try:+ poll(ready, 120, "the TUI composer to be ready")+ assert not term.closed, f"/api/pty closed (code={term.close_code}) during TUI startup"+ except AssertionError as exc:+ raise AssertionError(f"{exc}\n--- screen ---\n{term.dump()}") from None+ term.wait_quiet(0.5)+ self.ledger.snapshot()++ def turn(self, term: WsTerm, p: H.Profile, canary: str, n_main_before: int) -> dict:+ """Submit a prompt carrying ``canary``; returns the provider record of that turn. Waits for+ the canary to reach ANY sandbox provider, so a mis-scoped chat fails fast and by name."""+ term.submit(f"please echo {canary}")++ def carriers() -> list[str]:+ return [q.name for q in self.dash.sb.profiles.values()+ if any(canary in _last_user(r["body"]) for r in _main_requests(q))]+ poll(lambda: carriers() or term.closed, TURN_TIMEOUT, f"a provider to receive the turn carrying {canary}")+ rec = next((r for r in _main_requests(p)[n_main_before:] if canary in _last_user(r["body"])), None)+ assert rec is not None, (+ f"the profile={p.name} turn carrying {canary} reached provider(s) {carriers()} instead of "+ f"{p.name}'s\n--- screen ---\n{term.dump()}")+ term.wait_for(_reply(p, canary), timeout=TURN_TIMEOUT)+ poll(lambda: _user_rows(p, canary), TURN_TIMEOUT, f"{canary} persisted in {p.name}'s state.db")+ self.ledger.snapshot()+ return rec+++def _private_tui(tmp_path: Path) -> Path:+ """A private, syntax-checked copy of the prebuilt bundle, handed to the dashboard as+ ``HERMES_TUI_DIR`` (the prebuilt-install path of ``_make_tui_argv``). On a source checkout every+ PTY spawn otherwise re-runs ``npm run build``, rewriting ``ui-tui/dist/entry.js`` in place, and a+ TUI starting during a concurrent build (another worker, another dashboard) crashes on the+ truncated file (#121286). The bundle is self-contained (node builtins only)."""+ src = H.REPO_ROOT / "ui-tui" / "dist" / "entry.js"+ dst = tmp_path / "tui" / "dist" / "entry.js"+ dst.parent.mkdir(parents=True)+ # Same module type as ui-tui/package.json, so older Node versions without ESM syntax detection+ # load the copy exactly like the original.+ (dst.parent.parent / "package.json").write_text('{"type": "module"}\n', encoding="utf-8")+ def copied_intact() -> bool:+ shutil.copyfile(src, dst)+ return subprocess.run([shutil.which("node") or "node", "--check", str(dst)], capture_output=True,+ timeout=60, stdin=subprocess.DEVNULL).returncode == 0+ poll(copied_intact, 180, "an intact copy of ui-tui/dist/entry.js (a concurrent build may be writing it)",+ interval=1.0)+ return dst.parent.parent+++def dash_env(tmp_path: Path):+ _require_tui()+ tui_dir = _private_tui(tmp_path)+ sb = H.make_sandbox(tmp_path, ("default", "alpha", "beta"), responder=_echo_responder)+ dash = H.Dashboard(sb, tmp_path / "dashboard.log", extra_env={"HERMES_TUI_DIR": str(tui_dir)})+ ledger = ProcessLedger(dash.proc.pid)+ try:+ yield sb, dash, ledger+ finally:+ try:+ dash.close()+ finally:+ try:+ poll(lambda: not ledger.survivors(), 30, "dashboard descendants to exit")+ except AssertionError:+ pass+ left = ledger.kill_survivors()+ if left:+ print("teardown killed dashboard leftovers:\n " + "\n ".join(left), file=sys.stderr)+ sb.stop()+++def _assert_labelled(term: WsTerm, profile: str) -> None:+ assert canon(f"{profile} ❯") in term.text(), (+ f"the TUI composer is not labelled with profile {profile!r}\n--- screen ---\n{term.dump()}")+++def _first_turn(chat: Chat, alpha: H.Profile, default: H.Profile, canary: str) -> WsTerm:+ """Scenario 1: one chat turn through /api/pty lands on alpha's provider, screen and state.db."""+ term = chat.open("alpha")+ chat.wait_composer(term)+ rec = chat.turn(term, alpha, canary, n_main_before=0)+ assert rec["auth"] == f"Bearer {alpha.provider_key}", f"turn authenticated with {rec['auth']!r}, not alpha's key"+ assert rec["body"].get("model") == alpha.model, f"turn used model {rec['body'].get('model')!r}, not alpha's"+ rows = _user_rows(alpha, canary)+ assert len({s for s, _ in rows}) == 1, f"alpha's state.db has the canary in {rows}"+ assert not _main_requests(default), (+ f"the DEFAULT profile's provider served a profile=alpha chat: "+ f"{[_last_user(r['body'])[:80] for r in _main_requests(default)]}")+ assert not _user_rows(default, canary), "profile=alpha's prompt was persisted in the DEFAULT profile's state.db"+ _assert_labelled(term, "alpha")+ return term+++def _replayed_screen(term: WsTerm) -> str:+ """Render ONLY the first binary frame of a reattached socket: the server sends the ring-buffer+ snapshot as one frame before it asks the TUI for a redraw, so this is the replay on its own."""+ poll(lambda: term.first_frames or term.closed, 30, "the first frame of the reattached socket")+ assert term.first_frames, f"reattached socket closed (code={term.close_code}) before any output"+ screen = Screen(ROWS, COLS)+ screen.feed(term.first_frames[0])+ return canon("".join(screen.transcript() + screen.display()))+++def _reconnect_turn(chat: Chat, first: WsTerm, alpha: H.Profile, canary1: str, canary2: str) -> WsTerm:+ """Scenario 2: a client-side close + reconnect with the same attach token resumes the SAME TUI."""+ session_id = _user_rows(alpha, canary1)[0][0]+ first.close()+ assert first.closed, "client close did not complete"+ term = chat.open("alpha")+ assert canon(_reply(alpha, canary1)) in _replayed_screen(term), (+ "reattach did not replay the buffered PTY output (the first frame lacks the earlier reply): "+ f"{term.first_frames[0][:300]!r}")+ # ...and the forced redraw leaves the live screen showing the earlier turn and a usable composer.+ term.wait_for(_reply(alpha, canary1), timeout=60)+ chat.wait_composer(term)+ assert term.close_code is None, f"reattached socket closed with {term.close_code}"+ n_before = len(_main_requests(alpha))+ rec = chat.turn(term, alpha, canary2, n_main_before=n_before)+ history = " ".join(_text_of(m.get("content")) for m in rec["body"].get("messages", []))+ assert canary1 in history and _reply(alpha, canary1) in history, (+ "the post-reconnect turn did not carry the first turn in its history (a fresh TUI/session "+ f"answered): {history[-600:]!r}")+ sid2 = {s for s, _ in _user_rows(alpha, canary2)}+ assert sid2 == {session_id}, f"post-reconnect prompt landed in session(s) {sid2}, not the original {session_id}"+ assert _user_sessions(alpha) == {session_id}, (+ f"reconnect created a second session in alpha's state.db: {_user_sessions(alpha)}")+ return term+++def _other_profile_same_token(chat: Chat, alpha: H.Profile, beta: H.Profile,+ alpha_canaries: tuple[str, ...], canary3: str) -> None:+ """Scenario 3: the same attach token under profile=beta must not reattach alpha's PTY."""+ alpha_main = len(_main_requests(alpha))+ term = chat.open("beta")+ chat.wait_composer(term)+ screen = term.text()+ leaked = [c for c in (*alpha_canaries, f"reply-from-alpha-{alpha.tag}") if canon(c) in screen]+ assert not leaked, (f"profile=beta with alpha's attach token reattached alpha's TUI (showed {leaked})"+ f"\n--- screen ---\n{term.dump()}")+ rec = chat.turn(term, beta, canary3, n_main_before=0)+ assert rec["auth"] == f"Bearer {beta.provider_key}", f"beta's turn authenticated with {rec['auth']!r}"+ assert len(_main_requests(alpha)) == alpha_main, "beta's prompt reached alpha's provider"+ assert not _user_rows(alpha, canary3), "beta's prompt was persisted in alpha's state.db"+ assert not any(c in _last_user(r["body"]) for r in _main_requests(beta) for c in alpha_canaries), (+ "alpha's prompts reached beta's provider")+ _assert_labelled(term, "beta")+++def test_pty_chat_turn_reconnect_and_profile_scoped_keepalive(dash_env) -> None:+ sb, dash, ledger = dash_env+ alpha, beta, default = sb.profiles["alpha"], sb.profiles["beta"], sb.profiles["default"]+ chat = Chat(dash, ledger)+ c1, c2, c3 = (f"canary-{secrets.token_hex(6)}" for _ in range(3))++ term = _first_turn(chat, alpha, default, c1)+ _reconnect_turn(chat, term, alpha, c1, c2)+ _other_profile_same_token(chat, alpha, beta, (c1, c2), c3)++ assert not _main_requests(default), "the DEFAULT profile's provider saw traffic from profile-scoped chats"+ assert not _user_rows(default, "canary-"), "a profile-scoped prompt landed in the DEFAULT profile's state.db"+ assert dash.proc.poll() is None, f"dashboard died:\n{dash.log_tail()}"+diff --git a/tests/e2e/core/dashboard/test_dashboard_sessions.py b/tests/e2e/core/dashboard/test_dashboard_sessions.pynew file mode 100644index 00000000000..1434ba8eff5--- /dev/null+++ b/tests/e2e/core/dashboard/test_dashboard_sessions.py@@ -0,0 +1,163 @@+"""Dashboard session browser against a live ``state.db`` while another process writes to it.++Users hit this as "the Sessions page 500s / shows 'database is locked' while a chat is running" or+"the session count jumps backwards / double-counts" (the dashboard reads the same SQLite file the+agent, gateway and cron write). Harness: the real ``hermes dashboard`` process and a real writer+process (``hermes_state.SessionDB``, the agent's own persistence layer) appending sessions and+messages as fast as it can. Readers hammer the list, stats, detail and messages routes in parallel.++Invariants while the writer runs: every read is a 200 (never a lock/busy error), the list total+never goes backwards across sequential reads and never exceeds what the writer has committed, a+session detail's ``message_count`` equals the messages the messages route returns for it. After the+writer stops, the API total equals the raw row count in SQLite.+"""++from __future__ import annotations++import subprocess+import sys+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from typing import Callable++import pytest++from . import _helpers as H++pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="POSIX dashboard process")++SEEDED = 40+WRITE_SECONDS = 8.0++# Writes sessions + messages in the agent's own persistence layer; prints the committed count after+# every session so the harness knows an upper bound at any instant.+_WRITER = r"""+import sys, time+from hermes_state import SessionDB+deadline = time.monotonic() + float(sys.argv[1])+db = SessionDB()+n = 0+while time.monotonic() < deadline:+ sid = f"live-{n:05d}"+ db.create_session(sid, source="cli", model="writer")+ for j in range(3):+ db.append_message(sid, "user" if j % 2 == 0 else "assistant", f"{sid} message {j}")+ n += 1+ print(n, flush=True)+db.close()+print("DONE", n, flush=True)+"""+++class Writer:+ def __init__(self, sb: H.Sandbox, p: H.Profile) -> None:+ self.proc = subprocess.Popen(+ [sys.executable, "-c", _WRITER, str(WRITE_SECONDS)], env=sb.env({"HERMES_HOME": str(p.home)}),+ cwd=str(sb.home), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ text=True, start_new_session=True)+ self.committed = 0+ self.done: int | None = None+ threading.Thread(target=self._pump, daemon=True, name="dash-writer").start()++ def _pump(self) -> None:+ assert self.proc.stdout is not None+ for line in self.proc.stdout:+ parts = line.split()+ if parts[:1] == ["DONE"]:+ self.done = int(parts[1])+ elif parts and parts[0].isdigit():+ self.committed = int(parts[0])++[email protected](scope="module")+def env(tmp_path_factory: pytest.TempPathFactory):+ sb = H.make_sandbox(tmp_path_factory.mktemp("dash-sessions"))+ p = sb.profiles["default"]+ H.seed_sessions(sb, p, "seed", SEEDED)+ d = H.Dashboard(sb, sb.root / "dashboard.log")+ try:+ yield sb, p, d+ finally:+ d.close()+ sb.stop()+++def _read_round(d: H.Dashboard, committed: Callable[[], int]) -> list[str]:+ """One list read + detail/messages consistency for its newest rows. The upper bound is read+ AFTER the response: everything the writer reported by then, plus the one session in flight."""+ problems: list[str] = []+ r = d.request("GET", "/api/sessions", params={"limit": 100, "order": "recent"})+ upper_bound = committed() + 1+ if r.status_code != 200:+ return [f"GET /api/sessions -> {r.status_code} {r.text[:200]}"]+ body = r.json()+ total = body["total"]+ if not SEEDED <= total <= SEEDED + upper_bound:+ problems.append(f"total {total} outside [{SEEDED}, {SEEDED + upper_bound}] (writer committed {upper_bound})")+ for row in body["sessions"][:2]:+ sid = row["id"]+ det = d.request("GET", f"/api/sessions/{sid}")+ msgs = d.request("GET", f"/api/sessions/{sid}/messages")+ if det.status_code != 200 or msgs.status_code != 200:+ problems.append(f"{sid}: detail {det.status_code} / messages {msgs.status_code} {msgs.text[:200]}")+ continue+ listed = msgs.json().get("messages", [])+ # The writer appends to at most the newest session while we read: the detail may lag or+ # lead the messages read by the rows appended in between, never by more.+ if abs(det.json()["message_count"] - len(listed)) > 3:+ problems.append(f"{sid}: detail message_count {det.json()['message_count']} vs {len(listed)} messages")+ stats = d.request("GET", "/api/sessions/stats")+ if stats.status_code != 200:+ problems.append(f"GET /api/sessions/stats -> {stats.status_code} {stats.text[:200]}")+ return problems + [f"@total={total}"]+++def test_session_routes_stay_consistent_under_a_concurrent_writer(env) -> None:+ sb, p, d = env+ w = Writer(sb, p)+ H.poll(lambda: w.committed > 0, 60, "the writer's first commit")+ totals: list[int] = []+ problems: list[str] = []++ def reader() -> list[str]:+ out: list[str] = []+ while w.done is None and w.proc.poll() is None:+ got = _read_round(d, lambda: w.committed)+ out += [g for g in got if not g.startswith("@")]+ totals.extend(int(g[7:]) for g in got if g.startswith("@total="))+ return out++ # Sequential totals must be monotonic: one dedicated reader keeps its own ordered series.+ series: list[int] = []++ def ordered() -> list[str]:+ out: list[str] = []+ while w.done is None and w.proc.poll() is None:+ r = d.request("GET", "/api/sessions", params={"limit": 1})+ if r.status_code != 200:+ out.append(f"ordered read -> {r.status_code} {r.text[:200]}")+ continue+ series.append(r.json()["total"])+ return out++ with ThreadPoolExecutor(max_workers=5) as pool:+ futs = [pool.submit(reader) for _ in range(4)] + [pool.submit(ordered)]+ for f in futs:+ problems += f.result(timeout=WRITE_SECONDS + 120)+ w.proc.wait(timeout=60)+ err = w.proc.stderr.read() if w.proc.stderr else ""+ assert w.proc.returncode == 0 and w.done, f"writer failed rc={w.proc.returncode}: {err[-2000:]}"+ assert w.done >= 20, f"writer committed only {w.done} sessions: the contention window never opened"+ assert len(totals) >= 10 and len(series) >= 10, f"too few reads overlapped the writer ({len(totals)}, {len(series)})"+ assert not problems, f"{len(problems)} inconsistent read(s) while writing:\n " + "\n ".join(dict.fromkeys(problems[:30]))+ backwards = [(a, b) for a, b in zip(series, series[1:]) if b < a]+ assert not backwards, f"session total went backwards between sequential reads: {backwards[:5]}"++ raw = H.db_rows(p.db, "SELECT COUNT(*) FROM sessions WHERE parent_session_id IS NULL")[0][0]+ final = d.ok("GET", "/api/sessions", params={"limit": 1})["total"]+ assert final == raw == SEEDED + w.done, f"api total {final}, sqlite {raw}, expected {SEEDED + w.done}"+ newest = d.ok("GET", f"/api/sessions/live-{w.done - 1:05d}/messages")["messages"]+ assert [m["content"] for m in newest] == [f"live-{w.done - 1:05d} message {j}" for j in range(3)]+ log = d.log_tail(200_000).lower()+ assert "database is locked" not in log and "traceback" not in log, d.log_tail()