fix(codex): preserve streamed-message fallback

This commit is contained in:
Haider Sultan 2026-08-01 17:45:39 +08:00
parent 6331107909
commit 3cf6fb6848
4 changed files with 133 additions and 10 deletions

View File

@ -599,8 +599,10 @@ def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]:
else:
visible_text = " ".join(text.split())
visible_streamed_text = " ".join(streamed_text.split())
already_streamed = bool(
visible_streamed_text and visible_text.startswith(visible_streamed_text)
already_streamed = (
True
if visible_streamed_text and visible_text.startswith(visible_streamed_text)
else None
)
try:
emit(
@ -619,6 +621,9 @@ def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]:
params = note.get("params") or {}
if not isinstance(params, dict):
params = {}
if method in {"turn/completed", "turn/failed"}:
streamed_agent_messages.clear()
return
if method == "item/agentMessage/delta":
_fire_text_delta(params)
return

View File

@ -260,7 +260,7 @@ class TestAgentMessageInterimDispatch:
}))
agent._emit_interim_assistant_message.assert_called_once_with(
{"role": "assistant", "content": "I'll check the config first."},
already_streamed=False,
already_streamed=None,
)
def test_distinct_streamed_items_settle_against_their_own_deltas(self):
@ -314,6 +314,72 @@ class TestAgentMessageInterimDispatch:
("Done.", {"already_streamed": True}),
]
def test_missing_item_id_uses_turn_stream_fallback(self):
agent = _make_stub_agent()
agent._current_streamed_assistant_text = ""
agent._fire_stream_delta = lambda text: setattr(
agent,
"_current_streamed_assistant_text",
agent._current_streamed_assistant_text + text,
)
bridge = make_codex_app_server_event_bridge(agent)
bridge(
{
"method": "item/agentMessage/delta",
"params": {"delta": "Already visible."},
}
)
bridge(
_item_completed(
{
"type": "agentMessage",
"id": "final",
"text": "Already visible.",
}
)
)
agent._emit_interim_assistant_message.assert_called_once_with(
{"role": "assistant", "content": "Already visible."},
already_streamed=None,
)
@pytest.mark.parametrize("terminal_method", ["turn/completed", "turn/failed"])
def test_terminal_turn_event_clears_incomplete_item_buffers(
self, terminal_method
):
agent = _make_stub_agent()
agent._current_streamed_assistant_text = ""
agent._fire_stream_delta = lambda text: setattr(
agent,
"_current_streamed_assistant_text",
agent._current_streamed_assistant_text + text,
)
bridge = make_codex_app_server_event_bridge(agent)
bridge(
{
"method": "item/agentMessage/delta",
"params": {"itemId": "orphan", "delta": "Old turn."},
}
)
bridge({"method": terminal_method, "params": {}})
bridge(
_item_completed(
{
"type": "agentMessage",
"id": "orphan",
"text": "Old turn.",
}
)
)
agent._emit_interim_assistant_message.assert_called_once_with(
{"role": "assistant", "content": "Old turn."},
already_streamed=None,
)
def test_show_commentary_off_suppresses_interim(self):
"""display.show_commentary=false silences agentMessage interim
delivery on the app-server runtime (same contract as the

View File

@ -224,6 +224,59 @@ class TestRunConversationCodexPath:
assert visible == ["I'll inspect it first.", "Done."]
assert result["response_previewed"] is True
def test_streamed_final_without_item_id_is_rendered_once(self, monkeypatch):
def fake_run_turn(self, user_input: str, **kwargs):
final_text = "Done."
self._on_event(
{
"method": "item/agentMessage/delta",
"params": {"delta": final_text},
}
)
self._on_event(
{
"method": "item/completed",
"params": {
"item": {
"type": "agentMessage",
"id": "final-message",
"text": final_text,
}
},
}
)
return TurnResult(
final_text=final_text,
projected_messages=[{"role": "assistant", "content": final_text}],
turn_id="turn-no-item-id-1",
thread_id="thread-no-item-id-1",
)
monkeypatch.setattr(CodexAppServerSession, "run_turn", fake_run_turn)
monkeypatch.setattr(
CodexAppServerSession,
"ensure_started",
lambda self: "thread-no-item-id-1",
)
visible = []
def deliver_interim(text, *, already_streamed=False):
if not already_streamed:
visible.append(text)
agent = _make_codex_agent(
stream_delta_callback=visible.append,
interim_assistant_callback=deliver_interim,
)
with patch.object(agent, "_spawn_background_review", return_value=None):
result = agent.run_conversation("hello")
if not result["response_previewed"]:
visible.append(result["final_response"])
assert visible == ["Done."]
assert result["response_previewed"] is True
def test_codex_app_server_token_usage_updates_session_accounting(self, monkeypatch):
def fake_run_turn(self, user_input: str, **kwargs):
return TurnResult(

View File

@ -403,6 +403,12 @@ This runtime is **opt-in beta**. Working as of Hermes Agent 2026.5 + Codex CLI 0
- Memory and skill nudge counters (verified live via integration tests)
- Hermes web_search through codex (verified live: "OpenAI Codex CLI – Getting Started" returned end-to-end)
When `display.show_commentary` is enabled, completed app-server messages are
surfaced immediately as interim updates. When a completed message was already
streamed, Hermes marks it as previewed rather than rendering it a second time;
when the final response matches text already delivered this turn, the result
carries `response_previewed` so messaging clients skip the duplicate send.
Known limitations:
- **Hermes auth and codex auth are separate sessions.** You need both `codex login` AND `hermes auth add openai-codex` for the cleanest UX (the runtime uses codex's session for the LLM call). This is a deliberate design choice in Hermes' `_import_codex_cli_tokens` — Hermes won't share OAuth state with codex CLI to avoid clobbering each other on token refresh.
@ -410,13 +416,6 @@ Known limitations:
- **No inline patch preview in approval prompts when codex doesn't track the changeset.** Codex's `fileChange` approval params don't always carry the changeset. Hermes caches the data from the corresponding `item/started` notification when possible, but if approval arrives before the item has streamed, the prompt falls back to whatever `reason` codex provides.
- **Sub-second cancellation isn't guaranteed.** Mid-stream interrupts (Ctrl+C while codex is responding) are sent via `turn/interrupt`, but if codex has already flushed the final message, you get the response anyway.
Completed app-server messages are surfaced immediately as interim updates. When
an update was streamed, Hermes tracks its visible text by app-server item ID and
settles the matching completed item without rendering it again. When the last
completed update exactly matches the final response, Hermes also marks that
response as already previewed so messaging clients do not send it twice.
Distinct mid-turn commentary remains separate.
If you find a bug, [open an issue](https://github.com/NousResearch/hermes-agent/issues) with the output of `hermes logs --since 5m`. Mention `codex-runtime` in the title so it's easy to triage.
## Architecture