Skip to content

The agent that grows with you

test: native Windows E2E suite on real Hermes processes (e2e-windows job)

teknium18c44895e7b66
diff --git a/.github/workflows/tests-os.yml b/.github/workflows/tests-os.yml
index aa385c02fed..ed4b323b161 100644
--- a/.github/workflows/tests-os.yml
+++ b/.github/workflows/tests-os.yml
@@ -179,3 +179,92 @@ jobs:
OPENROUTER_API_KEY: ""
OPENAI_API_KEY: ""
NOUS_API_KEY: ""
+
+ e2e-windows:
+ # Real Hermes processes on a real Windows host (tests/e2e/core/windows): hermes.exe,
+ # `hermes serve`, `hermes gateway run/stop`, the tui_gateway stdio process, cron script
+ # jobs, the terminal tool's Git Bash / PowerShell / cmd children and a ConPTY console,
+ # all against the loopback fake provider (tests/fakes/fake_llm_provider.py). Separate
+ # from os-tests above: those are unit-level windows_only tests, these spawn process
+ # trees per test. Every file there is also marked `integration`, so os-tests'
+ # `-m "windows_only and not integration"` never runs them a second time.
+ #
+ # One pytest process per FILE, in parallel (same model as the Linux `e2e` job): the
+ # files spawn their own trees and must not share interpreter state. No retries: a
+ # Windows race that passes on retry is still a race. Tracked Windows bugs are strict
+ # xfails (per-file KNOWN tables), so a fix turns this job red until the entry goes.
+ name: Windows E2E (real processes)
+ runs-on: windows-latest
+ timeout-minutes: 25
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
+ with:
+ version: "0.9.28"
+ enable-cache: true
+ cache-dependency-glob: |
+ pyproject.toml
+ uv.lock
+
+ - name: Set up Python 3.11
+ uses: ./.github/actions/retry
+ with:
+ command: uv python install 3.11
+
+ - name: Install dependencies
+ # Same extras as os-tests: serve needs the web stack, the gateway the messaging
+ # imports, and the ConPTY case pywinpty (a core dependency on win32).
+ uses: ./.github/actions/retry
+ with:
+ command: uv sync --locked --python 3.11 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web
+
+ - name: Minimize uv cache
+ run: uv cache prune --ci
+
+ - name: Run Windows E2E suite
+ shell: bash
+ run: |
+ set -uo pipefail
+ logs="${RUNNER_TEMP}/e2e-windows"
+ mkdir -p "$logs"
+ files=$(find tests/e2e/core/windows -name 'test_*.py' | sort)
+ if [ -z "$files" ]; then
+ echo "::error::no test files under tests/e2e/core/windows"
+ exit 1
+ fi
+ pids=()
+ names=()
+ start=$SECONDS
+ for f in $files; do
+ # `-m windows_only` replaces pyproject's `not integration` addopts selector.
+ timeout 900 .venv/Scripts/python.exe -m pytest "$f" -m windows_only \
+ -p no:cacheprovider -v --tb=short -rA > "$logs/$(basename "$f" .py).log" 2>&1 &
+ pids+=($!)
+ names+=("$f")
+ done
+ fail=0
+ for i in "${!pids[@]}"; do
+ rc=0
+ wait "${pids[$i]}" || rc=$?
+ f="${names[$i]}"
+ echo "::group::$f (rc=$rc)"
+ cat "$logs/$(basename "$f" .py).log"
+ echo "::endgroup::"
+ if [ "$rc" -eq 5 ]; then
+ echo "::error::$f selected zero tests (marker renamed or selection broken)"
+ fail=1
+ elif [ "$rc" -ne 0 ]; then
+ echo "::error::$f failed (rc=$rc)"
+ grep -E '^(FAILED|ERROR) ' "$logs/$(basename "$f" .py).log" || true
+ fail=1
+ fi
+ done
+ echo "Windows E2E wall: $((SECONDS - start)) s"
+ exit "$fail"
+ env:
+ OPENROUTER_API_KEY: ""
+ OPENAI_API_KEY: ""
+ NOUS_API_KEY: ""
diff --git a/tests/e2e/core/windows/__init__.py b/tests/e2e/core/windows/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/e2e/core/windows/_helpers.py b/tests/e2e/core/windows/_helpers.py
new file mode 100644
index 00000000000..24e1401bc81
--- /dev/null
+++ b/tests/e2e/core/windows/_helpers.py
@@ -0,0 +1,299 @@
+"""Shared harness for the native-Windows end-to-end suite.
+
+Every test drives REAL Hermes processes (``hermes.exe`` / ``python -m
+hermes_cli.main``) on a real Windows host against the recording loopback
+provider (``tests/fakes/fake_llm_provider.py``). Nothing in Hermes is mocked;
+verdicts come from what reached the provider wire, what landed in ``state.db``
+/ on disk, and the live process table (psutil).
+
+Each test gets a fresh fake user profile under ``tmp_path``: ``USERPROFILE`` /
+``HOME`` / ``LOCALAPPDATA`` / ``APPDATA`` all point inside it and
+``HERMES_HOME`` is ``<profile>/.hermes``, so no child can read or write the
+runner's real Hermes state.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+import subprocess
+import sys
+import time
+import uuid
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Iterable
+
+import yaml
+
+from tests.fakes.fake_llm_provider import FakeLLMServer, write_hermes_home
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+TURN_TIMEOUT = 180.0
+
+# Windows needs these for a child to start at all (CreateProcess, Winsock, temp dirs,
+# Program Files lookups the Git Bash resolver uses). Credentials never pass.
+_PASSTHROUGH_ENV = frozenset({
+ "PATH", "PATHEXT", "SYSTEMROOT", "SystemRoot", "SYSTEMDRIVE", "SystemDrive", "COMSPEC",
+ "WINDIR", "TEMP", "TMP", "OS", "PROCESSOR_ARCHITECTURE", "NUMBER_OF_PROCESSORS",
+ "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "ProgramData", "CommonProgramFiles",
+ "CommonProgramFiles(x86)", "CommonProgramW6432", "USERNAME", "USERDOMAIN", "COMPUTERNAME",
+ "PSModulePath", "LANG", "TZ",
+})
+_SECRET_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY")
+
+
+@dataclass
+class WinHome:
+ """One hermetic fake Windows user profile with a Hermes home inside it."""
+
+ root: Path
+ profile: Path
+ hermes_home: Path
+ project: Path
+ extra_env: dict[str, str] = field(default_factory=dict)
+
+ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:
+ env = {
+ k: v for k, v in os.environ.items()
+ if k in _PASSTHROUGH_ENV and not k.upper().endswith(_SECRET_SUFFIXES)
+ }
+ local = self.profile / "AppData" / "Local"
+ roaming = self.profile / "AppData" / "Roaming"
+ local.mkdir(parents=True, exist_ok=True)
+ roaming.mkdir(parents=True, exist_ok=True)
+ env.update({
+ "USERPROFILE": str(self.profile),
+ "HOME": str(self.profile),
+ "LOCALAPPDATA": str(local),
+ "APPDATA": str(roaming),
+ "HERMES_HOME": str(self.hermes_home),
+ "PYTHONPATH": str(REPO_ROOT),
+ "PYTHONUNBUFFERED": "1",
+ "NO_COLOR": "1",
+ # The child's state.db lives under tmp_path; under a pytest ancestor the live-DB
+ # guard would refuse it. Documented child-process escape hatch (tests/conftest.py).
+ "HERMES_STATE_DB_GUARD_BYPASS": "1",
+ })
+ env.update(self.extra_env)
+ env.update(extra or {})
+ return env
+
+ def update_config(self, mutate: Callable[[dict], None]) -> None:
+ path = self.hermes_home / "config.yaml"
+ cfg = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+ mutate(cfg)
+ path.write_text(yaml.safe_dump(cfg, sort_keys=False, allow_unicode=True), encoding="utf-8")
+
+ @property
+ def db_path(self) -> Path:
+ return self.hermes_home / "state.db"
+
+
+def make_home(tmp_path: Path, base_url: str, *, extra_config: str = "") -> WinHome:
+ root = tmp_path
+ profile = root / "Users" / "e2e"
+ hermes_home = profile / ".hermes"
+ project = root / "project"
+ project.mkdir(parents=True, exist_ok=True)
+ write_hermes_home(hermes_home, base_url, extra_config=extra_config)
+ home = WinHome(root=root, profile=profile, hermes_home=hermes_home, project=project)
+
+ def _hermetic(cfg: dict) -> None:
+ cfg["updates"] = {"check": False} # offline: no GitHub round trip / git lazy fetch
+ cfg.setdefault("display", {})["compact"] = True
+
+ home.update_config(_hermetic)
+ return home
+
+
+def hermes_argv(*args: str) -> list[str]:
+ return [sys.executable, "-m", "hermes_cli.main", *args]
+
+
+def hermes_exe() -> Path:
+ """The console-script shim users actually launch (``<venv>\\Scripts\\hermes.exe``)."""
+ exe = Path(sys.executable).with_name("hermes.exe")
+ assert exe.is_file(), f"hermes.exe console script missing next to {sys.executable}"
+ return exe
+
+
+@dataclass
+class Run:
+ returncode: int
+ stdout: str
+ stderr: str
+
+ def tail(self, n: int = 3000) -> str:
+ return f"rc={self.returncode}\n--stdout--\n{self.stdout[-n:]}\n--stderr--\n{self.stderr[-n:]}"
+
+
+def run(argv: list[str], home: WinHome, *, cwd: Path | None = None, timeout: float = TURN_TIMEOUT,
+ env_extra: dict[str, str] | None = None, stdin: bytes | None = None) -> Run:
+ proc = subprocess.run(
+ argv, cwd=cwd or home.project, env=home.env(env_extra), capture_output=True,
+ input=stdin, stdin=None if stdin is not None else subprocess.DEVNULL, timeout=timeout,
+ )
+ return Run(proc.returncode, _decode(proc.stdout), _decode(proc.stderr))
+
+
+def hermes(home: WinHome, *args: str, **kw: Any) -> Run:
+ return run(hermes_argv(*args), home, **kw)
+
+
+def _decode(raw: bytes) -> str:
+ try:
+ return raw.decode("utf-8")
+ except UnicodeDecodeError:
+ return raw.decode("mbcs" if sys.platform == "win32" else "latin-1", errors="replace")
+
+
+# Provider wire ---------------------------------------------------------------
+
+
+def text_of(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return "\n".join(p.get("text", "") for p in content if isinstance(p, dict))
+ return ""
+
+
+def system_prompt(body: dict[str, Any]) -> str:
+ return "\n".join(text_of(m.get("content")) for m in body.get("messages") or [] if m.get("role") == "system")
+
+
+def last_user(body: dict[str, Any]) -> str:
+ users = [text_of(m.get("content")) for m in body.get("messages") or [] if m.get("role") == "user"]
+ return users[-1] if users else ""
+
+
+def tool_results(srv: FakeLLMServer) -> list[str]:
+ """Tool-result messages Hermes sent back to the model, in order, deduped across requests."""
+ seen: dict[str, str] = {}
+ for body in srv.main_requests():
+ for m in body.get("messages") or []:
+ if m.get("role") == "tool":
+ seen.setdefault(m.get("tool_call_id") or str(len(seen)), text_of(m.get("content")))
+ return list(seen.values())
+
+
+def parse_tool_json(result: str) -> dict[str, Any]:
+ """The terminal tool's JSON payload (subdirectory hints may be appended after it)."""
+ start = result.find("{")
+ assert start >= 0, f"tool result carries no JSON payload: {result[:500]!r}"
+ obj, _end = json.JSONDecoder().raw_decode(result[start:])
+ return obj
+
+
+# state.db --------------------------------------------------------------------
+
+
+def db_rows(home: WinHome, sql: str, params: Iterable[Any] = ()) -> list[sqlite3.Row]:
+ assert home.db_path.exists(), f"no state.db at {home.db_path}"
+ conn = sqlite3.connect(f"file:{home.db_path.as_posix()}?mode=ro", uri=True, timeout=30)
+ conn.row_factory = sqlite3.Row
+ try:
+ return list(conn.execute(sql, tuple(params)))
+ finally:
+ conn.close()
+
+
+def persisted_messages(home: WinHome) -> list[sqlite3.Row]:
+ return db_rows(home, "SELECT session_id, role, content FROM messages ORDER BY id")
+
+
+# Processes -------------------------------------------------------------------
+
+
+def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: float = 0.1) -> Any:
+ deadline = time.monotonic() + timeout
+ while True:
+ value = pred()
+ if value:
+ return value
+ if time.monotonic() >= deadline:
+ raise AssertionError(f"timed out after {timeout}s waiting for {what}")
+ time.sleep(interval)
+
+
+def process_tree(pid: int) -> list[Any]:
+ """psutil handles for ``pid`` and every live descendant (identity-checked by psutil)."""
+ import psutil
+
+ try:
+ root = psutil.Process(pid)
+ return [root, *root.children(recursive=True)]
+ except psutil.NoSuchProcess:
+ return []
+
+
+def survivors(procs: Iterable[Any], timeout: float) -> list[str]:
+ """Wait until every handle is gone; describe the ones still running at the deadline."""
+ import psutil
+
+ procs = list(procs)
+ _gone, alive = psutil.wait_procs(procs, timeout=timeout)
+ out = []
+ for p in alive:
+ try:
+ out.append(f"{p.pid} {' '.join(p.cmdline())[:200]}")
+ except psutil.Error:
+ continue
+ return out
+
+
+def kill_tree(procs: Iterable[Any]) -> None:
+ """Test cleanup only: hard-kill whatever this test spawned that is still alive."""
+ import psutil
+
+ for p in procs:
+ try:
+ p.kill()
+ except psutil.Error:
+ pass
+
+
+def taskkill_tree(pid: int) -> subprocess.CompletedProcess:
+ """The Desktop's backend quit path on Windows (electron/backend-child.ts): taskkill /T /F."""
+ return subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, timeout=60)
+
+
+def nonce(prefix: str) -> str:
+ return f"{prefix}-{uuid.uuid4().hex[:10]}"
+
+
+# Known bugs ------------------------------------------------------------------
+
+
+class KnownBugSymptom(Exception):
+ """Raised ONLY at the assertion that pins a tracked bug's symptom. Not an AssertionError:
+ a KNOWN entry's strict xfail matches just this, so a harness failure or any other broken
+ invariant in the same test still fails loudly instead of hiding behind the xfail."""
+
+
+def expect(ok: bool, message: str) -> None:
+ if not ok:
+ raise KnownBugSymptom(message)
+
+
+def known_marks(name: str, table: dict[str, str]) -> list[Any]:
+ """Marks for a test named in a file's ``KNOWN`` table: strict xfail on the symptom only.
+ Strict, so the test turns red the moment the bug is fixed and the entry must go."""
+ import pytest
+
+ if name not in table:
+ return []
+ return [pytest.mark.xfail(strict=True, raises=KnownBugSymptom, reason=table[name])]
+
+
+def known(name: str, table: dict[str, str]) -> Callable[[Callable], Callable]:
+ """Decorator form of :func:`known_marks` for a non-parametrized test."""
+
+ def apply(fn: Callable) -> Callable:
+ for mark in known_marks(name, table):
+ fn = mark(fn)
+ return fn
+
+ return apply
diff --git a/tests/e2e/core/windows/_rpc.py b/tests/e2e/core/windows/_rpc.py
new file mode 100644
index 00000000000..c8164092474
--- /dev/null
+++ b/tests/e2e/core/windows/_rpc.py
@@ -0,0 +1,119 @@
+"""Minimal stdio JSON-RPC client for ``python -m tui_gateway.entry`` — the process the Ink
+TUI spawns on every OS. Frames are UTF-8 JSON lines with non-ASCII left literal, exactly
+what Node's ``JSON.stringify`` + ``stdin.write`` produce, so the pipe encoding the gateway
+applies on Windows is part of what is under test."""
+
+from __future__ import annotations
+
+import json
+import queue
+import subprocess
+import sys
+import threading
+import time
+from typing import Any, Callable
+
+from tests.e2e.core.windows._helpers import TURN_TIMEOUT, WinHome
+
+READY_TIMEOUT = 120.0
+
+
+class StdioGateway:
+ def __init__(self, home: WinHome) -> None:
+ self.proc = subprocess.Popen(
+ [sys.executable, "-m", "tui_gateway.entry"], cwd=home.project, env=home.env(),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ )
+ self._frames: "queue.Queue[bytes | None]" = queue.Queue()
+ self._stderr: list[bytes] = []
+ self.events: list[dict[str, Any]] = []
+ self._responses: dict[str, dict[str, Any]] = {}
+ self._next = 0
+ threading.Thread(target=self._pump_out, daemon=True).start()
+ threading.Thread(target=self._pump_err, daemon=True).start()
+
+ def _pump_out(self) -> None:
+ assert self.proc.stdout is not None
+ for line in self.proc.stdout:
+ self._frames.put(line)
+ self._frames.put(None)
+
+ def _pump_err(self) -> None:
+ assert self.proc.stderr is not None
+ for line in self.proc.stderr:
+ self._stderr.append(line)
+
+ @property
+ def stderr(self) -> str:
+ return b"".join(self._stderr).decode("utf-8", errors="replace")
+
+ def send(self, obj: dict[str, Any]) -> None:
+ assert self.proc.stdin is not None
+ self.proc.stdin.write(json.dumps(obj, ensure_ascii=False).encode("utf-8") + b"\n")
+ self.proc.stdin.flush()
+
+ def _pump(self, timeout: float) -> None:
+ try:
+ raw = self._frames.get(timeout=timeout)
+ except queue.Empty:
+ return
+ if raw is None:
+ raise AssertionError(f"tui_gateway closed stdout (rc={self.proc.poll()}):\n{self.stderr[-3000:]}")
+ try:
+ msg = json.loads(raw.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ return # stray non-protocol output; the protocol stream is what matters
+ if msg.get("method") == "event":
+ self.events.append(msg.get("params") or {})
+ elif "id" in msg and "method" in msg:
+ self.send({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32601, "message": "unsupported"}})
+ elif "id" in msg:
+ self._responses[str(msg["id"])] = msg
+
+ def call(self, method: str, params: dict[str, Any] | None = None, timeout: float = TURN_TIMEOUT) -> Any:
+ self._next += 1
+ rid = f"win-{self._next}"
+ self.send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}})
+ deadline = time.monotonic() + timeout
+ while rid not in self._responses:
+ if time.monotonic() > deadline:
+ raise AssertionError(f"{method}: no response within {timeout}s\n{self.stderr[-2000:]}")
+ self._pump(0.25)
+ resp = self._responses.pop(rid)
+ assert "error" not in resp, f"{method} failed: {resp['error']}"
+ return resp.get("result")
+
+ def wait_event(self, etype: str, pred: Callable[[dict], bool] = lambda _e: True,
+ timeout: float = TURN_TIMEOUT) -> dict[str, Any]:
+ deadline = time.monotonic() + timeout
+ seen = 0
+ while True:
+ for ev in self.events[seen:]:
+ if ev.get("type") == etype and pred(ev):
+ return ev
+ seen = len(self.events)
+ if time.monotonic() > deadline:
+ raise AssertionError(
+ f"no {etype!r} within {timeout}s; saw {[e.get('type') for e in self.events][-20:]}\n"
+ f"{self.stderr[-2000:]}")
+ self._pump(0.25)
+
+ def turn(self, text: str) -> str:
+ self.wait_event("gateway.ready", timeout=READY_TIMEOUT)
+ sid = self.call("session.create", {})["session_id"]
+ self.call("prompt.submit", {"session_id": sid, "text": text})
+ done = self.wait_event("message.complete", lambda e: e.get("session_id") == sid)
+ payload = done.get("payload") or {}
+ text = payload.get("text")
+ return text if isinstance(text, str) else json.dumps(payload)
+
+ def close(self) -> int | None:
+ """Normal stop for a stdio gateway: the client closes the pipe."""
+ if self.proc.stdin is not None and not self.proc.stdin.closed:
+ self.proc.stdin.close()
+ try:
+ return self.proc.wait(timeout=60)
+ except subprocess.TimeoutExpired:
+ self.proc.kill()
+ self.proc.wait(timeout=30)
+ return None
diff --git a/tests/e2e/core/windows/test_boot_lifecycle.py b/tests/e2e/core/windows/test_boot_lifecycle.py
new file mode 100644
index 00000000000..22ea50f0c77
--- /dev/null
+++ b/tests/e2e/core/windows/test_boot_lifecycle.py
@@ -0,0 +1,180 @@
+"""Boot and lifecycle of the real Hermes processes on native Windows.
+
+* ``hermes.exe --version`` — the console-script shim users launch starts and reports
+ the installed package version.
+* ``hermes.exe chat -q`` — one oneshot turn against the loopback provider: the reply is
+ printed, the prompt reached the wire, and both messages persisted to ``state.db`` under
+ the session id the CLI announced.
+* ``hermes serve`` (the Desktop backend) — announces its port on stdout, and after the
+ Desktop's Windows quit path (``taskkill /T /F``) leaves no process of its tree behind
+ and a fresh backend boots again over the leftover host records.
+* ``hermes gateway run`` + ``hermes gateway stop`` — the Windows graceful-stop IPC (stop
+ marker, not TerminateProcess) drains the gateway: it exits on its own, records
+ ``stopped``, removes its pid file, and nothing of its tree survives.
+"""
+
+from __future__ import annotations
+
+import importlib.metadata
+import json
+import queue
+import re
+import socket
+import subprocess
+import threading
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.windows._helpers import (
+ WinHome,
+ db_rows,
+ hermes,
+ hermes_argv,
+ hermes_exe,
+ kill_tree,
+ last_user,
+ make_home,
+ nonce,
+ process_tree,
+ run,
+ survivors,
+ taskkill_tree,
+ wait_until,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text
+
+# Real process-tree kills (taskkill /T /F, psutil) of children this test spawned with a
+# scratch USERPROFILE/HERMES_HOME; the live-system guard would refuse the taskkill argv.
+pytestmark = [pytest.mark.windows_only, pytest.mark.integration, pytest.mark.live_system_guard_bypass]
+
+READY_TIMEOUT = 120.0
+
+
+def test_version_reports_installed_package(tmp_path: Path) -> None:
+ home = make_home(tmp_path, "http://127.0.0.1:9/v1") # never contacted by --version
+ res = run([str(hermes_exe()), "--version"], home, timeout=120)
+ assert res.returncode == 0, res.tail()
+ version = importlib.metadata.version("hermes-agent")
+ assert f"v{version}" in res.stdout, f"--version does not report the installed {version}:\n{res.tail()}"
+
+
+def test_chat_oneshot_turn_persists(tmp_path: Path) -> None:
+ prompt_id, reply_id = nonce("PROMPT"), nonce("REPLY")
+ with FakeLLMServer([Text(f"The answer is {reply_id}.")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ res = run([str(hermes_exe()), "chat", "-q", f"Say the code {prompt_id}", "-Q"], home)
+ assert res.returncode == 0, res.tail()
+ assert reply_id in res.stdout, f"reply not printed:\n{res.tail()}"
+ mains = srv.main_requests()
+ assert mains and prompt_id in last_user(mains[0]), "the prompt never reached the provider"
+
+ announced = re.search(r"session_id:\s*(\S+)", res.stdout + res.stderr)
+ assert announced, f"CLI did not announce a session id:\n{res.tail()}"
+ rows = db_rows(home, "SELECT session_id, role, content FROM messages ORDER BY id")
+ by_role = {r["role"]: r for r in rows}
+ assert prompt_id in (by_role.get("user") or {"content": ""})["content"], rows
+ assert reply_id in (by_role.get("assistant") or {"content": ""})["content"], rows
+ assert {r["session_id"] for r in rows} == {announced.group(1)}, (
+ f"persisted rows belong to {[r['session_id'] for r in rows]}, CLI announced {announced.group(1)}")
+
+
+def _port_open(port: int) -> bool:
+ with socket.socket() as s:
+ s.settimeout(1.0)
+ return s.connect_ex(("127.0.0.1", port)) == 0
+
+
+def _spawn_serve(home: WinHome) -> subprocess.Popen:
+ # Desktop spawn shape (electron/main.ts): token + desktop flag in env, stdin closed.
+ env = {"HERMES_DESKTOP": "1", "HERMES_DASHBOARD_SESSION_TOKEN": nonce("tok"),
+ "TERMINAL_CWD": str(home.project)}
+ return subprocess.Popen(
+ hermes_argv("serve", "--host", "127.0.0.1", "--port", "0"), cwd=home.profile, env=home.env(env),
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+ )
+
+
+def _serve_ready(home: WinHome) -> tuple[subprocess.Popen, int]:
+ """Spawn serve and wait for its READY port. A daemon pump keeps draining stdout after
+ READY, as the Desktop does, so a full pipe can never stall the backend."""
+ proc = _spawn_serve(home)
+ found: "queue.Queue[int | None]" = queue.Queue()
+ seen: list[str] = []
+
+ def pump() -> None:
+ assert proc.stdout is not None
+ announced = False
+ for raw in proc.stdout:
+ line = raw.decode("utf-8", errors="replace")
+ seen.append(line)
+ m = None if announced else re.search(r"HERMES_BACKEND_READY port=(\d+)", line)
+ if m:
+ announced = True
+ found.put(int(m.group(1)))
+ found.put(None)
+
+ threading.Thread(target=pump, daemon=True).start()
+ try:
+ port = found.get(timeout=READY_TIMEOUT)
+ except queue.Empty:
+ port = None
+ assert port is not None, f"serve (rc={proc.poll()}) announced no READY port:\n{''.join(seen)[-3000:]}"
+ assert _port_open(port), f"READY announced port {port} but nothing accepts on it"
+ return proc, port
+
+
+def test_serve_tree_kill_leaves_no_orphans_and_reboots(tmp_path: Path) -> None:
+ with FakeLLMServer() as srv:
+ home = make_home(tmp_path, srv.base_url)
+ first, port = _serve_ready(home)
+ tree = process_tree(first.pid)
+ second = None
+ try:
+ killed = taskkill_tree(first.pid)
+ assert killed.returncode == 0, killed.stderr
+ left = survivors(tree, timeout=30)
+ assert not left, f"processes of the killed backend tree survived taskkill /T /F: {left}"
+ wait_until(lambda: not _port_open(port), 30, f"port {port} to be released")
+
+ second, port2 = _serve_ready(home)
+ assert second.poll() is None and _port_open(port2)
+ finally:
+ kill_tree(tree)
+ if second is not None:
+ kill_tree(process_tree(second.pid))
+
+
+def _gateway_state(home: WinHome) -> dict:
+ path = home.hermes_home / "gateway_state.json"
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+
+
+def test_gateway_stop_drains_gracefully(tmp_path: Path) -> None:
+ with FakeLLMServer() as srv:
+ home = make_home(tmp_path, srv.base_url)
+ log = tmp_path / "gateway.log"
+ with log.open("wb") as fh:
+ gw = subprocess.Popen(hermes_argv("gateway", "run"), cwd=home.project, env=home.env(),
+ stdin=subprocess.DEVNULL, stdout=fh, stderr=subprocess.STDOUT)
+ tree: list = []
+ try:
+ wait_until(lambda: _gateway_state(home).get("gateway_state") == "running" or gw.poll() is not None,
+ READY_TIMEOUT, "gateway_state.json to report running")
+ assert gw.poll() is None, f"gateway exited {gw.returncode} during boot:\n{log.read_text(errors='replace')}"
+ tree = process_tree(gw.pid)
+
+ res = hermes(home, "gateway", "stop")
+ assert res.returncode == 0 and "Stopped" in res.stdout, res.tail()
+ code = gw.wait(timeout=60)
+ state = _gateway_state(home)
+ assert state.get("gateway_state") == "stopped", (
+ f"gateway did not drain through its graceful path (rc={code}); last state {state}\n"
+ f"{log.read_text(errors='replace')[-3000:]}")
+ assert not (home.hermes_home / "gateway.pid").exists(), "gateway.pid left behind after stop"
+ assert not survivors(tree, timeout=30), "processes of the gateway tree survived stop"
+ finally:
+ kill_tree(tree or process_tree(gw.pid))
diff --git a/tests/e2e/core/windows/test_cron_scripts.py b/tests/e2e/core/windows/test_cron_scripts.py
new file mode 100644
index 00000000000..d588d3f0432
--- /dev/null
+++ b/tests/e2e/core/windows/test_cron_scripts.py
@@ -0,0 +1,92 @@
+"""Cron script jobs on native Windows (``hermes cron create --script`` + ``hermes cron run``).
+
+A no-agent script job runs its script through an interpreter picked by extension and
+delivers stdout as the job result. ``hermes cron run <id>`` executes it synchronously
+through ``cron.scheduler.run_job`` (the ticker's code path) when no gateway owns the store.
+
+The ``.sh`` case launches Hermes with the PATH a NATIVE Windows process has (Start menu,
+Scheduled Task, Desktop): Git's ``cmd`` dir only, no ``Git\\bin`` / ``Git\\usr\\bin``, so
+the only ``bash`` a bare PATH lookup finds is the WSL stub in System32 (or none). Git for
+Windows is installed at its standard location the whole time, which is exactly the host
+the canonical resolver (``tools/environments/local.py::_find_bash``) handles.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.windows._helpers import WinHome, expect, hermes, known, make_home, nonce
+
+pytestmark = [pytest.mark.windows_only, pytest.mark.integration]
+
+KNOWN: dict[str, str] = {
+ "sh_script": "#120504 cron .sh scripts resolve bash via bare PATH lookup (WSL stub), not Git Bash",
+}
+
+_JOB_ID = re.compile(r"Created job: (\S+)")
+
+
+def _native_process_path() -> str:
+ """PATH minus every directory that ships a real bash.exe (Git\\bin, Git\\usr\\bin, MSYS2...);
+ System32 (with its WSL stub, when the feature is present) stays, as for a native process."""
+ kept = []
+ for entry in os.environ.get("PATH", "").split(os.pathsep):
+ norm = os.path.normcase(os.path.normpath(entry)) if entry else ""
+ if not entry:
+ continue
+ stub_dir = "system32" in norm or "windowsapps" in norm
+ if not stub_dir and os.path.isfile(os.path.join(entry, "bash.exe")):
+ continue
+ kept.append(entry)
+ system32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32")
+ if not any(os.path.normcase(os.path.normpath(e)) == os.path.normcase(system32) for e in kept):
+ kept.append(system32)
+ return os.pathsep.join(kept)
+
+
+def _run_script_job(home: WinHome, script: str, env_extra: dict[str, str] | None = None) -> tuple[dict, str]:
+ created = hermes(home, "cron", "create", "1d", "--name", "win-script", "--script", script,
+ "--no-agent", "--deliver", "local", cwd=home.profile, env_extra=env_extra)
+ match = _JOB_ID.search(created.stdout)
+ assert created.returncode == 0 and match, created.tail()
+ job_id = match.group(1)
+ ran = hermes(home, "cron", "run", job_id, cwd=home.profile, env_extra=env_extra)
+ assert ran.returncode == 0 and "Ran now:" in ran.stdout, f"job did not run synchronously:\n{ran.tail()}"
+ jobs = json.loads((home.hermes_home / "cron" / "jobs.json").read_text(encoding="utf-8"))["jobs"]
+ job = next(j for j in jobs if j["id"] == job_id)
+ outputs = sorted((home.hermes_home / "cron" / "output" / job_id).glob("*.md"))
+ return job, outputs[-1].read_text(encoding="utf-8") if outputs else ""
+
+
+def test_python_script_job_delivers_stdout(tmp_path: Path) -> None:
+ marker = nonce("PYJOB")
+ home = make_home(tmp_path, "http://127.0.0.1:9/v1") # no-agent: the model is never called
+ scripts = home.hermes_home / "scripts"
+ scripts.mkdir(parents=True)
+ (scripts / "report.py").write_text(f"import sys\nprint('{marker}', sys.platform)\n", encoding="utf-8")
+ job, output = _run_script_job(home, "report.py")
+ assert job["last_status"] == "ok", f"python script job failed: {job.get('last_error')}\n{output}"
+ assert f"{marker} win32" in output, f"script stdout not delivered:\n{output}"
+
+
+@known("sh_script", KNOWN)
+def test_sh_script_job_runs_under_git_bash(tmp_path: Path) -> None:
+ git_bash = Path(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe")
+ assert git_bash.is_file(), f"precondition: Git for Windows installed at {git_bash}"
+ marker = nonce("SHJOB")
+ home = make_home(tmp_path, "http://127.0.0.1:9/v1")
+ scripts = home.hermes_home / "scripts"
+ scripts.mkdir(parents=True)
+ (scripts / "report.sh").write_bytes(f'#!/usr/bin/env bash\necho "{marker}" "$(uname -s)"\n'.encode())
+ native_path = _native_process_path()
+ job, output = _run_script_job(home, "report.sh", env_extra={"PATH": native_path})
+ bare = shutil.which("bash", path=native_path)
+ expect(job["last_status"] == "ok" and marker in output,
+ f"bare PATH lookup finds {bare!r}; job status {job['last_status']!r}: {job.get('last_error')}\n{output}")
+ assert "_NT-" in output, f".sh job ran, but not under Git Bash (MSYS/MinGW uname):\n{output}"
diff --git a/tests/e2e/core/windows/test_prompt_paths.py b/tests/e2e/core/windows/test_prompt_paths.py
new file mode 100644
index 00000000000..410184fac9d
--- /dev/null
+++ b/tests/e2e/core/windows/test_prompt_paths.py
@@ -0,0 +1,107 @@
+"""Prompt assembly with native Windows paths, through real Hermes processes.
+
+* Subdirectory hints: after a terminal command touches ``backend\\src``, the tool result the
+ model receives carries ``backend/AGENTS.md`` — for the forward-slash spelling AND the
+ native backslash spelling a model emits on Windows (#121150).
+* AGENTS.md chain: ``hermes chat -q`` launched in ``pkg\\inner`` of a git repo loads all
+ three AGENTS.md files and labels them ``../../AGENTS.md`` / ``../AGENTS.md`` / ``AGENTS.md``
+ — one spelling on every OS (#121015).
+* ``@folder:`` references through the TUI gateway (the Ink TUI's process): the listing
+ header injected into the user message is ``pkg/sub/``, matching its own ``/`` directory
+ marker and entry lines, not ``pkg\\sub/`` (#121114).
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.windows._helpers import (
+ expect,
+ hermes,
+ known_marks,
+ known,
+ last_user,
+ make_home,
+ nonce,
+ system_prompt,
+ tool_results,
+)
+from tests.e2e.core.windows._rpc import StdioGateway
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+pytestmark = [pytest.mark.windows_only, pytest.mark.integration]
+
+KNOWN: dict[str, str] = {
+ "native-backslash": "#121150 subdirectory hints never load from native Windows paths (POSIX shlex)",
+ "chain_labels": "#121015 AGENTS.md chain labels use os.path.relpath separators (..\\AGENTS.md)",
+ "folder_header": "#121114 @folder listing header mixes separators on Windows (pkg\\sub/)",
+}
+
+# spelling -> terminal command the model issues (the issue's own repro commands)
+HINT_COMMANDS: dict[str, str] = {
+ "forward-slash": "python backend/src/main.py",
+ "native-backslash": "python backend\\src\\main.py",
+}
+
+
[email protected]("spelling", [
+ pytest.param(name, marks=known_marks(name, KNOWN)) for name in HINT_COMMANDS
+])
+def test_subdirectory_hint_reaches_model(spelling: str, tmp_path: Path) -> None:
+ canary = nonce("BACKEND-RULES")
+ with FakeLLMServer([ToolCall("terminal", {"command": HINT_COMMANDS[spelling]}), Text("done")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ (home.project / "backend" / "src").mkdir(parents=True)
+ (home.project / "backend" / "src" / "main.py").write_text("print('hi')\n", encoding="utf-8")
+ (home.project / "backend" / "AGENTS.md").write_text(f"# Backend\n\n{canary}\n", encoding="utf-8")
+ res = hermes(home, "chat", "-q", "Run the backend entry point.", "-Q")
+ assert res.returncode == 0, res.tail()
+ results = tool_results(srv)
+ assert len(results) == 1, f"expected one terminal result on the wire, got {results}"
+ expect(canary in results[0],
+ f"{spelling}: backend/AGENTS.md never reached the model after {HINT_COMMANDS[spelling]!r}:\n"
+ f"{results[0][-1500:]}")
+
+
+@known("chain_labels", KNOWN)
+def test_agents_chain_labels_are_os_independent(tmp_path: Path) -> None:
+ canaries = {name: nonce(name.upper()) for name in ("root", "pkg", "inner")}
+ with FakeLLMServer([Text("done")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ repo = home.project
+ subprocess.run(["git", "init", "-q", str(repo)], check=True, timeout=60)
+ inner = repo / "pkg" / "inner"
+ inner.mkdir(parents=True)
+ for directory, name in ((repo, "root"), (repo / "pkg", "pkg"), (inner, "inner")):
+ (directory / "AGENTS.md").write_text(f"# {name}\n\n{canaries[name]}\n", encoding="utf-8")
+ res = hermes(home, "chat", "-q", "hello", "-Q", cwd=inner)
+ assert res.returncode == 0, res.tail()
+ prompt = system_prompt(srv.main_requests()[0])
+ missing = [name for name, c in canaries.items() if c not in prompt]
+ assert not missing, f"AGENTS.md chain members missing from the system prompt: {missing}"
+ headings = [line[3:] for line in prompt.splitlines() if line.startswith("## ") and "AGENTS.md" in line]
+ expect(headings == ["../../AGENTS.md", "../AGENTS.md", "AGENTS.md"],
+ f"AGENTS.md chain headings are not the portable spelling: {headings}")
+
+
+@known("folder_header", KNOWN)
+def test_folder_reference_header_uses_one_separator(tmp_path: Path) -> None:
+ body = nonce("FOLDER-FILE")
+ with FakeLLMServer([Text("done")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ nested = home.project / "pkg" / "sub"
+ nested.mkdir(parents=True)
+ (nested / "a.py").write_text(f"# {body}\nx = 1\n", encoding="utf-8")
+ gw = StdioGateway(home)
+ try:
+ gw.turn("Review @folder:pkg/sub")
+ finally:
+ gw.close()
+ user = last_user(srv.main_requests()[0])
+ assert "- a.py" in user, f"@folder listing never reached the model:\n{user[-2000:]}"
+ # The header is the one non-entry line naming the folder; entries are "- name" lines.
+ header = [ln.strip() for ln in user.splitlines() if ln.strip().endswith("sub/") and not ln.lstrip().startswith("-")]
+ expect(header == ["pkg/sub/"], f"@folder header lines: {header}\n{user[-1500:]}")
diff --git a/tests/e2e/core/windows/test_state_db_guard.py b/tests/e2e/core/windows/test_state_db_guard.py
new file mode 100644
index 00000000000..f3889d025fd
--- /dev/null
+++ b/tests/e2e/core/windows/test_state_db_guard.py
@@ -0,0 +1,71 @@
+"""The state.db write-guard sees a live foreign holder on native Windows.
+
+``hermes sessions optimize-storage`` rewrites the store (FTS rebuild + VACUUM). Run under a
+live writer, it is how every agent ends up refusing turns (#110054), so it refuses while
+another process holds ``state.db`` or its WAL sidecars. The holder here is the realistic
+one: a real ``hermes gateway run`` for the same profile. Control: the same command succeeds
+once the gateway is stopped, so a refusal is about the holder and nothing else.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.windows._helpers import (
+ expect,
+ hermes,
+ hermes_argv,
+ kill_tree,
+ known,
+ make_home,
+ process_tree,
+ wait_until,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer
+
+pytestmark = [pytest.mark.windows_only, pytest.mark.integration, pytest.mark.live_system_guard_bypass]
+
+KNOWN: dict[str, str] = {
+ "foreign_holder": "#120205 foreign_state_db_holders() returns [] on Windows; the write-guard never refuses",
+}
+
+
+def _running(home) -> bool:
+ try:
+ state = json.loads((home.hermes_home / "gateway_state.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return False
+ return state.get("gateway_state") == "running"
+
+
+@known("foreign_holder", KNOWN)
+def test_optimize_storage_refuses_while_gateway_holds_store(tmp_path: Path) -> None:
+ with FakeLLMServer() as srv:
+ home = make_home(tmp_path, srv.base_url)
+ log = tmp_path / "gateway.log"
+ with log.open("wb") as fh:
+ gw = subprocess.Popen(hermes_argv("gateway", "run"), cwd=home.project, env=home.env(),
+ stdin=subprocess.DEVNULL, stdout=fh, stderr=subprocess.STDOUT)
+ tree: list = []
+ try:
+ wait_until(lambda: _running(home) or gw.poll() is not None, 120, "the gateway to report running")
+ assert gw.poll() is None, f"gateway exited during boot:\n{log.read_text(errors='replace')}"
+ tree = process_tree(gw.pid)
+ assert home.db_path.exists(), "the running gateway never opened state.db"
+
+ held = hermes(home, "sessions", "optimize-storage")
+ refused = held.returncode != 0 and "Refusing" in held.stdout
+ stop = hermes(home, "gateway", "stop")
+ assert stop.returncode == 0, stop.tail()
+ gw.wait(timeout=60)
+ quiet = hermes(home, "sessions", "optimize-storage")
+ assert quiet.returncode == 0, f"optimize-storage fails even with no holder:\n{quiet.tail()}"
+ named = any(str(p.pid) in held.stdout for p in tree) # venv launcher OR its interpreter child
+ expect(refused and named,
+ f"optimize-storage ran under a live gateway (pid {gw.pid}) instead of refusing:\n{held.tail()}")
+ finally:
+ kill_tree(tree or process_tree(gw.pid))
diff --git a/tests/e2e/core/windows/test_terminal_tool.py b/tests/e2e/core/windows/test_terminal_tool.py
new file mode 100644
index 00000000000..60e8d7354e4
--- /dev/null
+++ b/tests/e2e/core/windows/test_terminal_tool.py
@@ -0,0 +1,64 @@
+"""The real terminal tool on native Windows, driven by a model turn through ``hermes chat -q``.
+
+On Windows the terminal tool runs every command through Git Bash (``_find_bash``). The
+model reaches native shells from there, so each case is one scripted turn:
+
+ model -> terminal(<command>) -> real Git Bash child -> tool result -> model -> answer
+
+and asserts the command's stdout AND its exit code on both the next wire request (what
+the model is told) and the persisted ``tool`` row in ``state.db`` (what a resumed session
+replays). The Git Bash case also proves the shell is MSYS/MinGW, not WSL.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.windows._helpers import (
+ hermes,
+ make_home,
+ nonce,
+ parse_tool_json,
+ persisted_messages,
+ tool_results,
+)
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+pytestmark = [pytest.mark.windows_only, pytest.mark.integration]
+
+# shell -> (command template, exit code, extra marker the output must carry)
+SHELLS: dict[str, tuple[str, int, str]] = {
+ # uname -s under Git Bash is MINGW64_NT-* / MSYS_NT-*; under WSL it would be Linux.
+ "git-bash": ('echo "{marker}"; uname -s; exit 3', 3, "_NT-"),
+ "powershell": ("powershell.exe -NoProfile -NonInteractive -Command "
+ "\"Write-Output '{marker}'; Write-Output \\$PSVersionTable.PSEdition; exit 5\"", 5, "Desktop"),
+ "cmd": ('MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo {marker}& ver& exit /b 7"', 7, "Windows"),
+}
+
+
[email protected]("shell", list(SHELLS))
+def test_terminal_round_trip_persists_output_and_exit_code(shell: str, tmp_path: Path) -> None:
+ template, code, extra = SHELLS[shell]
+ marker, answer = nonce(shell.upper()), nonce("DONE")
+ with FakeLLMServer([ToolCall("terminal", {"command": template.format(marker=marker)}), Text(answer)]) as srv:
+ # `powershell -Command` is flagged as script execution; with no user present to approve,
+ # -q blocks it. The documented opt-in keeps this about the tool round trip, not approvals.
+ home = make_home(tmp_path, srv.base_url, extra_config="approvals:\n single_query_mode: approve\n")
+ res = hermes(home, "chat", "-q", f"Run the {shell} check.", "-Q")
+ assert res.returncode == 0, res.tail()
+ assert answer in res.stdout, f"final answer not delivered:\n{res.tail()}"
+ results = tool_results(srv)
+
+ assert len(results) == 1, f"expected one tool result on the wire, got {results}"
+ wire = parse_tool_json(results[0])
+ assert marker in (wire.get("output") or ""), f"{shell}: command output lost on the wire: {wire}"
+ assert extra in (wire.get("output") or ""), f"{shell}: output is not from the expected shell: {wire}"
+ assert wire.get("exit_code") == code, f"{shell}: exit code lost on the wire: {wire}"
+
+ stored = [r for r in persisted_messages(home) if r["role"] == "tool"]
+ assert len(stored) == 1, f"expected one persisted tool row, got {[dict(r) for r in stored]}"
+ row = parse_tool_json(stored[0]["content"])
+ assert marker in (row.get("output") or "") and row.get("exit_code") == code, (
+ f"{shell}: persisted tool row differs from what the model saw: {row}")
diff --git a/tests/e2e/core/windows/test_unicode_input.py b/tests/e2e/core/windows/test_unicode_input.py
new file mode 100644
index 00000000000..303e730fd31
--- /dev/null
+++ b/tests/e2e/core/windows/test_unicode_input.py
@@ -0,0 +1,151 @@
+"""Non-ASCII / emoji user input on native Windows reaches the model intact.
+
+Three real input paths a Windows user hits:
+
+* ``hermes chat -q "<text>"`` — argv (CreateProcessW) into the oneshot turn; the reply,
+ with its own emoji, is printed back through a pipe (Windows code-page territory).
+* the TUI gateway's stdio JSON-RPC — UTF-8 frames from the Ink TUI (Node writes literal
+ non-ASCII, never ``\\u`` escapes).
+* the classic interactive CLI (prompt_toolkit) typed into a real console: a ConPTY driven
+ through pywinpty, the same console layer Windows Terminal uses (#120776).
+"""
+
+from __future__ import annotations
+
+import re
+import subprocess
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.windows._helpers import (
+ hermes,
+ hermes_argv,
+ kill_tree,
+ last_user,
+ make_home,
+ nonce,
+ persisted_messages,
+ process_tree,
+ wait_until,
+)
+from tests.e2e.core.windows._rpc import StdioGateway
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text
+
+pytestmark = [pytest.mark.windows_only, pytest.mark.integration]
+
+KNOWN: dict[str, str] = {} # nothing red on origin/main in this file
+
+TEXT = "Grüße, 日本語 und Emoji 😂👍🏽"
+REPLY = "Réponse ✓ 😂"
+BMP = "Grüße, 日本語"
+
+
+def test_chat_q_argv_non_ascii_reaches_wire_and_state_db(tmp_path: Path) -> None:
+ tag = nonce("ARGV")
+ with FakeLLMServer([Text(f"{REPLY} {tag}")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ res = hermes(home, "chat", "-q", f"{TEXT} {tag}", "-Q")
+ assert res.returncode == 0, res.tail()
+ user = last_user(srv.main_requests()[0])
+ assert f"{TEXT} {tag}" in user, f"prompt altered before the wire: {user!r}"
+ stored = [r["content"] for r in persisted_messages(home) if r["role"] == "user"]
+ assert any(f"{TEXT} {tag}" in (c or "") for c in stored), f"prompt altered in state.db: {stored!r}"
+
+
+def test_chat_q_non_ascii_reply_printed_intact(tmp_path: Path) -> None:
+ tag = nonce("REPLY")
+ with FakeLLMServer([Text(f"{REPLY} {tag}")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ res = hermes(home, "chat", "-q", "Reply with the code.", "-Q")
+ assert res.returncode == 0, res.tail()
+ assert tag in res.stdout, f"reply not printed at all:\n{res.tail()}"
+ assert f"{REPLY} {tag}" in res.stdout, f"reply printed with its non-ASCII mangled: {res.stdout[-500:]!r}"
+
+
+def test_tui_gateway_utf8_frames_reach_wire(tmp_path: Path) -> None:
+ tag = nonce("TUI")
+ with FakeLLMServer([Text(f"{REPLY} {tag}")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ gw = StdioGateway(home)
+ try:
+ answer = gw.turn(f"{TEXT} {tag}")
+ finally:
+ gw.close()
+ user = last_user(srv.main_requests()[0])
+ assert tag in user, f"prompt never reached the provider: {user!r}"
+ assert f"{TEXT} {tag}" in user, f"TUI gateway altered the prompt before the wire: {user!r}"
+ assert f"{REPLY} {tag}" in answer, f"reply altered on the way back to the TUI: {answer!r}"
+
+
+class _Console:
+ """A real ConPTY (pywinpty) running the classic CLI; output is pumped on a thread."""
+
+ def __init__(self, argv: list[str], cwd: Path, env: dict[str, str]) -> None:
+ from winpty import PtyProcess
+
+ self.proc = PtyProcess.spawn(subprocess.list2cmdline(argv), cwd=str(cwd), env=env,
+ dimensions=(50, 200))
+ self._chunks: list[str] = []
+ self._last = time.monotonic()
+ threading.Thread(target=self._pump, daemon=True).start()
+
+ def _pump(self) -> None:
+ while True:
+ try:
+ data = self.proc.read(4096)
+ except (EOFError, OSError):
+ return
+ if data:
+ self._chunks.append(data)
+ self._last = time.monotonic()
+
+ @property
+ def screen(self) -> str:
+ return "".join(self._chunks)
+
+ def quiet_for(self, seconds: float) -> bool:
+ return bool(self._chunks) and time.monotonic() - self._last >= seconds
+
+ def close(self) -> None:
+ tree = process_tree(self.proc.pid)
+ try:
+ self.proc.terminate(force=True)
+ except Exception: # noqa: BLE001 - teardown of an already-dead console
+ pass
+ kill_tree(tree)
+
+
+_ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07")
+
+
+def _plain(screen: str) -> str:
+ return _ANSI.sub("", screen)
+
+
+def test_classic_cli_console_non_ascii_reaches_wire(tmp_path: Path) -> None:
+ """Typed into the classic CLI composer through a real ConPTY: Latin-1 + CJK letters.
+ Symbols (✓, emoji) typed this way never reached the composer (not echoed before Enter);
+ without a harness control proving pywinpty delivers them, that loss can't be pinned on
+ Hermes, so they are left out here (#120776 is the submit-time half)."""
+ tag = nonce("CONPTY")
+ with FakeLLMServer([Text(f"ack {tag}")]) as srv:
+ home = make_home(tmp_path, srv.base_url)
+ console = _Console(hermes_argv("chat"), home.project, home.env({"TERM": "xterm-256color"}))
+ try:
+ wait_until(lambda: console.quiet_for(3.0), 120, "the classic CLI to finish painting its prompt")
+ console.proc.write(f"{BMP} {tag}")
+ wait_until(lambda: tag in console.screen, 30, "the composer to echo the typed text")
+ echoed = _plain(console.screen)
+ console.proc.write("\r")
+ wait_until(lambda: srv.main_requests(), 90, "the typed turn to reach the provider")
+ user = last_user(srv.main_requests()[0])
+ finally:
+ screen = console.screen
+ console.close()
+ assert tag in user, f"typed text never reached the provider: {user!r}\n{_plain(screen)[-2000:]}"
+ assert f"{BMP} {tag}" in user, (
+ f"non-ASCII lost between the console and the wire: {ascii(user)}\n"
+ f"composer echoed it before Enter: {BMP in echoed}\nconsole tail:\n{ascii(_plain(screen)[-600:])}")