Skip to content

fix(acp): emit agent text before the tool call it precedes - #6452

Merged
simonrosenberg merged 2 commits into
OpenHands:mainfrom
smolpaws:fix/acp-message-order
Nov 4, 2026
Merged

simonrosenberg merged 2 commits into
OpenHands:mainfrom
smolpaws:fix/acp-message-order

Conversation

@smolpaws

@smolpaws smolpaws commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

Engel's request in Slack (#proj-agent-canvas, replying to a report that Codex's commentary arrives out of order in Canvas):

let's repro this out of order issue: note that it's canvas UI, using codex cli via ACP, so an agent profile on codex cli. Keep codex on sub, so reusing our codex cli auth. Use control-openhands and verify-openhands as you know. Also test everything ACP (local), fix the map


AGENT:

Scope

This PR fixes the bug that was reproduced: Codex (ACP) narration showing after its tool calls in Canvas. The broader ACP checks and the feature-map coverage they need are a follow-up (Canvas verify-openhands map). Two separate bugs found during those checks are filed on their own: OpenHands/OpenHands#19313 (no Stop button while an ACP conversation started from Home runs) and #6453 (Codex threads lost on restart because CODEX_HOME is temporary).

Why

In Agent Canvas, a Codex (ACP) turn shows its narration in the wrong place. The agent writes "let me look at this file", "let me run foo" before each command, but Canvas shows every command first and all of that text glued together at the end of the turn. A reload moves text that appeared in place while streaming down to the end (OpenHands/OpenHands#15606).

Cause: _OpenHandsACPBridge appends every AgentMessageChunk to one per-turn buffer, and _finalize_successful_turn emits that buffer once, as the turn's FinishAction. Tool calls are emitted live from session_update. So the persisted order is always: all tool calls, then all text.

Summary

  • When a ToolCallStart arrives, the bridge emits the text and thoughts said since the previous segment as an agent MessageEvent (masked again after joining), before that tool call's event. The FinishAction carries the text after the last tool call. A turn without tool calls is unchanged: one FinishAction with all its text.
  • StreamContext.next_item() retires the slot that streamed a segment and opens a new one. The new slot anchors on the event log when its first token arrives, so later text streams below the tool calls instead of growing at the top of the turn.
  • If the agent says nothing after its last tool call, the FinishAction message is empty; the (No response from ACP server) placeholder remains for turns with no text at all.

Issue Number

Fixes #6454. Also fixes OpenHands/OpenHands#15606. Reported in Slack (#proj-agent-canvas), Codex via ACP.

How to Test

Unit (red on main, green here): uv run pytest tests/sdk/agent/test_acp_message_order.py. The tests drive real acp.schema updates through session_update into ACPAgent.step and check event order, the finish text, thoughts placement and stream slot ids/anchors.

Live, Agent Canvas main (01d1970b8f) with Codex ACP (@agentclientprotocol/codex-acp@2.2.2, ChatGPT subscription auth, gpt-6-luna/low), started through the UI with the verify-openhands harness. Prompt: before each of ls, cat README.md, echo verify-order, say what you are about to do; then summarise.

Before, Agent Server 1.59.0 (released) events:

ACPToolCallEvent ×6
ActionEvent(finish): "I’m about to list the repository files with `ls`.I’m about to display `README.md` with `cat`.I’m about to run `echo verify-order`.Completed the three steps…"

After, this branch (--sdk-path), same prompt, events and page text (identical after reload):

MessageEvent agent: I’m about to list the files in this repository with `ls`.
ACPToolCallEvent ×2   (ls)
MessageEvent agent: I’m about to display `README.md` with `cat`.
ACPToolCallEvent ×2   (cat)
MessageEvent agent: I’m about to run the requested `echo verify-order` command.
ACPToolCallEvent ×2   (echo)
ActionEvent(finish): Listed the files (`README.md`, `src`), displayed `README.md`, and ran `echo verify-order`. No files were edited.

Wider suites: tests/sdk/agent, tests/sdk/conversation, tests/agent_server show the same failures with and without this change on this machine (environment-related; the OpenAPI tests that differed under xdist pass when run serially).

Video/Screenshots

Same prompt, same Canvas build (main), Codex ACP 2.2.2 on gpt-6-luna: before with Agent Server 1.59.0, after with this branch. Each run ends with a page reload. 52 s, sped up 1.4×.

Before: tool calls first, narration glued at the end. After: each sentence right before its command.

MP4 with sound


This PR was created by an AI agent (OpenHands / smolpaws) on behalf of Engel Nyst.

An ACP turn collected every agent message chunk into one buffer and only
emitted it as the turn's FinishAction, while tool calls streamed live. A
Codex turn that narrates each step therefore showed all of its narration
after all of its tool calls, and a reloaded conversation moved live text
to the end of the turn.

Text and thoughts said before a tool call are now emitted as an agent
MessageEvent just before that call. The FinishAction carries what the
agent said after its last tool call. Each segment streams in its own slot:
StreamContext.next_item() opens a new one anchored after the events
emitted in between.

Fixes OpenHands/OpenHands#15606

Co-authored-by: openhands <openhands@all-hands.dev>
@smolpaws
smolpaws marked this pull request as ready for review November 4, 2026 06:58
@enyst
enyst requested a review from all-hands-bot November 4, 2026 06:59

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Scope and ownership: the ACP bridge and event emission live in this repository (the Canvas symptom is downstream), so this is the right place for the change, and the fix matches the root cause described in OpenHands/OpenHands#15606.

Verified on head a239d443:

  • uv run pytest tests/sdk/agent/test_acp_message_order.py — 5 passed; tests/sdk/agent/test_acp_agent.py, tests/sdk/conversation/test_agent_final_response.py, tests/sdk/agent/test_stream_context.py — 521 passed.
  • Traced the stream-slot lifecycle through the retry paths (new_attempt), cancellation (close/claim/commit ordering in _emit_text_segment), and the no-tool-call turn — behavior stays consistent with main, including masking at the segment boundary.
  • CI on this exact head is green except Validate PR description, which fails only the linked-issue readiness gate (OpenHands/OpenHands#15606 currently carries bug, openhands, feature-map:mapped but not ready-for-dev). That is deterministic-automation territory, not a code defect.

Material finding — the final-response surface loses agent text for empty-tail turns (detailed inline on openhands-sdk/openhands/sdk/agent/acp_agent.py:3944):

The change intentionally lets a turn end with FinishAction(message="") when the agent says nothing after its last tool call, and get_agent_final_response (openhands-sdk/openhands/sdk/conversation/response_utils.py) returns the FinishAction message with no empty-string fallback. I reproduced in-process that for the new event sequence it returns "" even though the turn contains agent text in MessageEvent segments. Concretely:

  • GET /api/conversations/{id}/agent_final_response (AgentResponseResult, mirrored in clients/typescript/), and
  • the OpenAI-compatible gateway (openhands-agent-server/openhands/agent_server/openai/service.py → OpenAIAgentRunResult.final_response → chat-completion assistant content)

now return "" for this class of turns, where on main they returned the joined (misordered but non-empty) turn text. That is a demonstrated regression on a documented REST/gateway compatibility surface, introduced by this diff in exactly the scenario the PR targets. A small fix would be to fall back to the last agent MessageEvent when the FinishAction message is empty, or to keep the tail segment in the finish text.

Everything else in the diff — segment masking, slot retirement via claim/commit/next_item, deferred anchoring, and the tests driving real acp.schema updates — looks sound.

🔄 CHANGES REQUESTED

Fall back to the last agent message after an empty finish, stopping at user or finish boundaries so previous turns cannot supply stale text.

Co-authored-by: openhands <openhands@all-hands.dev>

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Re-reviewed the new head e982064d, which fixes the final-response regression reported on the previous head (a239d443): empty-finish ACP turns now fall back to the last agent MessageEvent within the same turn.

Verification on this head:

  • The fallback in get_agent_final_response is correctly bounded: a user MessageEvent boundary and an older finish ActionEvent both stop the search, so the fallback can never surface a previous turn's text. The (No response from ACP server) placeholder keeps the finish message non-empty for silent turns, so the fallback only fires when real same-turn text exists. Non-ACP conversations with an empty finish also benefit, within the endpoint's documented "FinishAction message or the last agent MessageEvent" contract.
  • Focused tests: tests/sdk/agent/test_acp_message_order.py + tests/sdk/conversation/test_agent_final_response.py — 20 passed, including the new end-to-end assertion (get_agent_final_response(events) == "Checking." through the real ACPAgent.step path) and the parametrized boundary tests. Surrounding suites (tests/sdk/agent/test_acp_agent.py, tests/sdk/agent/test_stream_context.py) — 511 passed.
  • GitHub Actions on this exact head: all 30 check runs succeeded, including sdk-tests, agent-server-tests, acp-live-tests, cross-tests, Check OpenAPI Schema, and the multi-OS build-binary-and-test jobs. The earlier "Validate PR description" failure is resolved; the linked issue #6454 currently carries ready-for-dev and priority:high.
  • No schema change, so no TypeScript/OpenAPI regeneration is needed; both contract checks are green.

No material findings on this head. The ACP segment emission, stream-slot retirement (claim/commit/next_item), deferred anchoring, and masking behavior reviewed earlier are unchanged here.

✅ APPROVED

@simonrosenberg
simonrosenberg merged commit 102980d into OpenHands:main Nov 4, 2026
39 of 40 checks passed
enyst pushed a commit that referenced this pull request Nov 8, 2026
- S19: drive profile resolution through openhands.sdk.launch
  (resolve/finalize/preview_launch); settings schema v10; moved unit test.
- S09: the test MCP server sends tools/list_changed inside the request
  (fastmcp 4 drops it afterwards); the mcp 2 client reports a 503 as
  "Server returned an error response"; refresh the session-recovery
  known failure's messages.
- S04: fork(title=) no longer warns (1.60); drop that check.
- S21: since #6452 pre-tool-call thoughts ride their own agent message;
  check them there.
- Map baseline c76d305 (2026-11-03).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013ArwwLKWzfpSTpRccheeWP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ACP agent text is emitted after all of the turn's tool calls [Bug]: When re-loading ACP conversations, messages disappear or move

4 participants