Skip to content

The agent that grows with you

fix(acp): stream live reasoning to editors on the gateway path

putis6b9e0a16a995
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 67f09b91c45..8fe4a300a1d 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -239,10 +239,28 @@ class GatewayACPAgent(acp.Agent):
self._snapshots.pop(session_id, None)
continue
self._snapshots[session_id] = snapshot
+ # Before this session's cards are offered again: until ``_client`` returns, ``self._gateway`` is
+ # not this connection, so a card answered while the request is out would lose its answer.
+ await self._request_live_reasoning(gateway, session_id)
for pending in snapshot.get("prompts", []):
self._permission(session_id, pending)
await self._notify_unknown(session_id)
+ async def _request_live_reasoning(self, client, session_id):
+ """Ask the owner to stream this session's reasoning (``show_reasoning``), as the CLI does.
+
+ The in-process server gave every editor turn a reasoning sink (``acp_adapter/server.py``). The
+ owner publishes ``reasoning.delta`` only for a live session whose flag a viewer set, and a restarted
+ owner's sessions start without it, so every attach and re-attach asks (#134889 ACP-4). The flag is
+ the session's: a viewer that hides reasoning later turns it off until the editor attaches again."""
+ try:
+ await client.rpc("config.set", session_id=session_id, key="show_reasoning", value="1", _timeout=10)
+ except Exception:
+ # Boundary: a display flag must not fail the attach (a refusal, a lost connection, or no answer
+ # within the CLI's 10 s). At worst the session runs without live reasoning; a reconnect's
+ # re-attach asks again.
+ logger.debug("ACP session %s keeps its reasoning hidden", session_id, exc_info=True)
+
async def _notify_unknown(self, session_id):
"""The classic chat's resume notice: say why the next prompt will be refused and how to recover."""
if self._has_unknown(session_id) and self._conn:
@@ -299,6 +317,7 @@ class GatewayACPAgent(acp.Agent):
self._editor_mcp[session_id] = {
"mcp_servers": [s.model_dump(by_alias=True) for s in mcp_servers]}
info = snapshot.get("info") or await client.rpc("session.info", session_id=session_id)
+ await self._request_live_reasoning(client, session_id)
return NewSessionResponse(session_id=session_id, **await self._session_fields(session_id, info, session_id))
def _editor_id(self, session_id):
@@ -386,6 +405,7 @@ class GatewayACPAgent(acp.Agent):
for pending in snapshot.get("prompts", []):
self._permission(session_id, pending)
await self._notify_unknown(session_id)
+ await self._request_live_reasoning(client, session_id)
return await self._session_fields(session_id, {**info, **(snapshot.get("info") or {})}, held_id)
@staticmethod
@@ -468,6 +488,7 @@ class GatewayACPAgent(acp.Agent):
self._editor_mcp[child] = payload or self._editor_mcp[session_id]
self._mutations.acknowledge(session_id, 'branch', payload)
info = self._snapshots[child].get('info') or await client.rpc('session.info', session_id=child)
+ await self._request_live_reasoning(client, child)
return ForkSessionResponse(session_id=child, **await self._session_fields(child, info, child))
async def set_session_model(self, model_id, session_id, **kwargs):
@@ -728,6 +749,9 @@ class GatewayACPAgent(acp.Agent):
if task:
task.cancel()
return
+ if kind == "reasoning.delta":
+ await self._project_reasoning(editor_id, payload)
+ return
# In-process turns publish ``tool_name``; managed workers publish ``name``.
tool_name = payload.get("tool_name") or payload.get("name") or "tool"
if kind == "tool.start":
@@ -785,6 +809,13 @@ class GatewayACPAgent(acp.Agent):
finally:
self._settling.discard(aid)
+ async def _project_reasoning(self, editor_id, payload):
+ """The model's reasoning as thought chunks, as the in-process server streamed it. It never enters the
+ reply's segments, so ``message.complete``'s final remainder is unchanged."""
+ text = _text(payload)
+ if text and self._conn:
+ await self._conn.session_update(session_id=editor_id, update=acp.update_agent_thought_text(text))
+
async def _project_session_state(self, kind, sid, editor_id, payload):
if kind == "session.usage":
await self._project_usage(sid, editor_id, payload)
diff --git a/tests/acp_adapter/test_gateway_compressed_reopen.py b/tests/acp_adapter/test_gateway_compressed_reopen.py
index fba7f426742..247f49588ad 100644
--- a/tests/acp_adapter/test_gateway_compressed_reopen.py
+++ b/tests/acp_adapter/test_gateway_compressed_reopen.py
@@ -16,7 +16,7 @@ class _Bridge:
def __init__(self, connection):
self.connection, self.events = connection, asyncio.Queue()
- async def rpc(self, method, **params):
+ async def rpc(self, method, _timeout=None, **params): # the client budget is never on the wire
from hermes_cli.gateway_client import GatewayClientError
reply = await self.connection.dispatch({'id': 1, 'method': method, 'params': params})
if 'error' in reply:
diff --git a/tests/acp_adapter/test_gateway_launch_flags.py b/tests/acp_adapter/test_gateway_launch_flags.py
index ea503a6e3e4..d121f70360d 100644
--- a/tests/acp_adapter/test_gateway_launch_flags.py
+++ b/tests/acp_adapter/test_gateway_launch_flags.py
@@ -15,6 +15,8 @@ def _agent(created):
async def rpc(method, **params):
if method == 'runtime.describe':
return {'session_create': {'sources': ['acp']}, 'capabilities': ['acp-editor-policy-v1']}
+ if method == 'config.set': # the new session's live-reasoning flag (#134889 ACP-4)
+ return {'key': params['key'], 'value': params['value'], 'scope': 'session'}
assert method == 'session.create', method
created.append(params)
return {'session_id': 's', 'info': {'cwd': params['cwd']}}
diff --git a/tests/acp_adapter/test_gateway_prompt_reoffer.py b/tests/acp_adapter/test_gateway_prompt_reoffer.py
index 3669421ab31..57b113add81 100644
--- a/tests/acp_adapter/test_gateway_prompt_reoffer.py
+++ b/tests/acp_adapter/test_gateway_prompt_reoffer.py
@@ -37,6 +37,8 @@ class Gateway:
async def rpc(self, method, **params):
if method == "session.resume":
return {"session_id": params["session_id"], "prompts": [self.prompt], "pending": []}
+ if method == "config.set": # the editor's live-reasoning flag on every (re)attach, never a respond
+ return {"key": params["key"], "value": params["value"], "scope": "session"}
self.responses.append((method, params.get("choice", params.get("answer"))))
if self.lose:
self.lose = False
diff --git a/tests/acp_adapter/test_gateway_queued_unknown.py b/tests/acp_adapter/test_gateway_queued_unknown.py
index 9414b2c4ff4..97046cf9b49 100644
--- a/tests/acp_adapter/test_gateway_queued_unknown.py
+++ b/tests/acp_adapter/test_gateway_queued_unknown.py
@@ -61,7 +61,7 @@ async def test_resumed_unknown_turn_names_the_existing_discard_recovery():
agent._conn = AsyncMock()
lost = 'admission-lost-0123456789abcdef'
agent._gateway.rpc.side_effect = lambda method, **params: {
- 'session.info': {}, 'session.resume': {
+ 'session.info': {}, 'config.set': {}, 'session.resume': {
'session_id': 's', 'messages': [], 'prompts': [],
'pending': [{'admission_id': lost, 'status': 'unknown', 'execution_generation': 4}]},
}[method]
@@ -73,7 +73,9 @@ async def test_resumed_unknown_turn_names_the_existing_discard_recovery():
assert 'chat --cli --resume s' in text and f'/discard {lost}' in text, text
assert 'do not resend' in text
assert 'nothing was submitted' in str(refused.value)
- assert [call.args[0] for call in agent._gateway.rpc.await_args_list] == ['session.info', 'session.resume']
+ # The load's own RPCs only (the session's reasoning flag included): no prompt.submit.
+ asked = [call.args[0] for call in agent._gateway.rpc.await_args_list]
+ assert asked == ['session.info', 'session.resume', 'config.set']
@pytest.mark.asyncio
diff --git a/tests/acp_adapter/test_gateway_reasoning.py b/tests/acp_adapter/test_gateway_reasoning.py
new file mode 100644
index 00000000000..a7bedeec9f0
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_reasoning.py
@@ -0,0 +1,163 @@
+"""Live reasoning for editors on the gateway path (#134889 ACP-4).
+
+The in-process server (``acp_adapter/server.py``) gave every editor turn a reasoning sink and streamed it as
+``agent_thought_chunk``. On the gateway path the owner publishes ``reasoning.delta`` only for a live session
+whose ``show_reasoning`` flag a viewer set (``gateway/local_viewer_events.py``), so the editor asks for it on
+every attach. The end-to-end test runs an actual ``hermes acp`` stdio process against an ordinary isolated
+gateway and a provider that reasons before it answers.
+"""
+import asyncio
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from acp.schema import AllowedOutcome
+from websockets.exceptions import ConnectionClosed
+
+from acp_adapter.gateway_server import GatewayACPAgent
+from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
+from tests.acp_adapter.test_gateway_sessions import editor, viewer
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text
+
+REASONING = "REASONING-BEFORE-THE-ANSWER"
+ANSWER = "THE-ANSWER"
+# A card the owner still lists for the session: an attach that resumes the session offers it to the editor again.
+CARD = {"kind": "approval", "prompt_id": "p-1", "execution_generation": 3, "command": "rm -r build",
+ "description": "remove the build directory", "choices": ["once", "deny"]}
+
+
+def model_peer():
+ """The daemon's provider: each of the test's three turns streams its reasoning before its answer."""
+ with FakeLLMServer([Text(ANSWER, reasoning=REASONING) for _ in range(3)]) as provider:
+ yield SimpleNamespace(server_port=provider.port)
+
+
+async def _turn(acp, sid):
+ """One prompt; the editor must get the reasoning live, as thought chunks before the answer starts."""
+ start = len(acp.frames)
+ response = await acp.rpc("session/prompt", sessionId=sid, prompt=[{"type": "text", "text": "think first"}])
+ assert response.get("result", {}).get("stopReason") == "end_turn", response
+ updates = [frame["params"]["update"] for frame in acp.frames[start:]
+ if frame.get("method") == "session/update" and frame["params"].get("sessionId") == sid]
+ chunks = [(update["sessionUpdate"], update["content"]["text"]) for update in updates
+ if update.get("sessionUpdate") in ("agent_thought_chunk", "agent_message_chunk")]
+ kinds = [kind for kind, _ in chunks]
+ assert "".join(text for kind, text in chunks if kind == "agent_thought_chunk") == REASONING, chunks
+ assert "".join(text for kind, text in chunks if kind == "agent_message_chunk") == ANSWER, chunks
+ # The provider streams the reasoning first: a projection that held it back would land after the answer.
+ last_thought = max(index for index, kind in enumerate(kinds) if kind == "agent_thought_chunk")
+ assert last_thought < kinds.index("agent_message_chunk"), chunks
+
+
+async def test_every_session_the_editor_attaches_streams_its_reasoning_live(daemon, tmp_path):
+ async with viewer(daemon) as ws, editor(daemon, tmp_path) as acp:
+ await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})
+ created = await acp.rpc("session/new", cwd=str(tmp_path), mcpServers=[])
+ await _turn(acp, created["result"]["sessionId"])
+ # Sessions another client opened over a raw viewer socket, which never asks for reasoning.
+ to_load, to_fork = [
+ (await ws.rpc("session.create", request_id=name, source="cli", cwd=str(tmp_path)))["session_id"]
+ for name in ("to-load", "to-fork")]
+ loaded = await acp.rpc("session/load", sessionId=to_load, cwd=str(tmp_path), mcpServers=[])
+ assert "result" in loaded, loaded
+ await _turn(acp, to_load)
+ forked = await acp.rpc("session/fork", sessionId=to_fork, cwd=str(tmp_path), mcpServers=[])
+ await _turn(acp, forked["result"]["sessionId"])
+
+
[email protected]("attach", ["new", "load", "resume", "fork", "reconnect"])
[email protected]("failure", [None, GatewayRPCError("not_found"), GatewayClientError("Gateway disconnected"),
+ ConnectionClosed(None, None), TimeoutError()],
+ ids=["set", "refused", "reply-lost", "socket-closed", "unanswered"])
+async def test_an_attach_asks_for_live_reasoning_before_it_replies_and_never_fails_on_it(monkeypatch, attach, failure):
+ # The owner runs the conversation as "logical"; a load or resume may hold another id for it (a compressed
+ # chain's), and a fork holds its child.
+ monkeypatch.setattr("acp_adapter.catalog.logical_session_id", lambda db, held: "logical")
+ agent = GatewayACPAgent()
+ agent._conn = AsyncMock()
+ agent._conn.request_permission.side_effect = lambda session_id, tool_call, options: SimpleNamespace(
+ outcome=AllowedOutcome(outcome="selected", option_id=options[0].option_id)) # answers every card at once
+ asked = []
+ done = {"request": False} # the flag request has finished (answered, refused or given up)
+
+ async def rpc(method, **params):
+ asked.append((method, params))
+ if method == "config.set":
+ try:
+ for _ in range(3): # the owner's round trip: a card offered before it is answered meanwhile
+ await asyncio.sleep(0)
+ if failure is not None:
+ raise failure
+ finally:
+ done["request"] = True
+ return {"runtime.describe": {"session_create": {"sources": ["acp"]}, "capabilities": ["acp-editor-policy-v1"],
+ "profile_id": str(agent._home)},
+ "session.create": {"session_id": "logical", "info": {"cwd": "/"}},
+ "session.info": {"cwd": "/"},
+ "session.resume": {"session_id": params.get("session_id"), "messages": [], "prompts": [CARD],
+ "pending": [], "execution_generation": 3, "revision": 1},
+ "session.mutate": {"status": "committed", "branched_session_id": "child"},
+ "config.set": {"key": "show_reasoning", "value": "1", "scope": "session"},
+ "approval.respond": {"status": "resolved"}}[method]
+
+ owner = AsyncMock(events=asyncio.Queue())
+ owner.rpc.side_effect = rpc
+ agent._gateway = owner
+ session_fields = agent._session_fields
+
+ async def reply_fields(*args, **kwargs): # every attach but the re-attach builds its reply here
+ done.setdefault("at_reply", done["request"])
+ return await session_fields(*args, **kwargs)
+
+ agent._session_fields = reply_fields
+ if attach == "new":
+ held = (await agent.new_session(cwd="/")).session_id
+ elif attach in ("load", "resume"):
+ held = "held"
+ await getattr(agent, f"{attach}_session")(cwd="/", session_id=held)
+ elif attach == "fork":
+ held = (await agent.fork_session(cwd="/", session_id="parent")).session_id
+ else: # the gateway restarted: the editor's next call reconnects and re-attaches the session it holds
+ agent._gateway, agent._snapshots["logical"], held = None, {}, "logical"
+
+ @asynccontextmanager
+ async def connect_gateway():
+ yield owner
+
+ monkeypatch.setattr("acp_adapter.gateway_server.connect_gateway", connect_gateway)
+ await agent._client()
+ owner_id = "child" if attach == "fork" else "logical"
+ try:
+ # Asked for the session the owner runs, waiting at most the CLI's 10 s, and finished before the attach
+ # replied; at worst a failure costs the live reasoning, never the session.
+ assert ("config.set", {"session_id": owner_id, "key": "show_reasoning", "value": "1", "_timeout": 10}) in asked
+ assert done.get("at_reply", True), "the attach replied before its request finished"
+ assert owner_id in agent._snapshots, "the attach dropped the session"
+ for _ in range(5): # the cards the attach offered settle
+ await asyncio.gather(*agent._permissions.values(), return_exceptions=True)
+ await asyncio.sleep(0)
+ offered = 1 if attach in ("load", "resume", "reconnect") else 0 # the owner's pending card comes back
+ assert agent._conn.request_permission.await_count == offered, "the card was not offered"
+ answers = [method for method, _ in asked if method == "approval.respond"]
+ assert len(answers) == offered, "the editor's answer to a card was lost"
+ # Thoughts, a lone line break too, reach the id the editor holds, outside the reply, even between two
+ # parts of the answer.
+ for kind, payload in [("message.delta", {"text": "AN"}), ("reasoning.delta", {"text": "thinking"}),
+ ("reasoning.delta", {"text": "\n"}), ("message.delta", {"text": "SWER"}),
+ ("message.complete", {"text": "ANSWER", "outcome": "completed"})]:
+ await agent._project({"session_id": owner_id, "type": kind, "admission_id": "a1", "payload": payload})
+ updates = [(call.kwargs["session_id"], call.kwargs["update"])
+ for call in agent._conn.session_update.await_args_list]
+ reply = "".join(update.content.text for _, update in updates if update.session_update == "agent_message_chunk")
+ thoughts = [(sid, update.content.text) for sid, update in updates
+ if update.session_update == "agent_thought_chunk"]
+ assert (reply, thoughts) == ("ANSWER", [(held, "thinking"), (held, "\n")])
+ finally:
+ if agent._event_task:
+ agent._event_task.cancel()
+ await asyncio.gather(agent._event_task, return_exceptions=True)
diff --git a/tests/acp_adapter/test_gateway_reconnect.py b/tests/acp_adapter/test_gateway_reconnect.py
index e56b0a29bdb..85769bd865f 100644
--- a/tests/acp_adapter/test_gateway_reconnect.py
+++ b/tests/acp_adapter/test_gateway_reconnect.py
@@ -19,7 +19,7 @@ class Owner:
def __init__(self, profile_id, epoch, *, die_on_submit=None):
self.profile_id, self.epoch, self.die_on_submit = profile_id, epoch, die_on_submit
- self.calls = []
+ self.calls, self.configs = [], []
self.server = None
async def handler(self, ws):
@@ -27,6 +27,8 @@ class Owner:
frame = json.loads(raw)
method, params = frame["method"], frame["params"]
self.calls.append(method)
+ if method == "config.set":
+ self.configs.append(params)
if method == "prompt.submit" and self.die_on_submit == "before_ack":
await ws.close() # the owner dies with the submit in flight
return
@@ -77,9 +79,11 @@ async def test_editor_reconnects_to_a_restarted_gateway_without_resending(monkey
response = await asyncio.wait_for(agent.prompt([acp.text_block("after restart")], "s"), 5)
assert response.stop_reason == "end_turn"
assert agent._failure is None
- # The replacement was re-verified and re-subscribed before the new submit; the
- # lost input was submitted to the first owner only.
- assert owners[1].calls == ["runtime.describe", "session.resume", "prompt.submit"]
+ # The replacement was re-verified and re-subscribed before the new submit, and asked again
+ # for the session's live reasoning: a restarted owner's live session starts without that
+ # flag (ACP-4). The lost input was submitted to the first owner only.
+ assert owners[1].calls == ["runtime.describe", "session.resume", "config.set", "prompt.submit"]
+ assert owners[1].configs == [{"session_id": "s", "key": "show_reasoning", "value": "1"}]
assert owners[0].calls.count("prompt.submit") == 1
assert agent._snapshots["s"]["replay_epoch"] == "second"
texts = [call.kwargs["update"].content.text for call in agent._conn.session_update.await_args_list
diff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.py
index fa6de40b395..63b6f742c5b 100644
--- a/tests/gateway/test_session_mutation_model.py
+++ b/tests/gateway/test_session_mutation_model.py
@@ -90,7 +90,7 @@ def test_model_receipt_changes_next_wire_and_branch_keeps_independent_history(tm
from hermes_cli.gateway_chat_view import GatewayChatView
from acp_adapter.gateway_server import GatewayACPAgent
class Client:
- async def rpc(self, method, **kwargs):
+ async def rpc(self, method, _timeout=None, **kwargs): # the client budget is never on the wire
return await call(method, **kwargs)
client = Client()
view = GatewayChatView(client, before)