Skip to content

The agent that grows with you

fix(gateway): background completions reach the chat while the launching turn is still running

teknium1704f0b1c91e5
diff --git a/gateway/AGENTS.md b/gateway/AGENTS.md
index db0534fae67..52fe85fb5be 100644
--- a/gateway/AGENTS.md
+++ b/gateway/AGENTS.md
@@ -64,6 +64,13 @@ completion and triggers a new agent turn. Verbosity: `display.background_process
tail), `all` (running updates + final raw output), `result` (final raw output only), `error`
(final raw output only on non-zero exit), `off`.
+The watcher is armed on the gateway loop at registration time (`terminal_tool_background.py::
+_register_completion_watcher` → `run_notifications.py::arm_process_watcher`); `pending_watchers`
+is only the fallback for processes registered before the gateway serves (checkpoint recovery) or
+while it stops, drained at startup and post-turn. Agent-notify watchers send no user-facing
+receipt (the agent's next turn is the report) unless the launching turn is still running at exit
+— then the injection only queues a follow-up, so the concise receipt goes out immediately.
+
The idle completion watcher also drains `watch_match` / `watch_disabled`; no user follow-up is
required. Notify-off drains these without waking. Transport failures are retried; unavailable
durable completion owners/transports do not spend delivery attempts. Profile-namespaced process
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 9810eaa7cf2..a8e13477fdd 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -1707,6 +1707,16 @@ class GatewayNotificationsMixin:
new_output = _redact_gateway_user_facing_secrets(new_output)
return new_output
+ async def _launching_turn_active(self, platform_name: str, watcher: dict) -> bool:
+ """Whether the session that launched *watcher*'s process is still inside a turn on its
+ adapter (``_active_sessions`` is the base adapter's busy guard)."""
+ session_key = str(watcher.get("session_key") or "").strip()
+ if not session_key:
+ return False
+ source = await asyncio.to_thread(self._build_process_event_source, watcher)
+ adapter = self._resolve_injection_adapter(platform_name, source)
+ return session_key in (getattr(adapter, "_active_sessions", None) or {})
+
async def _send_watcher_message(self, platform_name: str, chat_id, thread_id, message_text: str, watcher: dict) -> None:
from gateway.run import _non_conversational_metadata
source = await asyncio.to_thread(self._build_process_event_source, watcher)
@@ -1778,6 +1788,22 @@ class GatewayNotificationsMixin:
header = "⏳ Background task still running" + (f" — `{short_cmd}`" if short_cmd else "")
return f"{header}\n\nRecent output:\n```\n{new_output.strip()}\n```" if new_output.strip() else header
+ def arm_process_watcher(self, watcher: dict) -> bool:
+ """Start ``_run_process_watcher`` for a watcher registered mid-turn, from the agent's
+ tool thread. Waiting for the post-turn drain leaves a process that finishes while its
+ launching turn is still running with no watcher at all (#112033). False = the gateway
+ is not serving (startup, shutdown): the caller keeps the descriptor in
+ ``pending_watchers`` for the startup / post-turn drain."""
+ loop = getattr(self, "_gateway_loop", None)
+ if not getattr(self, "_running", False) or loop is None or not loop.is_running():
+ return False
+ from agent.async_utils import safe_schedule_threadsafe
+ future = safe_schedule_threadsafe(
+ self._run_process_watcher(watcher), loop, logger=logger,
+ log_message="Live process watcher arming failed",
+ )
+ return future is not None
+
async def _run_process_watcher(self, watcher: dict) -> None:
"""Poll a background process and push updates until it exits. Mode
(``display.background_process_notifications``): concise (default one-liner; failures append
@@ -1820,11 +1846,23 @@ class GatewayNotificationsMixin:
synth_text = format_process_notification(completion_evt)
if not synth_text:
break
+ # Captured before injection: afterwards the key is busy either way (the injected
+ # turn itself installs the guard).
+ turn_busy = await self._launching_turn_active(platform_name, watcher)
delivered = await self._enqueue_process_completion_notification(synth_text, completion_evt)
if delivered is False:
# The process remains terminal; retry after failed adapter injection instead
# of suppressing the result.
continue
+ # The agent normally reports the result itself, so the chat gets no separate receipt.
+ # While the launching turn is still running the injection only queues a follow-up, and
+ # the chat would stay mute for as long as that turn lasts (#112033): send the concise
+ # receipt now.
+ if turn_busy and (notify_mode in {"concise", "all", "result"} or (
+ notify_mode == "error" and session.exit_code not in {0, None}
+ )):
+ message_text = self._format_process_final_message(session_id, session, "concise")
+ await self._send_watcher_message(platform_name, chat_id, thread_id, message_text, watcher)
break
# Text-only notification; skip when already consumed via wait/log (the agent_notify branch
# FALLS THROUGH here, hence the re-check).
diff --git a/tests/tools/test_terminal_watcher_arming.py b/tests/tools/test_terminal_watcher_arming.py
new file mode 100644
index 00000000000..735f78f1024
--- /dev/null
+++ b/tests/tools/test_terminal_watcher_arming.py
@@ -0,0 +1,49 @@
+"""Gateway completion watchers are armed at launch, not only after the turn ends.
+
+A ``notify_on_complete`` process that finishes while its launching turn is still running
+used to sit in ``pending_watchers`` until the post-turn drain, leaving the chat mute for
+the whole turn (#112033).
+"""
+
+from types import SimpleNamespace
+
+from tools.process_registry import ProcessRegistry
+from tools.terminal_tool_background import _register_completion_watcher
+
+
+def _proc_session():
+ return SimpleNamespace(
+ id="proc_active", watcher_platform="telegram", watcher_chat_id="123",
+ watcher_user_id="u", watcher_user_name="Ada", watcher_thread_id="",
+ watcher_message_id="", parent_session_id="",
+ )
+
+
+def _install_runner(monkeypatch, runner):
+ import gateway.run as gateway_run
+ monkeypatch.setattr(gateway_run, "_gateway_runner_ref", lambda: runner)
+
+
+def test_live_gateway_arms_watcher_at_registration(monkeypatch):
+ armed = []
+ _install_runner(monkeypatch, SimpleNamespace(arm_process_watcher=lambda w: armed.append(w) or True))
+ registry = ProcessRegistry()
+
+ _register_completion_watcher(registry, _proc_session(), "agent:main:telegram:dm:123")
+
+ assert [w["session_id"] for w in armed] == ["proc_active"]
+ assert armed[0]["notify_on_complete"] is True and armed[0]["chat_id"] == "123"
+ assert registry.pending_watchers == []
+
+
+def test_watcher_stays_pending_without_a_serving_gateway(monkeypatch):
+ """No runner (CLI-side import) and a runner that is not serving both keep the
+ startup / post-turn drain path."""
+ registry = ProcessRegistry()
+ _install_runner(monkeypatch, None)
+ _register_completion_watcher(registry, _proc_session(), "agent:main:telegram:dm:123")
+
+ _install_runner(monkeypatch, SimpleNamespace(arm_process_watcher=lambda w: False))
+ _register_completion_watcher(registry, _proc_session(), "agent:main:telegram:dm:123")
+
+ assert [w["session_id"] for w in registry.pending_watchers] == ["proc_active", "proc_active"]
diff --git a/tools/terminal_tool_background.py b/tools/terminal_tool_background.py
index 3824a795442..eb70a1fc6c6 100644
--- a/tools/terminal_tool_background.py
+++ b/tools/terminal_tool_background.py
@@ -7,6 +7,7 @@ monkeypatch points authoritative.
import json
import logging
+import sys
from typing import Any, List, Optional
logger = logging.getLogger("tools.terminal_tool")
@@ -115,15 +116,26 @@ def _apply_async_support(proc_session, result_data, notify_on_complete, watch_pa
def _register_completion_watcher(process_registry, proc_session, session_key) -> None:
"""Gateway mode: register a fast watcher so completion triggers a new
- agent turn (CLI mode uses the completion_queue directly)."""
+ agent turn (CLI mode uses the completion_queue directly).
+
+ Armed on the live gateway loop right away: the post-turn drain alone leaves a
+ process that finishes while its launching turn is still running unwatched, and
+ the chat mute for as long as that turn lasts (#112033). Before the gateway
+ serves, or while it stops, the descriptor waits in ``pending_watchers`` for the
+ startup / post-turn drain instead."""
proc_session.watcher_interval = 5
- process_registry.pending_watchers.append({
+ watcher = {
"session_id": proc_session.id, "check_interval": 5, "session_key": session_key,
"platform": proc_session.watcher_platform,
**{attr.removeprefix("watcher_"): getattr(proc_session, attr)
for attr, _ in _ROUTING_FIELDS[:-1]},
"notify_on_complete": True, "parent_session_id": proc_session.parent_session_id,
- })
+ }
+ runner_ref = getattr(sys.modules.get("gateway.run"), "_gateway_runner_ref", None)
+ runner = runner_ref() if callable(runner_ref) else None
+ if runner is not None and runner.arm_process_watcher(watcher):
+ return
+ process_registry.pending_watchers.append(watcher)
def spawn_background_process(
diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.md
index 6953dd1f7eb..f6a932a2ae9 100644
--- a/website/docs/user-guide/messaging/index.md
+++ b/website/docs/user-guide/messaging/index.md
@@ -538,6 +538,8 @@ You can also set this via environment variable:
HERMES_BACKGROUND_NOTIFICATIONS=result
```
+With `terminal(background=true, notify_on_complete=true)` the finished process starts a new agent turn and the agent reports the result itself, so no separate status line is sent. The exception is a process that finishes while the turn that launched it is still running: the completion is queued as the agent's next turn and you get the one-line `concise` status right away (unless the mode is `off`, or `error` with a zero exit code), instead of silence until that turn ends.
+
### Use Cases
- **Server monitoring** — "/bg Check the health of all services and alert me if anything is down"