The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): Desktop /stop, per-process Stop and MCP reload work on the shared owner
Teknium86d6377ae97f
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 6859841104f..647c34fd926 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -567,7 +567,7 @@ describe('usePromptActions /stop', () => {expect(calls).toEqual([{ method: 'session.interrupt', params: { session_id: 'rt-target-session' } },- { method: 'process.stop', params: {} }+ { method: 'process.stop', params: { session_id: 'rt-target-session' } }])expect(requestGateway).not.toHaveBeenCalledWith('slash.exec', expect.anything())expect(requestGateway).not.toHaveBeenCalledWith('command.dispatch', expect.anything())@@ -594,7 +594,7 @@ describe('usePromptActions /stop', () => {await handle!.submitText('/stop')expect(requestGateway).toHaveBeenCalledWith('session.interrupt', { session_id: RUNTIME_SESSION_ID })- expect(requestGateway).toHaveBeenCalledWith('process.stop', {})+ expect(requestGateway).toHaveBeenCalledWith('process.stop', { session_id: RUNTIME_SESSION_ID })})})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex 50fff902896..ddee05ef745 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -659,9 +659,12 @@ export function useSlashCommand(deps: SlashCommandDeps) {const { render: renderSlashOutput, sessionId: initialSessionId, storedSessionId } = resolvedconst lines: string[] = []+ // The shared owner stops only the processes this chat owns, so process.stop names the+ // id session.interrupt resolved (a recovered runtime when the old one was reaped).+ let stopSessionId = initialSessionIdtry {- await withSessionNotFoundResume(+ ;({ sessionId: stopSessionId } = await withSessionNotFoundResume(initialSessionId,storedSessionId,liveId => requestGateway('session.interrupt', { session_id: liveId }),@@ -674,14 +677,14 @@ export function useSlashCommand(deps: SlashCommandDeps) {}}}- )+ ))lines.push('Stopped the active turn.')} catch (err) {lines.push(`Could not stop the active turn: ${err instanceof Error ? err.message : String(err)}`)}try {- const result = await requestGateway<unknown>('process.stop', {})+ const result = await requestGateway<unknown>('process.stop', { session_id: stopSessionId })const processMessage = renderRpcResult(result, ctx.name)if (processMessage) {diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.pyindex a727d2fed65..48ea479e683 100644--- a/gateway/session_ancillary.py+++ b/gateway/session_ancillary.py@@ -1,7 +1,8 @@-"""Desktop/Ink projections of existing owner state, plus the session-scoped process stop.+"""Desktop/Ink projections of existing owner state, plus the session-scoped process verbs.No legacy server, manager construction, process recovery, or execution on reads. ``process.stop``-is the one write: it stops exactly the processes ``process.list`` projects for the session.+and ``process.kill`` stop only processes ``process.list`` projects for the session; ``reload.mcp``+reconciles only the requesting profile's MCP servers."""import asynciofrom functools import partial@@ -24,7 +25,8 @@ def handlers(connection):'subagent.list': 'subagents', 'subagent.tail': 'tail',}.items()}, 'approval.pending': partial(approvals, connection),'approval.received': partial(approvals, connection, ack=True),- 'process.stop': partial(stop_processes, connection)}+ 'process.stop': partial(stop_processes, connection),+ 'process.kill': partial(kill_process, connection), 'reload.mcp': partial(reload_mcp, connection)}async def approvals(connection, ref, params, *, ack=False):@@ -77,13 +79,9 @@ async def read(connection, ref, params, *, kind):return {'processes': process_snapshot(authority, ref, agent, records)}-async def stop_processes(connection, ref, params):- """Ink ``/stop``: kill the background processes this session owns (what ``process.list``- shows), never the registry-wide ``kill_all`` the legacy sidecar ran, which on the shared owner- reached every chat, Desktop window and served profile (dokterdok N2). An explicit stop, so a- ``persist_on_release`` job of THIS session is still reached (#41225)."""- if set(params) - {'session_id', 'profile'} or not isinstance(ref.session_id, str) or not ref.session_id:- raise RuntimeStoreError('invalid_params')+def _owned_targets(connection, ref, params, *, select):+ """``(registry, ids)``: the session's own processes (what ``process.list`` shows) that+ ``select(process)`` keeps; ``(None, [])`` when no process was ever registered here."""authority = connection.authorityif ref.session_id not in authority.sessions:raise RuntimeStoreError('not_found')@@ -93,13 +91,61 @@ async def stop_processes(connection, ref, params):_require_current_route(authority, ref)agent, records = _owner_objects(authority, ref)module = sys.modules.get('tools.process_registry')- if module is None: # nothing ever registered a process in this interpreter- return {'killed': 0}+ if module is None:+ return None, []registry = module.process_registrykeys, owners = _ownership(authority, ref, agent, records)with registry._lock:- targets = [p.id for p in _owned_locked(registry, keys, owners)- if not p.exited or p._scope_stop_pending]+ return registry, [p.id for p in _owned_locked(registry, keys, owners) if select(p)]+++async def kill_process(connection, ref, params):+ """Desktop's per-process Stop: one process THIS session owns (the ``process.list`` rule); any+ other id, another chat's included, is ``not_found``. The legacy sidecar handler looked the+ session up in its own table, which never holds an authority session."""+ if (set(params) - {'session_id', 'process_id', 'profile'} or not ref.session_id+ or not isinstance(params.get('process_id'), str) or not params['process_id']):+ raise RuntimeStoreError('invalid_params')+ registry, ids = _owned_targets(connection, ref, params, select=lambda p: p.id == params['process_id'])+ if not ids:+ raise RuntimeStoreError('not_found')+ return await asyncio.to_thread(registry.kill_process, ids[0])+++async def reload_mcp(connection, ref, params):+ """Desktop's MCP add / toggle / repair: bring THIS profile's live MCP servers in step with its+ config (the owner's housekeeping reconcile, run now) and refresh this profile's cached agents.+ Never the sidecar's teardown of every server, which cut every chat's in-flight MCP calls."""+ if set(params) - {'session_id', 'confirm', 'rev', 'profile'}:+ raise RuntimeStoreError('invalid_params')+ if 'session:control' not in connection.actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ if params.get('confirm') is not True:+ return {'status': 'confirm_required', 'message': 'Reloading MCP refreshes every chat of this profile.'}+ from tools.mcp_oauth import suppress_interactive_oauth+ from tools.mcp_tool_discovery import reconcile_mcp_servers_with_config++ def reconcile():+ with suppress_interactive_oauth():+ return reconcile_mcp_servers_with_config()+ result = await asyncio.to_thread(reconcile)+ from gateway.session_authorities import served_profile_name+ runner = connection.authority.runner+ multiplex = bool(getattr(runner.config, 'multiplex_profiles', False))+ runner._mcp_reload_refresh_cached_agents(multiplex, served_profile_name(connection.authority.profile_id))+ changed = ', '.join(f'{k}: {", ".join(v)}' for k, v in result.items() if v) or 'no server changes'+ return {'status': 'reloaded', 'message': f'MCP servers reconciled ({changed})'}+++async def stop_processes(connection, ref, params):+ """Ink ``/stop``: kill the background processes this session owns (what ``process.list``+ shows), never the registry-wide ``kill_all`` the legacy sidecar ran, which on the shared owner+ reached every chat, Desktop window and served profile (dokterdok N2). An explicit stop, so a+ ``persist_on_release`` job of THIS session is still reached (#41225)."""+ if set(params) - {'session_id', 'profile'} or not isinstance(ref.session_id, str) or not ref.session_id:+ raise RuntimeStoreError('invalid_params')+ registry, targets = _owned_targets(connection, ref, params,+ select=lambda p: not p.exited or p._scope_stop_pending)def kill():results = [registry.kill_process(pid, source='process.stop', consume_output=False) for pid in targets]diff --git a/tests/gateway/fixtures/desktop_process_verbs_peer.py b/tests/gateway/fixtures/desktop_process_verbs_peer.pynew file mode 100644index 00000000000..d47ac605b6a--- /dev/null+++ b/tests/gateway/fixtures/desktop_process_verbs_peer.py@@ -0,0 +1,68 @@+"""Authenticated WS fixture: Desktop's exact process/MCP frames on the shared owner; no inference."""+import asyncio+import json+import os+from pathlib import Path+import shlex+import sys+import traceback+++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.process_registry import process_registry+ 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='desktop-verbs')+ api = await start_gateway_api(runner)+ web_server.app.state.auth_required = True+ receipt, processes = {}, []+ command = shlex.quote(sys.executable) + ' -c ' + shlex.quote('import time; time.sleep(60)')+ try:+ ticket = mint_ticket(user_id='owner', provider='fixture')+ async with connect(api.api_origin.replace('http:', 'ws:') + '/api/ws?ticket=' + ticket) as ws:+ sid = (await rpc(ws, 'session.create', request_id='desktop', source='gui', toolsets=[]))['result']['session_id']+ route = authority.sessions[sid].route+ for task, key in [(sid, route), (sid, route), ('foreign', 'agent:main:telegram:dm:1')]:+ processes.append(process_registry.spawn_local(command, cwd=str(home), task_id=task, owner_task_id=task,+ session_key=key))+ own, other, foreign = processes+ # composer-status.ts: per-process Stop.+ kill = await rpc(ws, 'process.kill', process_id=own.id, session_id=sid)+ await asyncio.to_thread(own._completion_event.wait, 10)+ receipt['kill'] = kill.get('result', {}).get('status', kill.get('error'))+ receipt['foreign_kill'] = (await rpc(ws, 'process.kill', process_id=foreign.id, session_id=sid)).get('error', {}).get('message')+ # slash.ts /stop: the session id session.interrupt resolved.+ stop = await rpc(ws, 'process.stop', session_id=sid)+ await asyncio.to_thread(other._completion_event.wait, 10)+ receipt['stop'] = stop.get('result', stop.get('error'))+ receipt['exited'] = [p.exited for p in processes]+ # use-mcp-servers.ts / mcp.ts / repair.ts.+ reload = await rpc(ws, 'reload.mcp', confirm=True, session_id=sid)+ receipt['reload_mcp'] = reload.get('result', {}).get('status', reload.get('error'))+ finally:+ for proc in processes:+ if not proc.exited:+ process_registry.kill_process(proc.id)+ 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_desktop_process_verbs.py b/tests/gateway/test_desktop_process_verbs.pynew file mode 100644index 00000000000..0704b18b0d7--- /dev/null+++ b/tests/gateway/test_desktop_process_verbs.py@@ -0,0 +1,29 @@+"""Desktop's /stop, per-process Stop and MCP reload are served by the shared owner (dokterdok N27)."""+import json+from pathlib import Path+import subprocess+import sys++from tests.gateway.fixtures.local_recovery_probe import child_env+++def test_desktop_process_kill_stop_and_mcp_reload_reach_only_this_session(tmp_path):+ """``process.kill`` stops this chat's own process and refuses another chat's; ``process.stop``+ with the resolved session id stops the rest of this chat's; ``reload.mcp`` is served (a+ profile-scoped reconcile), not the -32601 the Desktop reported as "MCP reload failed"."""+ 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/desktop_process_verbs_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['kill'] == 'killed', receipt+ assert receipt['foreign_kill'] == 'not_found', receipt+ assert receipt['stop'] == {'killed': 1}, receipt+ assert receipt['exited'] == [True, True, False], receipt+ assert receipt['reload_mcp'] == 'reloaded', receiptdiff --git a/tests/gateway/test_session_process_scope.py b/tests/gateway/test_session_process_scope.pyindex ab731f6f25a..ecf1fc2ff6b 100644--- a/tests/gateway/test_session_process_scope.py+++ b/tests/gateway/test_session_process_scope.py@@ -10,8 +10,8 @@ from tests.gateway.fixtures.local_recovery_probe import child_envdef test_stop_is_session_scoped_and_global_verbs_keep_the_owner_refusal(tmp_path):"""Ink ``/stop`` kills only its own session's processes (a persisted one included); anotherchat's processes, persisted or not, survive. ``delegation.pause``, ``reload.env``,- ``reload.mcp`` and ``agents.list`` keep the authority's -32601 instead of reaching the legacy- handler that pauses every spawn, rewrites the shared environ or reloads every MCP server."""+ and ``agents.list`` keep the authority's -32601 instead of reaching the legacy+ handler that pauses every spawn or rewrites the shared environ."""root = Path(__file__).resolve().parents[2]home, user = tmp_path / 'state', tmp_path / 'user'home.mkdir()@@ -29,4 +29,5 @@ def test_stop_is_session_scoped_and_global_verbs_keep_the_owner_refusal(tmp_pathassert receipt['exited_after_sessionless'] == [True, True, False, False], receiptassert receipt['pause'] == -32601 and receipt['spawn_paused'] is False, receiptassert receipt['reload_env'] == -32601 and receipt['environ_rewritten'] is False, receipt- assert receipt['reload_mcp'] == -32601 and receipt['agents_list'] == -32601, receipt+ # reload.mcp is now served by the owner, profile-scoped (test_desktop_process_verbs.py).+ assert receipt['agents_list'] == -32601, receipt