Skip to content

The agent that grows with you

fix(gateway): local viewers see codex messages that arrive without deltas

teknium137fba503a31a
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 6b9bea42e90..f4843d89bc2 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -208,15 +208,28 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
# stitched as a "partial delivery" nobody received (classic -q parity).
raise _NoStreamConsumer()
+ local_viewer_route = getattr(ctx.source, "platform", None) == Platform.LOCAL
+
def interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
if not ctx._run_still_current():
return
+ unseen = False
+ if local_viewer_route and not already_streamed and str(text or "").strip():
+ # LocalSessionAdapter.send publishes nothing, so unstreamed commentary handed to the
+ # consumer would be recorded as delivered while no viewer saw it. A codex app-server
+ # final that arrives with no deltas then suppresses the reply (message.complete "").
+ # Publish the in-process TUI's message.interim contract instead, and count the text
+ # as delivered only when a viewer or observer actually took it.
+ payload = {"text": text, "already_streamed": False}
+ unseen = not self._publish_execution("message.interim", payload)
if stts is not None:
# Flush accepted deltas; completed commentary is a separate speech segment.
stts.on_delta(None)
if not already_streamed:
stts.on_delta(text)
stts.on_delta(None)
+ if unseen:
+ return
if stream_consumer is not None:
stream_consumer.on_segment_break() if already_streamed else stream_consumer.on_commentary(text)
elif not already_streamed and ctx._status_adapter and str(text or "").strip():
diff --git a/tests/e2e/core/providers/test_native_codex_app_server_tui.py b/tests/e2e/core/providers/test_native_codex_app_server_tui.py
new file mode 100644
index 00000000000..39ae07fbb05
--- /dev/null
+++ b/tests/e2e/core/providers/test_native_codex_app_server_tui.py
@@ -0,0 +1,74 @@
+"""codex_app_server on an interactive viewer: a real ``hermes --tui`` attached to the gateway.
+
+The codex bridge hands every completed agentMessage (the final answer included) to the interim
+commentary path. On the gateway's local route that commentary used to reach only
+``LocalSessionAdapter.send``, which publishes nothing yet reports success, so an agentMessage that
+arrived without ``item/agentMessage/delta`` frames was recorded as delivered, the final send was
+suppressed and ``message.complete`` carried empty text: the TUI showed the tool card and no reply.
+
+Real chain: ``hermes --tui`` on a real PTY (VT-rendered grid), its gateway daemon, a real AIAgent
+on the native codex runtime, and the fake ``codex app-server`` binary
+(``tests/fakes/providers/codex_app_server.py``) completing agentMessage items with no deltas.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import sqlite3
+import sys
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.providers._native_helpers import latest_session, make_home, messages
+from tests.e2e.core.terminal._pty import REPO_ROOT, PtyHermes, poll
+from tests.fakes.providers.codex_app_server import FakeCodex
+
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="real PTY + /proc session scan"),
+ # Cleanup SIGKILLs the PTY session's tree (TUI, gateway daemon, app-server) by session id.
+ pytest.mark.live_system_guard_bypass,
+]
+
+COMMENTARY, FINAL = "CODEX-COMMENTARY-ALPHA", "CODEX-FINAL-OMEGA"
+
+
+def test_undelta_codex_messages_reach_the_attached_tui(tmp_path: Path) -> None:
+ if shutil.which("node") is None or not (REPO_ROOT / "ui-tui" / "dist" / "entry.js").is_file():
+ 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")
+
+ fake = FakeCodex(tmp_path, [{"steps": [
+ {"kind": "message", "text": COMMENTARY, "deltas": False},
+ {"kind": "command", "command": "echo CANARY-1", "output": "CANARY-1-OUT\n"},
+ {"kind": "message", "text": FINAL, "deltas": False},
+ ]}])
+ home = make_home(tmp_path, {"provider": "openai", "default": "gpt-5.5", "openai_runtime": "codex_app_server",
+ "codex_bin": str(fake.bin)}, env_file={"OPENAI_API_KEY": "sk-fake-codex-e2e"})
+ tui = PtyHermes(tmp_path, ["--tui", "--yolo"], None, rows=50, cols=120)
+ try:
+ tui.wait_ready()
+ tui.submit("run the canary USER-ONE")
+ # Completion signal independent of the screen: the agent persisted the final answer.
+ rows = []
+
+ def final_persisted() -> bool:
+ nonlocal rows
+ try:
+ rows = messages(home, latest_session(home))
+ except (AssertionError, sqlite3.OperationalError): # no db / schema not created yet
+ return False
+ return any(r["role"] == "assistant" and r["content"] == FINAL for r in rows)
+
+ poll(final_persisted, timeout=90, what="the codex final answer persisted")
+ tui.wait_quiet(2.0, timeout=45)
+ screen = tui.dump()
+ rows = [(r["role"], r["content"]) for r in rows]
+ assert tui.count(FINAL) == 1, f"final answer on screen {tui.count(FINAL)}x (rows={rows}):\n{screen}"
+ assert tui.count(COMMENTARY) == 1, f"commentary on screen {tui.count(COMMENTARY)}x:\n{screen}"
+ assert tui.text().index(COMMENTARY) < tui.text().index(FINAL), screen
+ fake.assert_wire_clean()
+ finally:
+ tui.close()
diff --git a/tests/e2e/core/terminal/_pty.py b/tests/e2e/core/terminal/_pty.py
index 9bfa74d6856..f16d180c164 100644
--- a/tests/e2e/core/terminal/_pty.py
+++ b/tests/e2e/core/terminal/_pty.py
@@ -102,15 +102,17 @@ def cmdline(pid: int) -> str:
class PtyHermes:
"""One interactive ``hermes`` process on a PTY with an emulated screen."""
- def __init__(self, root: Path, argv_tail: list[str], llm: FakeLLMServer, *, rows: int, cols: int,
+ def __init__(self, root: Path, argv_tail: list[str], llm: FakeLLMServer | None, *, rows: int, cols: int,
extra_config: str = "") -> None:
+ """``llm=None``: the caller already wrote ``root/home/.hermes`` (e.g. a native-runtime home)."""
self.root = root
self.home = root / "home"
self.hermes_home = self.home / ".hermes"
operator = (_operator_home() / ".hermes").resolve()
assert operator not in (self.hermes_home.resolve(), *self.hermes_home.resolve().parents), (
f"sandbox {self.hermes_home} sits inside the operator's Hermes home")
- write_hermes_home(self.hermes_home, llm.base_url, extra_config=extra_config)
+ if llm is not None:
+ write_hermes_home(self.hermes_home, llm.base_url, extra_config=extra_config)
self.llm = llm
self.screen = Screen(rows, cols)
self.raw = bytearray()
diff --git a/tests/fakes/providers/codex_app_server.py b/tests/fakes/providers/codex_app_server.py
index 2f756027256..3586470f070 100644
--- a/tests/fakes/providers/codex_app_server.py
+++ b/tests/fakes/providers/codex_app_server.py
@@ -520,7 +520,8 @@ def _step_message(ctx: _TurnCtx, step: dict) -> None:
item_id, text = ctx.new_id(), step["text"]
ctx.started({"type": "agentMessage", "id": item_id, "text": ""})
size = max(1, len(text) // max(1, step.get("chunks", 3)))
- for start in range(0, len(text), size):
+ # ``deltas: False``: the item reaches item/completed with no item/agentMessage/delta before it.
+ for start in range(0, len(text), size) if step.get("deltas", True) else ():
ctx.server.notify("item/agentMessage/delta", ctx.scope(itemId=item_id, delta=text[start:start + size]))
ctx.completed({"type": "agentMessage", "id": item_id, "text": text})