Skip to content

The agent that grows with you

fix(acp): list gateway editor threads, add config pickers, stop on cancel

unsupportedpastelsb2f9dee01a40
diff --git a/acp_adapter/catalog.py b/acp_adapter/catalog.py
index e2237a9f06d..dee1cc402b1 100644
--- a/acp_adapter/catalog.py
+++ b/acp_adapter/catalog.py
@@ -12,8 +12,12 @@ def read_catalog_rows(path):
path = Path(path)
if not path.exists():
return {}
+ from hermes_cli.gateway_session_store import SurfaceLabelReader
+ # The owner stores an editor thread as ``local`` with ``created_source='acp'``; the surface
+ # reader matches both labels in SQL, before the LIMIT.
with SessionDB(db_path=path, read_only=True) as db:
- return {str(row["id"]): dict(row) for row in db.list_sessions_rich(source="acp", limit=1000)}
+ rows = SurfaceLabelReader(db).list_sessions_rich(source="acp", limit=1000)
+ return {str(row["id"]): dict(row) for row in rows}
def _local_owners(db):
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index d539cfead80..1bfef1c9d20 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -297,7 +297,7 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
async def _session_fields(self, session_id, info, editor_id):
"""Main's new/load/resume/fork reply fields (model picker, modes, provenance ``_meta``); the
command list and context indicator follow once the reply is queued, as main scheduled them."""
- from acp_adapter.gateway_session_meta import model_state, provenance_meta, session_modes
+ from acp_adapter.gateway_session_meta import config_options, model_state, provenance_meta, session_modes
from acp_adapter.modes import MODE_TO_EDIT_APPROVAL_POLICY
title = info.get("title")
if isinstance(title, str) and title.strip():
@@ -311,7 +311,8 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
# ``_adopt`` seeded the mode from the snapshot: a change the pump projected since is what the reply shows.
modes = session_modes({"edit_approval_policy": MODE_TO_EDIT_APPROVAL_POLICY[self._modes.setdefault(
session_id, session_modes(info).current_mode_id)]})
- return {"models": models, "modes": modes, "field_meta": meta}
+ return {"models": models, "modes": modes, "field_meta": meta,
+ "config_options": config_options(models, info, modes.current_mode_id)}
async def _after_attach(self, session_id, editor_id):
from acp_adapter.gateway_session_meta import available_commands_update
@@ -572,40 +573,60 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
return SetSessionModeResponse()
async def set_config_option(self, config_id, session_id, value=None, **kwargs):
- """Accepted so editors do not fail on their own config writes, as main did; only the edit
- approval policy has a meaning here, and it is the same owner setting the modes select."""
+ """The pickers ``config_options`` advertises: the edit mode is the modes select's owner setting,
+ the model ``set_session_model``'s pick, the effort the owner's ``reasoning`` mutation (``default``
+ = ``/reasoning reset``). Another id is accepted so editors do not fail on their own config writes,
+ as main did. The reply is the full list, read back from the owner."""
from acp.schema import SetSessionConfigOptionResponse
+ from acp_adapter.gateway_session_meta import (
+ REASONING_CONFIG_ID, config_options, current_mode, model_state, reasoning_choices,
+ )
from acp_adapter.modes import EDIT_APPROVAL_POLICY_CONFIG_ID, EDIT_APPROVAL_POLICY_TO_MODE
- session_id = self._held_session(session_id)
+ editor_id, session_id = session_id, self._held_session(session_id)
if config_id == EDIT_APPROVAL_POLICY_CONFIG_ID:
if value not in EDIT_APPROVAL_POLICY_TO_MODE:
raise GatewayClientError("invalid_params")
await self._set_edit_policy(session_id, value)
- return SetSessionConfigOptionResponse(config_options=[])
+ elif config_id == "model":
+ if not isinstance(value, str):
+ raise GatewayClientError("invalid_params")
+ await self.set_session_model(model_id=value, session_id=editor_id)
+ elif config_id == REASONING_CONFIG_ID:
+ if value not in reasoning_choices():
+ raise GatewayClientError("invalid_params")
+ await self._idle_control(session_id, "reasoning", {"effort": None if value == "default" else value},
+ "Reasoning effort")
+ info = await (await self._client()).rpc("session.info", session_id=session_id)
+ models = await asyncio.to_thread(model_state, info)
+ return SetSessionConfigOptionResponse(config_options=config_options(
+ models, info, self._modes.get(session_id) or current_mode(info)))
async def _set_edit_policy(self, session_id, policy):
- """The owner's ``edit_policy`` mutation (revision-fenced, idle sessions only, like a model pick);
- every surface attached to the session reads the committed policy from ``session.info``."""
+ """The owner's ``edit_policy`` mutation; every surface attached to the session reads the
+ committed policy from ``session.info``."""
from acp_adapter.modes import EDIT_APPROVAL_POLICY_TO_MODE
+ await self._idle_control(session_id, "edit_policy", {"policy": policy}, "Mode")
+ self._modes[session_id] = EDIT_APPROVAL_POLICY_TO_MODE[policy]
+
+ async def _idle_control(self, session_id, operation, payload, label):
+ """A revision-fenced owner mutation that applies to idle sessions only, like a model pick."""
client = await self._client()
- payload = {"policy": policy}
self._unacked.pop(session_id, None)
try:
- await self._mutations.apply(client, session_id, "edit_policy", payload)
+ await self._mutations.apply(client, session_id, operation, payload)
except GatewayClientError as exc:
if str(exc) not in {"session_busy", "unknown_execution"}:
raise
# Named in the transcript (as a deferred model pick is) and the reply: a running turn ends on its
# own, a lost one (unknown_execution) blocks every control until it is resolved or discarded.
- text = ("Mode changes apply when the session is idle; try again after this turn."
- if str(exc) == "session_busy" else "Mode changes wait for the lost turn: "
+ text = (f"{label} changes apply when the session is idle; try again after this turn."
+ if str(exc) == "session_busy" else f"{label} changes wait for the lost turn: "
+ self._unknown_recovery(session_id, submitted=False).removeprefix("unknown_execution: "))
if self._conn:
await self._conn.session_update(session_id=self._editor_id(session_id),
update=acp.update_agent_message_text(text + "\n"))
raise acp.RequestError(-32603, text) from exc
- self._mutations.acknowledge(session_id, "edit_policy", payload)
- self._modes[session_id] = EDIT_APPROVAL_POLICY_TO_MODE[policy]
+ self._mutations.acknowledge(session_id, operation, payload)
async def list_sessions(self, cursor=None, cwd=None, **kwargs):
from acp.schema import ListSessionsResponse, SessionInfo
diff --git a/acp_adapter/gateway_session_meta.py b/acp_adapter/gateway_session_meta.py
index 2c1766a6c79..b559900f4be 100644
--- a/acp_adapter/gateway_session_meta.py
+++ b/acp_adapter/gateway_session_meta.py
@@ -12,11 +12,13 @@ from pathlib import Path
import sqlite3
from acp.schema import (
- AvailableCommand, AvailableCommandsUpdate, ModelInfo, SessionInfoUpdate, SessionMode, SessionModeState,
- SessionModelState, UnstructuredCommandInput, Usage, UsageUpdate,
+ AvailableCommand, AvailableCommandsUpdate, ModelInfo, SessionConfigOptionSelect, SessionConfigSelectOption,
+ SessionInfoUpdate, SessionMode, SessionModeState, SessionModelState, UnstructuredCommandInput, Usage, UsageUpdate,
)
-from acp_adapter.modes import DEFAULT_EDIT_APPROVAL_POLICY, DEFAULT_MODE, EDIT_APPROVAL_POLICY_TO_MODE, MODES
+from acp_adapter.modes import (
+ DEFAULT_EDIT_APPROVAL_POLICY, DEFAULT_MODE, EDIT_APPROVAL_POLICY_CONFIG_ID, EDIT_APPROVAL_POLICY_TO_MODE, MODES,
+)
logger = logging.getLogger(__name__)
@@ -67,6 +69,32 @@ def session_modes(info: dict | None = None) -> SessionModeState:
SessionMode(id=mode, name=name, description=description) for mode, (_p, name, description) in MODES.items()])
+REASONING_CONFIG_ID = "reasoning_effort"
+
+
+def reasoning_choices() -> tuple[str, ...]:
+ """The owner's ``reasoning`` levels; ``default`` hands the level back to the profile."""
+ from hermes_constants import VALID_REASONING_EFFORTS
+ return ("default", "none", *VALID_REASONING_EFFORTS)
+
+
+def config_options(models: SessionModelState | None, info: dict, mode_id: str) -> list:
+ """Zed renders its composer pickers only from ``configOptions``: the edit mode, the model
+ (``set_session_model``'s picker ids) and the reasoning effort (``session.info``'s level)."""
+ def select(config_id, name, category, current, choices):
+ return SessionConfigOptionSelect(id=config_id, name=name, category=category, type="select", current_value=current,
+ options=[SessionConfigSelectOption(value=v, name=n) for v, n in choices])
+ options = [select(EDIT_APPROVAL_POLICY_CONFIG_ID, "Edits", "mode", MODES[mode_id][0],
+ [(policy, name) for policy, name, _ in MODES.values()])]
+ if models is not None:
+ options.append(select("model", "Model", "model", models.current_model_id,
+ [(m.model_id, m.name) for m in models.available_models]))
+ effort = info.get("reasoning_effort")
+ options.append(select(REASONING_CONFIG_ID, "Reasoning effort", "thought_level",
+ effort if effort in reasoning_choices() else "default", [(v, v) for v in reasoning_choices()]))
+ return options
+
+
def model_state(info: dict) -> SessionModelState | None:
"""The picker for the session's model (``session.info``), from the shared inventory; a single
current-model row when nothing is listable, as main's ``_build_model_state``. Blocking."""
diff --git a/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts b/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts
index 2084934394e..54a1fd70514 100644
--- a/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts
+++ b/apps/desktop/src/app/chat/composer/discard-lost-prompt.ts
@@ -17,9 +17,9 @@ export async function discardLostPrompt(
})
}
-/** Withdraw a server-queued admission before it starts. The authority settles every waiter and
- * its pending fanout retires the card; a row that started meanwhile is refused (stale_generation)
- * and keeps running. Same owner routing as discardLostPrompt. */
+/** Withdraw a server-queued admission. The authority settles every waiter and its pending fanout
+ * retires the card; a row that started meanwhile is stopped in the same RPC (no follow-up
+ * session.interrupt needed). Same owner routing as discardLostPrompt. */
export async function cancelQueuedPrompt(
sessionId: string | null | undefined,
queueSessionKey: string,
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index b0c3c291907..2ec98b5e114 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -815,8 +815,18 @@ class AuthorityConnection:
async def cancel(self, ref, params):
admission_id = params.get('admission_id')
- if (await self.authority.receipt(self.actor, ref, admission_id)).status != 'queued':
- return asdict(await self.authority.cancel_queued(self.actor, ref, admission_id)) # started: unaffected
+ receipt = await self.authority.receipt(self.actor, ref, admission_id)
+ if receipt.status == 'started':
+ # Stopped in this RPC: an editor that exits right after its cancel never sends a follow-up
+ # interrupt. A stale generation means the turn already settled.
+ try:
+ await self.interrupt(ref, {'execution_generation': receipt.execution_generation})
+ except RuntimeStoreError as exc:
+ if exc.reason != 'stale_generation':
+ raise
+ return asdict(await self.authority.receipt(self.actor, ref, admission_id))
+ if receipt.status != 'queued':
+ return asdict(await self.authority.cancel_queued(self.actor, ref, admission_id))
# Queued at this read, claimed by the drain before the cancel commit: Stop that exact claim (as
# API and ACP do) instead of refusing while the withdrawn prompt runs.
row = await self.authority.cancel_or_claimed(self.actor, ref, admission_id)
diff --git a/tests/acp_adapter/test_gateway_catalog_local_rows.py b/tests/acp_adapter/test_gateway_catalog_local_rows.py
new file mode 100644
index 00000000000..fe7ae793a31
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_catalog_local_rows.py
@@ -0,0 +1,14 @@
+"""session/list finds editor threads the gateway owner stores as ``local`` (#143547 ACP-24)."""
+from acp_adapter.catalog import catalog_sessions
+from hermes_state import SessionDB
+
+
+def test_catalog_lists_gateway_owned_editor_threads_only(tmp_path):
+ db_path = tmp_path / 'state.db'
+ with SessionDB(db_path) as db:
+ for sid, created in (('editor-thread', 'acp'), ('cli-chat', 'cli')):
+ db.create_session(session_id=sid, source='local', cwd=str(tmp_path))
+ db._execute_write(lambda conn, sid=sid, created=created: conn.execute(
+ 'UPDATE sessions SET created_source = ? WHERE id = ?', (created, sid)))
+ db.append_message(sid, 'user', 'saved turn')
+ assert [row['session_id'] for row in catalog_sessions(db_path, str(tmp_path))] == ['editor-thread']
diff --git a/tests/acp_adapter/test_gateway_config_options.py b/tests/acp_adapter/test_gateway_config_options.py
new file mode 100644
index 00000000000..38b372c28d4
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_config_options.py
@@ -0,0 +1,31 @@
+"""Zed renders its model and effort pickers only from ``configOptions`` (#143547 ACP-24)."""
+import pytest
+from acp.schema import ModelInfo, SessionModelState
+
+from acp_adapter.server import HermesACPAgent
+
+
+async def test_effort_pick_applies_through_the_reasoning_mutation_and_returns_the_pickers(monkeypatch):
+ monkeypatch.setattr('acp_adapter.gateway_session_meta.model_state', lambda info: SessionModelState(
+ available_models=[ModelInfo(model_id='openrouter:fixture', name='fixture')], current_model_id='openrouter:fixture'))
+ info = {'model': 'fixture', 'provider': 'openrouter', 'reasoning_effort': 'medium'}
+ mutations = []
+
+ class RPC:
+ async def rpc(self, method, **params):
+ if method == 'session.mutate':
+ mutations.append((params['operation'], params['payload']))
+ info['reasoning_effort'] = params['payload']['effort']
+ return {'status': 'applied'}
+ if method == 'session.info':
+ return dict(info)
+ return {'revision': 1, 'execution_generation': 1, 'info': dict(info)}
+
+ agent = HermesACPAgent()
+ agent._gateway = RPC()
+ agent._snapshots['s'] = {'revision': 1, 'execution_generation': 1}
+ reply = await agent.set_config_option(config_id='reasoning_effort', session_id='s', value='high')
+ assert mutations == [('reasoning', {'effort': 'high'})]
+ pickers = {option.category: option.current_value for option in reply.config_options}
+ assert pickers == {'mode': 'ask', 'model': 'openrouter:fixture', 'thought_level': 'high'}
diff --git a/tests/acp_adapter/test_gateway_session_commands.py b/tests/acp_adapter/test_gateway_session_commands.py
index c183c7115c3..b2bf9c2a097 100644
--- a/tests/acp_adapter/test_gateway_session_commands.py
+++ b/tests/acp_adapter/test_gateway_session_commands.py
@@ -141,6 +141,8 @@ async def test_modes_and_the_config_option_set_the_owners_edit_policy():
async def rpc(method, **params):
if method == 'session.resume':
return {'revision': 3, 'execution_generation': 7}
+ if method == 'session.info':
+ return {}
assert method == 'session.mutate', method
sent.append((params['operation'], params['payload'], params['expected_generation']))
return {'session_id': 's', 'operation': 'edit_policy', 'revision': 4}
diff --git a/tests/gateway/test_prompt_cancel_started.py b/tests/gateway/test_prompt_cancel_started.py
new file mode 100644
index 00000000000..2746a9ff9e6
--- /dev/null
+++ b/tests/gateway/test_prompt_cancel_started.py
@@ -0,0 +1,40 @@
+"""prompt.cancel on a started admission stops it in the same RPC (#143547 ACP-23): an editor that
+exits right after its cancel never sends the follow-up ``session.interrupt``."""
+import asyncio
+
+import pytest
+
+# Imported before the home-I/O guard: the drain's lazy import of it probes the checkout root.
+import gateway.session_managed_worker
+
+from tests.gateway.test_canonical_stop_hard_cancel import Agent
+from tests.gateway.test_session_authority_cancel_settlement import REF, _authority, _submit, _wire_turn_agent
+
+
+async def test_prompt_cancel_stops_a_started_turn_without_a_follow_up_interrupt(tmp_path, monkeypatch):
+ from gateway import session_finite
+ from gateway.session_controls import AuthorityConnection
+
+ db, authority = _authority(tmp_path, monkeypatch)
+ agent = Agent()
+ authority.runner._cached_agent_for = {}.get
+ claimed, stopped = asyncio.Event(), asyncio.Event()
+
+ async def execute(authority, ref, row):
+ _wire_turn_agent(authority, row['generation'], agent)
+ claimed.set()
+ await asyncio.wait_for(stopped.wait(), 5)
+ return 'done'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+ with db:
+ receipt = await _submit(authority, 'turn')
+ await asyncio.wait_for(claimed.wait(), 5)
+ conn = AuthorityConnection(authority, object(), {'user_id': 'human'})
+ reply = await conn.dispatch({'id': 1, 'method': 'prompt.cancel', 'params': {
+ 'session_id': REF.session_id, 'admission_id': receipt.admission_id}})
+ stopped.set()
+ await asyncio.wait_for(authority.sessions['s'].task, 5)
+ assert 'error' not in reply, reply
+ assert reply['result']['admission_id'] == receipt.admission_id
+ assert agent.stops == ['hard'], 'the started turn kept running'