fix(codex): dedupe streamed app-server items
This commit is contained in:
parent
07b542ebb9
commit
108b24f5ec
|
|
@ -439,7 +439,9 @@ def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]:
|
|||
"tool.completed", name, None, None, duration=..., is_error=...,
|
||||
result=...)``
|
||||
* ``item/agentMessage/delta`` → ``_fire_stream_delta(text)`` so chat
|
||||
adapters can render the assistant's reply as it streams.
|
||||
adapters can render the assistant's reply as it streams. Successfully
|
||||
delivered visible text is tracked per ``itemId`` for completion-time
|
||||
de-duplication.
|
||||
* ``item/reasoning/delta`` → ``_fire_reasoning_delta(text)``
|
||||
* ``item/completed`` for ``agentMessage`` →
|
||||
``_emit_interim_assistant_message({"role": "assistant",
|
||||
|
|
@ -455,6 +457,7 @@ def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]:
|
|||
# item/started and consumed on item/completed so duration is correct
|
||||
# even when codex doesn't report durationMs.
|
||||
started: dict[str, tuple[str, dict, float]] = {}
|
||||
streamed_agent_messages: dict[str, str] = {}
|
||||
|
||||
def _stable_call_id(item: dict, name: str) -> str:
|
||||
"""Deterministic tool_call id mirroring CodexEventProjector, so a
|
||||
|
|
@ -547,10 +550,18 @@ def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]:
|
|||
fn = getattr(agent, "_fire_stream_delta", None)
|
||||
if fn is None:
|
||||
return
|
||||
before = getattr(agent, "_current_streamed_assistant_text", "") or ""
|
||||
try:
|
||||
fn(text)
|
||||
except Exception:
|
||||
logger.debug("_fire_stream_delta raised", exc_info=True)
|
||||
return
|
||||
after = getattr(agent, "_current_streamed_assistant_text", "") or ""
|
||||
item_id = params.get("itemId") or ""
|
||||
if item_id and after.startswith(before) and len(after) > len(before):
|
||||
streamed_agent_messages[item_id] = (
|
||||
streamed_agent_messages.get(item_id, "") + after[len(before) :]
|
||||
)
|
||||
|
||||
def _fire_reasoning_delta(params: dict) -> None:
|
||||
text = params.get("delta") or params.get("text") or ""
|
||||
|
|
@ -566,6 +577,8 @@ def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]:
|
|||
|
||||
def _fire_agent_message_completed(item: dict) -> None:
|
||||
text = item.get("text") or ""
|
||||
item_id = item.get("id") or ""
|
||||
streamed_text = streamed_agent_messages.pop(item_id, "")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return
|
||||
# display.show_commentary=false — mid-turn narration stays off the
|
||||
|
|
@ -576,8 +589,21 @@ def make_codex_app_server_event_bridge(agent) -> Callable[[dict], None]:
|
|||
emit = getattr(agent, "_emit_interim_assistant_message", None)
|
||||
if emit is None:
|
||||
return
|
||||
normalize = getattr(agent, "_normalize_interim_visible_text", None)
|
||||
if callable(normalize):
|
||||
visible_text = normalize(text)
|
||||
visible_streamed_text = normalize(streamed_text)
|
||||
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)
|
||||
)
|
||||
try:
|
||||
emit({"role": "assistant", "content": text})
|
||||
emit(
|
||||
{"role": "assistant", "content": text},
|
||||
already_streamed=already_streamed,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug(
|
||||
"_emit_interim_assistant_message raised", exc_info=True,
|
||||
|
|
|
|||
|
|
@ -5062,7 +5062,10 @@ class AIAgent:
|
|||
logger.debug("interim_assistant_callback error", exc_info=True)
|
||||
|
||||
def _emit_interim_assistant_message(
|
||||
self, assistant_msg: Dict[str, Any]
|
||||
self,
|
||||
assistant_msg: Dict[str, Any],
|
||||
*,
|
||||
already_streamed: Optional[bool] = None,
|
||||
) -> None:
|
||||
"""Surface a real mid-turn assistant commentary message to the UI layer.
|
||||
|
||||
|
|
@ -5101,7 +5104,8 @@ class AIAgent:
|
|||
or self._interim_text_was_delivered(visible)
|
||||
):
|
||||
return
|
||||
already_streamed = self._interim_content_was_streamed(visible)
|
||||
if already_streamed is None:
|
||||
already_streamed = self._interim_content_was_streamed(visible)
|
||||
try:
|
||||
cb(visible, already_streamed=already_streamed)
|
||||
if undelivered_parts:
|
||||
|
|
|
|||
|
|
@ -441,9 +441,61 @@ class TestAgentMessageInterimDispatch:
|
|||
"text": "I'll check the config first.",
|
||||
}))
|
||||
agent._emit_interim_assistant_message.assert_called_once_with(
|
||||
{"role": "assistant", "content": "I'll check the config first."}
|
||||
{"role": "assistant", "content": "I'll check the config first."},
|
||||
already_streamed=False,
|
||||
)
|
||||
|
||||
def test_distinct_streamed_items_settle_against_their_own_deltas(self):
|
||||
delivered = []
|
||||
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,
|
||||
)
|
||||
agent._emit_interim_assistant_message = (
|
||||
lambda message, **kwargs: delivered.append((message["content"], kwargs))
|
||||
)
|
||||
agent._normalize_interim_visible_text = lambda text: " ".join(text.split())
|
||||
bridge = make_codex_app_server_event_bridge(agent)
|
||||
|
||||
bridge(
|
||||
{
|
||||
"method": "item/agentMessage/delta",
|
||||
"params": {"itemId": "commentary", "delta": "Checking first."},
|
||||
}
|
||||
)
|
||||
bridge(
|
||||
_item_completed(
|
||||
{
|
||||
"type": "agentMessage",
|
||||
"id": "commentary",
|
||||
"text": "Checking first.",
|
||||
}
|
||||
)
|
||||
)
|
||||
bridge(
|
||||
{
|
||||
"method": "item/agentMessage/delta",
|
||||
"params": {"itemId": "final", "delta": "Done."},
|
||||
}
|
||||
)
|
||||
bridge(
|
||||
_item_completed(
|
||||
{
|
||||
"type": "agentMessage",
|
||||
"id": "final",
|
||||
"text": "Done.",
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
assert delivered == [
|
||||
("Checking first.", {"already_streamed": True}),
|
||||
("Done.", {"already_streamed": True}),
|
||||
]
|
||||
|
||||
def test_empty_text_does_not_emit_interim(self):
|
||||
agent = _make_stub_agent()
|
||||
bridge = make_codex_app_server_event_bridge(agent)
|
||||
|
|
|
|||
|
|
@ -168,6 +168,62 @@ class TestRunConversationCodexPath:
|
|||
assert result["final_response"] == "Done."
|
||||
assert result["response_previewed"] is False
|
||||
|
||||
def test_distinct_streamed_items_are_each_rendered_once(self, monkeypatch):
|
||||
def fake_run_turn(self, user_input: str, **kwargs):
|
||||
for item_id, text in (
|
||||
("commentary-message", "I'll inspect it first."),
|
||||
("final-message", "Done."),
|
||||
):
|
||||
self._on_event(
|
||||
{
|
||||
"method": "item/agentMessage/delta",
|
||||
"params": {"itemId": item_id, "delta": text},
|
||||
}
|
||||
)
|
||||
self._on_event(
|
||||
{
|
||||
"method": "item/completed",
|
||||
"params": {
|
||||
"item": {
|
||||
"type": "agentMessage",
|
||||
"id": item_id,
|
||||
"text": text,
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
return TurnResult(
|
||||
final_text="Done.",
|
||||
projected_messages=[{"role": "assistant", "content": "Done."}],
|
||||
turn_id="turn-two-items-1",
|
||||
thread_id="thread-two-items-1",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(CodexAppServerSession, "run_turn", fake_run_turn)
|
||||
monkeypatch.setattr(
|
||||
CodexAppServerSession,
|
||||
"ensure_started",
|
||||
lambda self: "thread-two-items-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 == ["I'll inspect it first.", "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(
|
||||
|
|
|
|||
|
|
@ -2371,6 +2371,23 @@ def test_interim_commentary_is_not_marked_already_streamed_when_stream_callback_
|
|||
}
|
||||
|
||||
|
||||
def test_interim_commentary_accepts_per_item_streamed_override(monkeypatch):
|
||||
agent = _build_agent(monkeypatch)
|
||||
observed = {}
|
||||
agent.interim_assistant_callback = (
|
||||
lambda text, *, already_streamed=False: observed.update(
|
||||
{"text": text, "already_streamed": already_streamed}
|
||||
)
|
||||
)
|
||||
|
||||
agent._emit_interim_assistant_message(
|
||||
{"role": "assistant", "content": "final"},
|
||||
already_streamed=True,
|
||||
)
|
||||
|
||||
assert observed == {"text": "final", "already_streamed": True}
|
||||
|
||||
|
||||
def test_interim_content_was_streamed_matches_prefix_not_exact(monkeypatch):
|
||||
"""_interim_content_was_streamed should return True when the streamed text
|
||||
is a PREFIX of the final content (trailing delta added after stream, or
|
||||
|
|
|
|||
|
|
@ -411,10 +411,11 @@ Known limitations:
|
|||
- **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
|
||||
the last update exactly matches the final response, Hermes marks that response
|
||||
as already previewed so TUI and messaging clients settle it as one assistant
|
||||
message instead of rendering or sending it twice. Distinct mid-turn commentary
|
||||
remains separate.
|
||||
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.
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue