The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): the shared owner serves Desktop's subagent Steer and Stop
Tekniumca836e4b5f8a
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.pyindex d5320b9b150..836a2de53a1 100644--- a/gateway/session_ancillary.py+++ b/gateway/session_ancillary.py@@ -27,7 +27,35 @@ def handlers(connection):'approval.received': partial(approvals, connection, ack=True),'process.stop': partial(stop_processes, connection),'process.kill': partial(kill_process, connection), 'reload.mcp': partial(reload_mcp, connection),- 'file.attach': partial(attach_file, connection)}+ 'file.attach': partial(attach_file, connection),+ **{name: partial(subagent_control, connection, steer=name == 'subagent.steer')+ for name in ('subagent.steer', 'subagent.interrupt')}}+++async def subagent_control(connection, ref, params, *, steer):+ """Desktop's per-child Steer / Stop: only a child of THIS session's live agent (the+ ``subagent.list`` rule). The sidecar handler never held an authority session."""+ fields = {'session_id', 'profile', 'subagent_id'} | ({'text'} if steer else set())+ if (set(params) - fields or not ref.session_id or any(not isinstance(params.get(k), str) or not params[k]+ for k in fields - {'profile'})):+ raise RuntimeStoreError('invalid_params')+ if ref.session_id not in connection.authority.sessions:+ raise RuntimeStoreError('not_found')+ authorize(connection, ref, params, 'session:control')+ live, sub = connection.authority.sessions[ref.session_id], params['subagent_id']+ with live.event_stream.lock:+ _require_current_route(connection.authority, ref)+ child = next((r['agent'] for r in _owner_objects(connection.authority, ref)[1] if r.get('subagent_id') == sub), None)+ if not steer:+ from agent.interrupt_compat import request_hard_interrupt+ return {'found': child is not None and bool(request_hard_interrupt(child, f'Interrupted via Desktop ({sub})')),+ 'subagent_id': sub}+ from tools import delegate_tool_registry as registry+ with registry._active_subagents_lock: # linearized with the child's final steer drain+ record = registry._active_subagents.get(sub)+ queued = bool(child is not None and record and record.get('agent') is child and record.get('accepting_steer')+ and child.steer(params['text']))+ return {'status': 'queued' if queued else 'rejected', 'subagent_id': sub, 'text': params['text']}async def attach_file(connection, ref, params):diff --git a/tests/gateway/fixtures/subagent_controls_peer.py b/tests/gateway/fixtures/subagent_controls_peer.pynew file mode 100644index 00000000000..bb23e86491a--- /dev/null+++ b/tests/gateway/fixtures/subagent_controls_peer.py@@ -0,0 +1,87 @@+"""Authenticated owner fixture: Desktop's per-child Steer/Stop reach only this session's children."""+import asyncio+import json+import os+from pathlib import Path+import sys+import traceback+import weakref+++async def probe():+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.run_api import start_gateway_api, stop_gateway_api+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket+ from tests.gateway.fixtures.local_recovery_probe import rpc+ from tools.delegate_tool_child_run import _register_child+ from tools.delegate_tool_registry import _close_subagent_steering, _unregister_subagent+ from websockets.asyncio.client import connect++ home = Path(os.environ['HERMES_HOME'])+ (home / 'config.yaml').write_text('gateway:\n multiplex_profiles: false\nmodel:\n provider: custom\n default: no-inference\n base_url: http://127.0.0.1:1/v1\nauxiliary:\n title_generation:\n enabled: false\n')+ runner = GatewayRunner()+ authority = await initialize_session_authority(runner, profile_id=str(home), instance_id='subagent-controls')+ api = await start_gateway_api(runner)+ web_server.app.state.auth_required = True+ receipt = {}++ class Agent:+ def __init__(self):+ self.steered, self.stopped = [], []++ def steer(self, text):+ self.steered.append(text)+ return True++ def hard_interrupt(self, message=None):+ self.stopped.append(message)+ return True++ ticket = mint_ticket(user_id='owner', provider='fixture')+ async with connect(api.api_origin.replace('http:', 'ws:') + '/api/ws?ticket=' + ticket) as ws:+ created = await rpc(ws, 'session.create', request_id='controls-owner', source='gui', toolsets=[])+ sid = created['result']['session_id']+ live = authority.sessions[sid]+ parent, other_parent = Agent(), Agent()+ parent.session_id, other_parent.session_id = sid, 'foreign-session'+ with runner._agent_cache_lock:+ runner._agent_cache[live.route] = (parent, 'fixture')+ children = {}+ try:+ for name, ancestor in [('owned', parent), ('sibling', other_parent)]:+ child = children[name] = Agent()+ child._subagent_id = name+ child._delegate_parent_ref = weakref.ref(ancestor)+ child._parent_session_id = ancestor.session_id+ _register_child(child, ancestor, name + '-goal', owner_session_id=None,+ owner_transport=None, owner_session_record=None)+ # The exact Desktop producer frames (subagent-controls.tsx).+ for name in ('owned', 'sibling'):+ steer = await rpc(ws, 'subagent.steer', session_id=sid, subagent_id=name, text='check ' + name)+ stop = await rpc(ws, 'subagent.interrupt', session_id=sid, subagent_id=name)+ receipt[name] = {'steer': steer.get('result', steer.get('error')),+ 'stop': stop.get('result', stop.get('error'))}+ receipt['delivered'] = {name: [child.steered, len(child.stopped)] for name, child in children.items()}+ # A child past its final steer drain refuses instead of dropping the text.+ _close_subagent_steering('owned', children['owned'])+ late = await rpc(ws, 'subagent.steer', session_id=sid, subagent_id='owned', text='too late')+ receipt['late'] = late.get('result', late.get('error'))+ finally:+ for name, child in children.items():+ _unregister_subagent(name, agent=child)+ await stop_gateway_api(api)+ (home / 'receipt.json').write_text(json.dumps(receipt))+++if __name__ == '__main__':+ status = 0+ try:+ asyncio.run(probe())+ except BaseException:+ traceback.print_exc()+ status = 1+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(status)diff --git a/tests/gateway/test_session_subagent_controls.py b/tests/gateway/test_session_subagent_controls.pynew file mode 100644index 00000000000..12f3da22901--- /dev/null+++ b/tests/gateway/test_session_subagent_controls.py@@ -0,0 +1,29 @@+"""Desktop's subagent Steer / Stop are served by the shared owner (dokterdok N56)."""+import json+from pathlib import Path+import subprocess+import sys++from tests.gateway.fixtures.local_recovery_probe import child_env+++def test_desktop_subagent_steer_and_stop_reach_only_this_sessions_children(tmp_path):+ """Before: the owner answered -32601 and the legacy fallback ran the sidecar handler, which+ never holds an authority session, so Steer/Stop always read as rejected."""+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir()+ user.mkdir()+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1')+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/subagent_controls_peer.py')],+ cwd=root, env=env, capture_output=True, text=True, timeout=90, check=False)+ assert result.returncode == 0, result.stdout + result.stderr+ receipt = json.loads((home / 'receipt.json').read_text())+ assert receipt['owned'] == {'steer': {'status': 'queued', 'subagent_id': 'owned', 'text': 'check owned'},+ 'stop': {'found': True, 'subagent_id': 'owned'}}, receipt+ assert receipt['sibling'] == {'steer': {'status': 'rejected', 'subagent_id': 'sibling', 'text': 'check sibling'},+ 'stop': {'found': False, 'subagent_id': 'sibling'}}, receipt+ assert receipt['delivered'] == {'owned': [['check owned'], 1], 'sibling': [[], 0]}, receipt+ assert receipt['late']['status'] == 'rejected', receipt