The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): a background-process completion the gateway admits paints main's header and reply in the idle CLI
Teknium4de5d886490a
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 0a2181b9562..8f31a77378b 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -5342,6 +5342,13 @@ export interface ErrorPayload {export interface NoticePayload {message: string}+/** ``message.start``. Empty from the TUI gateway's emitters and for an ordinary admission; ``gateway/session_authority._stamp_claim`` adds an automation admission's async-result card (``session_automation.admission_display``: a background-process completion) and its model text, so a viewer that did not submit the turn paints the same header the submitter would. */+export interface MessageStartPayload {+ display_kind?: string | null+ display_text?: string | null+ notification_category?: string | null+ text?: string | null+}/** ``message.delta``. A session-authority local-viewer turn also publishes ``text: null``: the reply segment boundary (the agent's ``stream_delta_callback(None)``, before tool lines) that closes the classic CLI's reply box. Every other viewer ignores an empty chunk. */export interface MessageDeltaPayload {text: string | null@@ -6704,8 +6711,8 @@ export interface BackendGatewayEventMap {'message.interim': MessageInterimPayload/** The agent reacted to a message; paint it live. */'message.reaction': MessageReactionPayload- /** A turn began streaming; no payload. */- 'message.start': Record<string, never>+ /** A turn began streaming; an automation turn carries its async-result card. */+ 'message.start': MessageStartPayload/** The MoA aggregator started. */'moa.aggregating': MoaAggregatingPayload/** MoA phase transition (currently only ``aggregator``). */diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 18eee488ea2..8f07d578c25 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -23146,6 +23146,62 @@"title": "MessageReactionPayload","type": "object"},+ "MessageStartPayload": {+ "additionalProperties": false,+ "description": "``message.start``. Empty from the TUI gateway's emitters and for an ordinary admission;\n``gateway/session_authority._stamp_claim`` adds an automation admission's async-result card\n(``session_automation.admission_display``: a background-process completion) and its model\ntext, so a viewer that did not submit the turn paints the same header the submitter would.",+ "properties": {+ "display_kind": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Display Kind"+ },+ "display_text": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Display Text"+ },+ "notification_category": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Notification Category"+ },+ "text": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Text"+ }+ },+ "title": "MessageStartPayload",+ "type": "object"+ },"MoaAggregatingPayload": {"additionalProperties": false,"properties": {@@ -46630,13 +46686,12 @@},{"name": "message.start",- "summary": "A turn began streaming; no payload.",+ "summary": "A turn began streaming; an automation turn carries its async-result card.","params": [{"name": "payload","schema": {- "type": "object",- "additionalProperties": false+ "$ref": "#/components/schemas/MessageStartPayload"}}]diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 551a913ea85..799f7d6c54c 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -836,7 +836,9 @@ class SessionAuthority:'authority_epoch': self.epoch, 'execution_generation': row['generation'],'admission_id': row['admission_id']}self.executing[ref.session_id] = row['generation']- live.event_stream.publish(ref.session_id, {}, event_type='message.start')+ from gateway.session_automation import admission_display+ live.event_stream.publish(ref.session_id, admission_display(row.get('payload') or {}),+ event_type='message.start')self._publish_pending(ref)return rowdiff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 96e0d3b1eb4..94d87bdf844 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -91,6 +91,21 @@ _AUTOMATION_METADATA = frozenset({'gateway_session_key', 'gateway_session_id', ''display_kind', 'display_text', 'gateway_proven_session_id', 'gateway_completion_ids'})+def admission_display(payload):+ """An automation admission's async-result card (plus its model text) for the claim's+ ``message.start``: a viewer that did not submit the turn (the classic CLI, idle while a+ background process it started finishes in the gateway) paints the same header the submitting+ surface would. ``{}`` for every other input."""+ descriptor = payload.get('local_automation_v1') or (payload.get('native_text_v1') or {}).get('automation') or {}+ kind, text = descriptor.get('display_kind'), descriptor.get('display_text')+ if not kind or not isinstance(text, str) or not text.strip():+ return {}+ card = {'display_kind': kind, 'display_text': text, 'text': str(payload.get('text') or '')}+ if descriptor.get('notification_category') == 'diagnostic':+ card['notification_category'] = 'diagnostic'+ return card++def snapshot_automation(authority, adapter, event, identity):runner = authority.runnerif (not event.internal or event.message_type != MessageType.TEXT or event.is_command()diff --git a/hermes_cli/cli_process_notifications.py b/hermes_cli/cli_process_notifications.pyindex 8123189638a..49321751549 100644--- a/hermes_cli/cli_process_notifications.py+++ b/hermes_cli/cli_process_notifications.py@@ -34,6 +34,13 @@ class CLIProcessNotificationsMixin:return mode == "off"def _drain_process_notifications(self, consumer: str) -> None:+ from hermes_cli.gateway_tools_notify import gateway_store, queue_admitted_turn+ store = gateway_store(self)+ if store is not None:+ # The process registry and its delivery claims live in the gateway, which admits the+ # notification turn itself; this viewer only paints it (IPS-086).+ queue_admitted_turn(self, store)+ returnfrom tools.process_registry import process_registryfrom tools.async_delegation import claim_event_delivery, complete_event_deliveryfrom tools.process_registry_notifications import (diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex 1c9313bd523..a47e5168de6 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -481,12 +481,19 @@ class GatewayAgent:self._usage_stale = Trueself._interrupt_requested = Falseself._interrupt_sent_at = None- self._drain_stale()- try:- receipt = self.connection.call("prompt.submit", **self._submit_params(- user_message, persist_user_message, turn_author))- except GatewayClientError as exc:- return self._failed(history, user_message, str(exc))+ from hermes_cli.gateway_tools_notify import take_admitted_turn+ adopted = take_admitted_turn(self, persist_user_message if isinstance(persist_user_message, str)+ else user_message)+ if adopted is not None:+ # A notification turn the gateway already admitted and is running (its frames are queued).+ receipt = adopted+ else:+ self._drain_stale()+ try:+ receipt = self.connection.call("prompt.submit", **self._submit_params(+ user_message, persist_user_message, turn_author))+ except GatewayClientError as exc:+ return self._failed(history, user_message, str(exc))self._admission = (receipt or {}).get("admission_id")if receipt and receipt.get("execution_generation") is not None:self._generation = receipt["execution_generation"]diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 62b6668b499..5347fed9bbf 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -40,6 +40,8 @@ class SessionState:# Called (loop thread) with each ``session.usage`` payload; GatewayAgent maps it onto main's# agent attributes, so a frame landing between turns is never dropped with the turn queue.self.usage_listeners: list = []+ # A gateway-admitted notification turn the idle CLI queued a header for (gateway_tools_notify).+ self.admitted_turn: dict | None = Nonedef adopt_snapshot(self, snapshot):self.info = dict(snapshot.get("info") or {})diff --git a/hermes_cli/gateway_tools_notify.py b/hermes_cli/gateway_tools_notify.pynew file mode 100644index 00000000000..35560441ea1--- /dev/null+++ b/hermes_cli/gateway_tools_notify.py@@ -0,0 +1,86 @@+"""Background-process notification turns the gateway admits for this CLI's session (W11).++On main the classic CLI drained ``tools.process_registry`` itself, queued a+``ProcessNotificationBatch`` into ``_pending_input`` and ran the ``[IMPORTANT: Background process+...]`` turn. Over the session authority the process runs in the gateway: the gateway drains the+completion, admits the notification turn (``authority.admit_automation``) and runs it. The CLI+neither drains the registry nor claims delivery (IPS-086) — it only watches its session's stream.++The claim's ``message.start`` carries the admission's async-result card (``display_kind`` /+``display_text`` / model ``text``; ``gateway.session_automation.admission_display``). The idle tick+turns it into main's ``TimelineNotification``, so main's input path paints the same ``◈ Background+Process Finished: ...`` header, and ``GatewayAgent.run_conversation`` pumps that already-admitted+turn (no ``prompt.submit``) through the same callbacks as a typed turn.+"""+from __future__ import annotations++import queue+++def gateway_store(cli):+ """The CLI's gateway session store, or None (a test double / an unavailable store)."""+ from hermes_cli.gateway_session_store import GatewaySessionStore+ store = getattr(cli, "_session_db", None)+ return store if isinstance(store, GatewaySessionStore) else None+++def _card(params):+ payload = params.get("payload")+ if not isinstance(payload, dict):+ return None+ kind, display, text = payload.get("display_kind"), payload.get("display_text"), payload.get("text")+ if not kind or not isinstance(display, str) or not display.strip() or not isinstance(text, str) or not text:+ return None+ return payload+++def queue_admitted_turn(cli, store) -> None:+ """Idle tick: find a gateway-admitted notification turn's ``message.start`` for this session and+ queue main's ``TimelineNotification`` for it. Frames before it are the between-turn leftovers+ ``run_conversation`` would discard anyway; frames after it stay queued for the pump."""+ from tools.process_registry_notifications import TimelineNotification+ connection, session_id = store.connection, getattr(cli, "session_id", None)+ state = connection.state(session_id)+ state.admitted_turn = None # a header queued earlier whose turn never ran is stale now+ events = connection.events+ while True:+ try:+ frame = events.get_nowait()+ except queue.Empty:+ return+ if isinstance(frame, Exception):+ events.put(frame) # the disconnect belongs to the next turn+ return+ params = frame.get("params") if isinstance(frame, dict) else None+ if (not isinstance(params, dict) or params.get("session_id") != session_id+ or params.get("type") != "message.start" or not params.get("admission_id")):+ continue+ card = _card(params)+ if card is None:+ continue+ state.admitted_turn = {"admission_id": params["admission_id"], "text": card["text"],+ "execution_generation": params.get("execution_generation")}+ _put_first(cli._pending_input, TimelineNotification(+ card["text"], card["display_text"], card["display_kind"],+ card.get("notification_category") or "result"))+ return+++def _put_first(pending, item):+ """Ahead of anything already queued: the gateway is running this turn NOW (typed inputs the+ post-turn path re-queued are admitted behind it), and a typed turn run first would drop it."""+ with pending.mutex:+ pending.queue.appendleft(item)+ pending.unfinished_tasks += 1+ pending.not_empty.notify()+++def take_admitted_turn(agent, text):+ """The admitted turn ``run_conversation(text)`` replays instead of submitting; None (and the+ stale adoption dropped) for any other turn."""+ state = agent._state()+ adopted = getattr(state, "admitted_turn", None)+ state.admitted_turn = None+ if not adopted or adopted.get("text") != text:+ return None+ return adopteddiff --git a/tests/hermes_cli/test_gateway_tools_notify.py b/tests/hermes_cli/test_gateway_tools_notify.pynew file mode 100644index 00000000000..a0e586f113d--- /dev/null+++ b/tests/hermes_cli/test_gateway_tools_notify.py@@ -0,0 +1,182 @@+"""A notification turn the gateway admits while the classic CLI is idle reaches main's screen.++On main the CLI drained ``tools.process_registry`` itself and ran the ``[IMPORTANT: Background+process ...]`` turn. Over the session authority the process (and its completion) live in the+gateway, which admits and runs that turn on its own; the CLI viewer must paint main's+``◈ Background Process Finished: ...`` header and stream the turn's reply through the same callbacks.+"""+import asyncio+import queue+from types import SimpleNamespace+from unittest.mock import Mock++from hermes_cli.gateway_agent import GatewayAgent+from hermes_cli.gateway_connection import GatewayConnection+from hermes_cli.gateway_session_store import GatewaySessionStore+from tests.hermes_cli.test_gateway_agent import SID, FakeClient, connect_with, frame+from tests.waiting import wait_until++DISPLAY = "Background Process Finished: sleep 6; echo BGDONE"+MODEL_TEXT = "[IMPORTANT: Background process proc_1 completed (exit 0).\nOutput:\nBGDONE]"+++def _gateway_frames():+ """What the authority publishes for one admitted local automation turn (admission adm-9)."""+ return [+ # _admitted -> _publish_pending: the queued row (its public input text) before any claim.+ {"jsonrpc": "2.0", "method": "event", "params": {+ "type": "session.info", "session_id": SID, "payload": {+ "running": False, "pending": [{"admission_id": "adm-9", "input_id": "x", "text": MODEL_TEXT}]}}},+ frame("message.start", {"display_kind": "process_complete", "display_text": DISPLAY, "text": MODEL_TEXT},+ generation=9, admission="adm-9"),+ frame("message.delta", {"text": "STEP13 notified "}, generation=9, admission="adm-9"),+ frame("message.delta", {"text": "reply."}, generation=9, admission="adm-9"),+ frame("message.complete", {"text": "STEP13 notified reply.", "status": "complete"},+ generation=9, admission="adm-9"),+ ]+++def _connected():+ client = FakeClient([])+ conn = GatewayConnection(connect=connect_with(client))+ conn.start(5)+ conn.state(SID)+ return conn, client+++def _play(conn, client, frames):+ async def put():+ for item in frames:+ await client.events.put(item)+ asyncio.run_coroutine_threadsafe(put(), conn.loop).result(5)+ wait_until(lambda: conn.events.qsize() >= len(frames), timeout=5)+++def _idle_cli(conn):+ from cli import HermesCLI+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id = SID+ cli._pending_input = queue.Queue()+ cli._session_db = GatewaySessionStore(connection=conn)+ cli._agent_running = False+ return cli+++def test_idle_cli_paints_header_and_streams_the_gateway_admitted_turn(monkeypatch, capsys):+ conn, client = _connected()+ try:+ # The CLI process never owns the registry over the gateway: draining it is a bug.+ monkeypatch.setattr("tools.process_registry.process_registry", SimpleNamespace(+ drain_notifications=Mock(side_effect=AssertionError("CLI drained the process registry"))))+ cli = _idle_cli(conn)+ _play(conn, client, _gateway_frames())+ cli._drain_process_notifications("cli-idle")+ queued = cli._pending_input.get_nowait()+ assert cli._pending_input.empty()+ assert queued.display_kind == "process_complete" and queued.display_text == DISPLAY+ assert str(queued) == MODEL_TEXT++ # Main's input path renders the header exactly as for a local completion.+ for attr, value in {"_pending_resume_sessions": [], "_typed_voice_stop": lambda t: False,+ "handle_bang_shell": lambda t: False, "_turn_summary_begin": lambda: None,+ "_tui_after_turn": lambda: None, "_app": SimpleNamespace(invalidate=lambda: None),+ "chat": Mock()}.items():+ setattr(cli, attr, value)+ cli._tui_process_one_input(queued)+ assert f"◈ {DISPLAY}" in capsys.readouterr().out+ message = cli.chat.call_args.args[0]+ assert message is queued++ # chat(): stage the row, then run_conversation pumps the ALREADY-admitted turn.+ deltas = []+ agent = GatewayAgent(connection=conn, session_id=SID, stream_delta_callback=deltas.append)+ cli.conversation_history = []+ cli._chat_stage_user_message(agent, message)+ result = agent.run_conversation(str(message), conversation_history=[])+ assert "prompt.submit" not in [method for method, _ in client.calls]+ assert deltas == ["STEP13 notified ", "reply."]+ assert result["final_response"] == "STEP13 notified reply."+ assert result["failed"] is False and result["interrupted"] is False+ assert ("prompt.receipt", {"session_id": SID, "admission_id": "adm-9", "include_result": True}) in client.calls+ assert result["messages"][0]["display_kind"] == "process_complete"+ finally:+ conn.close()+++def test_adoption_is_one_shot_and_never_hijacks_a_typed_turn():+ conn, client = _connected()+ try:+ cli = _idle_cli(conn)+ _play(conn, client, _gateway_frames()[:2])+ cli._drain_process_notifications("cli-idle")+ assert not cli._pending_input.empty()+ # The user's own turn runs instead (e.g. chat() bailed before run_conversation): it submits.+ client.script = [frame("message.complete", {"text": "typed", "outcome": "completed"})]+ agent = GatewayAgent(connection=conn, session_id=SID)+ agent._pending_cli_user_message = {"role": "user", "content": "hello"}+ result = agent.run_conversation("hello")+ assert "prompt.submit" in [method for method, _ in client.calls]+ assert result["final_response"] == "typed"+ assert getattr(conn.state(SID), "admitted_turn", None) is None+ finally:+ conn.close()+++def test_post_turn_adoption_runs_before_inputs_queued_behind_the_running_turn():+ conn, client = _connected()+ try:+ cli = _idle_cli(conn)+ cli._pending_input.put("typed while the last turn ran")+ _play(conn, client, _gateway_frames()[:2])+ cli._drain_process_notifications("cli-post-turn")+ first = cli._pending_input.get_nowait()+ assert getattr(first, "display_text", None) == DISPLAY+ assert cli._pending_input.get_nowait() == "typed while the last turn ran"+ finally:+ conn.close()+++def test_idle_tick_without_an_admitted_turn_queues_nothing():+ conn, client = _connected()+ try:+ cli = _idle_cli(conn)+ _play(conn, client, [frame("session.usage", {"usage": {"api_calls": 1}}),+ frame("message.complete", {"text": "late"}, admission="adm-old")])+ cli._drain_process_notifications("cli-idle")+ assert cli._pending_input.empty()+ finally:+ conn.close()+++def test_stamp_claim_publishes_the_card_and_an_ordinary_claim_stays_empty():+ from gateway.session_authority import SessionAuthority+ from gateway.session_contract import SessionRef+ from gateway.session_events import SessionEvents+ published = []+ stream = SessionEvents()+ stream.publish = lambda sid, payload, *, event_type: published.append((event_type, payload))+ authority = SimpleNamespace(epoch=3, executing={}, _publish_pending=lambda ref: None)+ live = SimpleNamespace(event_stream=stream)+ ref = SessionRef("p", SID)+ automation = {"text": MODEL_TEXT, "local_automation_v1": {+ "identity": "i", "owner": SID, "route": "r", "target": SID,+ "display_kind": "process_complete", "display_text": DISPLAY}}+ SessionAuthority._stamp_claim(authority, ref, live, {"generation": 9, "admission_id": "adm-9", "payload": automation})+ SessionAuthority._stamp_claim(authority, ref, live, {"generation": 10, "admission_id": "adm-10",+ "payload": {"text": "typed"}})+ assert published == [("message.start", {"display_kind": "process_complete", "display_text": DISPLAY,+ "text": MODEL_TEXT}), ("message.start", {})]+++def test_claim_stamp_carries_the_automation_card_on_message_start():+ from gateway.session_automation import admission_display+ local = {"text": MODEL_TEXT, "local_automation_v1": {+ "identity": "i", "owner": SID, "route": "r", "target": SID,+ "display_kind": "process_complete", "display_text": DISPLAY}}+ assert admission_display(local) == {"display_kind": "process_complete", "display_text": DISPLAY,+ "text": MODEL_TEXT}+ diagnostic = {"text": "x", "native_text_v1": {"automation": {+ "display_kind": "process_complete", "display_text": DISPLAY, "notification_category": "diagnostic"}}}+ assert admission_display(diagnostic)["notification_category"] == "diagnostic"+ assert admission_display({"text": "typed by the user"}) == {}+ assert admission_display({"text": "x", "local_automation_v1": {"identity": "i"}}) == {}diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex a6b65eac320..c08ada7338f 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -113,7 +113,20 @@ event("notice", NoticePayload, doc="Informational one-liner for the session (cap# ── turn stream ───────────────────────────────────────────────────────────────────────────────-event("message.start", None, doc="A turn began streaming; no payload.")+class MessageStartPayload(Payload):+ """``message.start``. Empty from the TUI gateway's emitters and for an ordinary admission;+ ``gateway/session_authority._stamp_claim`` adds an automation admission's async-result card+ (``session_automation.admission_display``: a background-process completion) and its model+ text, so a viewer that did not submit the turn paints the same header the submitter would."""++ display_kind: str | None = None+ display_text: str | None = None+ notification_category: str | None = None+ text: str | None = None+++event("message.start", MessageStartPayload,+ doc="A turn began streaming; an automation turn carries its async-result card.")class StreamDeltaPayload(Payload):