hermes-agent/tests/tui_gateway/test_entry_picker_prewarm.py
Bikash Joshi 1af97a3f31 fix(tui_gateway): drop peer-less global broadcasts instead of printing them to serve stdout
_broadcast_global_event fell back to _emit -> write_json -> the module stdio
transport whenever no WS peer was registered. That fallback is only right for
the stdio TUI (tui_gateway.entry), whose stdout IS the JSON-RPC channel. In
`hermes serve` / the dashboard, JSON-RPC runs over WS and Desktop captures
stdout into desktop.log, so once the last WS client left, the change watcher
(sessions.changed every ~15-25s), the free-tier bootstrap (setup.ready, fired
before any client connects) and the orphan reaper (session.reclaimed) printed
raw frames there (~1100 `[hermes] {"jsonrpc": ...}` lines).

entry.main() now marks stdout as the RPC channel; everywhere else a peer-less
global broadcast is dropped with a debug log. Clients re-pull state on
connect (gateway.ready / setup.status), so nothing is lost.
2026-09-23 05:54:29 -07:00

92 lines
3.8 KiB
Python

"""Regression test: the stdio TUI entry point prewarms the /model picker cache.
The classic CLI run() loop calls ``prewarm_picker_cache_async()`` during the
idle window after the banner, so the first ``/model`` open hits a warm
provider-models disk cache. The stdio TUI entry point (``entry.main()``) never
did — the first ``/model`` open in a TUI session blocked on serial /v1/models
fetches for every authenticated provider (#72021).
These tests pin the entrypoint wiring itself (the helper's own worker/once
guard is covered in ``tests/hermes_cli/test_picker_prewarm.py``):
- ``main()`` invokes ``hermes_cli.model_switch_providers.prewarm_picker_cache_async``
exactly once, AFTER the ``gateway.ready`` event is written (banner shown,
user about to type — the idle window the prewarm is meant to fill).
- The startup path stays non-blocking: with the prewarm spied out, ``main()``
proceeds into the stdin read loop and returns normally on EOF.
- A prewarm import/start failure is swallowed (fire-and-forget contract) and
must not prevent ``main()`` from reaching the read loop.
Harness: same style as tests/tui_gateway/test_tui_entry_mcp_owner.py — import
``tui_gateway.entry`` and monkeypatch its module attributes, running the real
``main()`` with stubbed I/O collaborators (no subprocess, no real gateway).
"""
from __future__ import annotations
import io
from tui_gateway import entry
from hermes_cli import model_switch_providers
def _run_main(monkeypatch, events, *, prewarm=None):
"""Run entry.main() with stubbed collaborators, recording ordering.
``events`` receives ``("write", <event type>)`` for every write_json call
and ``("prewarm",)`` when the spy fires, in call order.
"""
monkeypatch.setattr(entry, "_install_sidecar_publisher", lambda: None)
monkeypatch.setattr(entry.server, "_stdio_is_rpc_channel", False, raising=False) # main() flips it; restore after
monkeypatch.setattr(entry, "ensure_mcp_discovery_started", lambda: None)
monkeypatch.setattr(entry, "resolve_skin", lambda: "default")
monkeypatch.setattr(entry.server, "_ensure_skin_watcher", lambda: None)
monkeypatch.setattr(entry, "_log_exit", lambda reason: None)
# Genuine EOF, no fd-0 forensics in the test process.
monkeypatch.setattr(entry, "handle_spurious_eof", lambda *a: False)
def _write_json(payload):
params = payload.get("params") or {}
events.append(("write", params.get("type") or payload.get("method")))
return True
monkeypatch.setattr(entry, "write_json", _write_json)
# entry.main() imports the helper lazily from hermes_cli.model_switch,
# so the spy must live on that module, not on entry.
if prewarm is None:
def prewarm():
events.append(("prewarm",))
return None # fire-and-forget handle; never blocks
monkeypatch.setattr(model_switch_providers, "prewarm_picker_cache_async", prewarm)
# Empty stdin -> immediate EOF -> main() returns after entering the loop.
monkeypatch.setattr(entry.sys, "stdin", io.StringIO(""))
entry.main()
def test_main_survives_prewarm_failure(monkeypatch):
"""Fire-and-forget contract: a prewarm that raises at start must be
swallowed and main() must still reach the read loop and exit cleanly."""
events: list[tuple] = []
def _boom():
events.append(("prewarm",))
raise RuntimeError("provider registry exploded")
_run_main(monkeypatch, events, prewarm=_boom) # must not raise
assert ("prewarm",) in events
assert ("write", "gateway.ready") in events
def test_main_marks_stdout_as_the_rpc_channel(monkeypatch):
"""The stdio TUI is the one process whose stdout carries JSON-RPC, so peer-less global
broadcasts (skin.changed, sessions.changed) must still reach it there."""
_run_main(monkeypatch, [])
assert entry.server._stdio_is_rpc_channel is True