The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(process): heartbeats wake the agent only on new output, and never as a user bubble
Brooklyn Nicholson8cb4fdc9257a
diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.tsindex 6b2be68a385..d5176fd531f 100644--- a/apps/desktop/src/lib/chat-messages.test.ts+++ b/apps/desktop/src/lib/chat-messages.test.ts@@ -450,6 +450,29 @@ describe('toChatMessages', () => {])})+ it('never paints a background-process heartbeat wake as a user bubble', () => {+ // Current backends type the wake `display_kind: 'hidden'`; a row persisted by an older+ // backend arrives untyped and must disappear the same way — the user never wrote it.+ const legacyWake =+ '[Background process proc_ea2cdb25d899 heartbeat #7 — still running after 7m2s (next in 60s; you will also be told when it exits).\nCommand: zsh -ic hgui\nOutput since last heartbeat:\n(no new output since the last heartbeat)]'+ const messages = toChatMessages([+ { role: 'user', content: 'start the dev server', timestamp: 1 },+ { role: 'assistant', content: 'Started on slot 0.', timestamp: 2 },+ { role: 'user', content: legacyWake, timestamp: 3 },+ { role: 'assistant', content: 'Still running normally.', timestamp: 4 },+ { role: 'user', content: legacyWake.replace('#7', '#8'), display_kind: 'hidden', timestamp: 5 },+ { role: 'assistant', content: 'HMR rebuilt after the edit.', timestamp: 6 }+ ])++ expect(messages.map(message => message.role)).toEqual(['user', 'assistant', 'assistant', 'assistant'])+ expect(messages.map(chatMessageText)).toEqual([+ 'start the dev server',+ 'Started on slot 0.',+ 'Still running normally.',+ 'HMR rebuilt after the edit.'+ ])+ })+// Hermes closes a failed turn with an assistant-role row (agent/turn_failure_copy.py);// painted as the model's reply it read as the assistant refusing the request.it('renders the failed-turn boundary as a Hermes notice, not a model reply', () => {diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.tsindex 68b0136ee8e..22556c1f8fe 100644--- a/apps/desktop/src/lib/chat-messages/hydration.ts+++ b/apps/desktop/src/lib/chat-messages/hydration.ts@@ -23,6 +23,10 @@ import {import type { ChatMessage, ChatMessagePart } from './types'const ATTACHED_CONTEXT_MARKER_RE = /(?:^|\n)--- Attached Context ---\s*\n/+// A background-process heartbeat wake persisted by a backend older than the+// one that types those rows `display_kind=hidden`. It is model scaffolding,+// not something the user wrote, so it never paints as a bubble.+const LEGACY_HEARTBEAT_ROW_RE = /^\[Background process \S+ heartbeat #\d+ /const CONTEXT_WARNINGS_MARKER_RE = /(?:^|\n)--- Context Warnings ---[\s\S]*$/const CONTEXT_REF_RE = /@(file|folder|url|image|tool|terminal):(?:"[^"\n]+"|'[^'\n]+'|`[^`\n]+`|\S+)/g@@ -136,8 +140,16 @@ function displayContentForMessage(role: SessionMessage['role'], content: unknownreturn [missing.join('\n'), visibleText].filter(Boolean).join('\n\n') || visibleText}-function transcriptContent(displayKind: SessionMessage['display_kind'], content: string): string | null {- return displayKind === 'hidden' ? null : content+function transcriptContent(+ displayKind: SessionMessage['display_kind'],+ role: SessionMessage['role'],+ content: string+): string | null {+ if (displayKind === 'hidden') {+ return null+ }++ return role === 'user' && LEGACY_HEARTBEAT_ROW_RE.test(content.trim()) ? null : content}/**@@ -364,6 +376,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {const rawDisplayContent = transcriptContent(message.display_kind,+ message.role,timelineDisplayContent(message, displayContentForMessage(message.role, content)))diff --git a/hermes_cli/cli_process_notifications.py b/hermes_cli/cli_process_notifications.pyindex e1f990a1110..8123189638a 100644--- a/hermes_cli/cli_process_notifications.py+++ b/hermes_cli/cli_process_notifications.py@@ -37,7 +37,8 @@ class CLIProcessNotificationsMixin:from tools.process_registry import process_registryfrom tools.async_delegation import claim_event_delivery, complete_event_deliveryfrom tools.process_registry_notifications import (- ProcessNotificationBatch, TimelineNotification, group_process_notifications)+ HEARTBEAT_DISPLAY_KIND, ProcessNotificationBatch, TimelineNotification, group_process_notifications,+ heartbeat_display_text)claimed = []for event, text in process_registry.drain_notifications(@@ -49,13 +50,17 @@ class CLIProcessNotificationsMixin:claimed.append((event, text))complete_event_delivery(event, claim)if self._background_notifications_suppressed():- return+ # Subagent results are not process notifications: they still land.+ claimed = [(event, text) for event, text in claimed if event.get("type") == "async_delegation"]for notifications in group_process_notifications(claimed):event, text = notifications[0]- if event.get("type", "completion") == "completion":+ evt_type = event.get("type", "completion")+ if evt_type == "completion":pending = ProcessNotificationBatch(notifications)+ elif evt_type == "heartbeat":+ pending = TimelineNotification(text, heartbeat_display_text(event), HEARTBEAT_DISPLAY_KIND)else:- pending = TimelineNotification.for_delegation(text, event) if event.get("type") == "async_delegation" else text+ pending = TimelineNotification.for_delegation(text, event) if evt_type == "async_delegation" else textfrom agent.notification_presentation import diagnostic_process_eventif diagnostic_process_event(event) and not isinstance(pending, TimelineNotification):pending = TimelineNotification(text, text, "internal_notification", "diagnostic")diff --git a/tests/hermes_cli/test_process_notification_display.py b/tests/hermes_cli/test_process_notification_display.pyindex fc2eaa37615..69b26f96523 100644--- a/tests/hermes_cli/test_process_notification_display.py+++ b/tests/hermes_cli/test_process_notification_display.py@@ -40,6 +40,45 @@ def test_drain_honors_background_process_notifications_off(monkeypatch, mode, exif expect_injected:assert cli._pending_input.get_nowait() is not None++def test_off_mutes_process_wakes_but_subagent_results_still_land(monkeypatch):+ """``off`` is about background PROCESSES: a finished ``delegate_task(background=true)`` is a+ result the user asked for, never a notification to opt out of."""+ delegation = {"type": "async_delegation", "delegation_id": "d1", "session_key": "display-session",+ "results": [{"status": "completed", "summary": "done", "goal": "audit"}]}+ events = [_event("proc_a", 0), {**_event("proc_b", 0), "type": "heartbeat", "seq": 1, "output": "line"}, delegation]+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id = "display-session"+ cli._pending_input = queue.Queue()+ monkeypatch.setattr("tools.process_registry.process_registry", _registry(events))+ monkeypatch.setattr("tools.async_delegation.claim_event_delivery", lambda *a: "claimed")+ monkeypatch.setattr("tools.async_delegation.complete_event_delivery", lambda *a: None)+ monkeypatch.setattr("cli.CLI_CONFIG", {"display": {"background_process_notifications": "off"}})+ cli._drain_process_notifications("cli-post-turn")+ queued = cli._pending_input.get_nowait()+ assert cli._pending_input.empty()+ assert queued.display_kind == "async_delegation_complete"+++def test_heartbeat_wake_paints_one_line_and_persists_hidden(monkeypatch):+ """The model gets the output delta; the human gets a one-line receipt, and the persisted row is+ typed ``hidden`` so Desktop/TUI never paint the wake as a user bubble."""+ from tools.process_registry_notifications import HEARTBEAT_DISPLAY_KIND, heartbeat_display_text+ beat = {**_event("proc_hb", None), "type": "heartbeat", "seq": 3, "elapsed": 422, "interval": 60,+ "output": "web tsc=0\nSECRET_OUTPUT_LINE"}+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id = "display-session"+ cli._pending_input = queue.Queue()+ monkeypatch.setattr("tools.process_registry.process_registry", _registry([beat]))+ monkeypatch.setattr("tools.async_delegation.claim_event_delivery", lambda *a: "claimed")+ monkeypatch.setattr("tools.async_delegation.complete_event_delivery", lambda *a: None)+ cli._drain_process_notifications("cli-idle")+ queued = cli._pending_input.get_nowait()+ assert queued == format_process_notification(beat)+ assert queued.display_kind == HEARTBEAT_DISPLAY_KIND == "hidden"+ assert queued.display_text == heartbeat_display_text(beat)+ assert "SECRET_OUTPUT_LINE" not in queued.display_text and "long-build.sh" in queued.display_text+def test_process_completion_display_keeps_payload_separate_across_surfaces(monkeypatch, capsys, tmp_path):events = [_event("proc_1", 0)]payload = format_process_notification(events[0])diff --git a/tests/tools/test_process_heartbeat.py b/tests/tools/test_process_heartbeat.pyindex 62fecb33033..b708a2bc457 100644--- a/tests/tools/test_process_heartbeat.py+++ b/tests/tools/test_process_heartbeat.py@@ -63,6 +63,29 @@ def test_heartbeat_carries_only_new_output_and_stops_at_exit(tmp_path, monkeypattimeout=2.5)+def test_a_tick_with_no_new_output_queues_nothing():+ """Every queued heartbeat costs the owning session a full model turn, so a quiet tick is+ skipped rather than delivered as "(no new output)"; the next tick with output still carries+ exactly the delta and the sequence counts delivered beats only."""+ registry = ProcessRegistry()+ session = pr.ProcessSession(id="proc_quiet", command="sleep 600", notify_on_complete=True)+ session._heartbeat_last = 0.0++ registry._emit_heartbeat(session, now=100.0)+ registry._emit_heartbeat(session, now=200.0)+ assert _drain(registry.completion_queue) == []+ assert session._heartbeat_last == 200.0 and session._heartbeat_seq == 0++ session.output_buffer += "first line\n"+ session.total_output_chars += len("first line\n")+ registry._emit_heartbeat(session, now=300.0)+ (beat,) = _drain(registry.completion_queue)+ assert beat["type"] == "heartbeat" and beat["seq"] == 1 and beat["output"] == "first line\n"++ registry._emit_heartbeat(session, now=400.0)+ assert _drain(registry.completion_queue) == []++def test_schema_minimum_heartbeat_is_disabled_for_foreground(monkeypatch):from tools import terminal_tool as ttdiff --git a/tests/tui_gateway/test_heartbeat_wakes.py b/tests/tui_gateway/test_heartbeat_wakes.pynew file mode 100644index 00000000000..67e7743a4da--- /dev/null+++ b/tests/tui_gateway/test_heartbeat_wakes.py@@ -0,0 +1,69 @@+"""A background-process heartbeat is a wake for the model, not a message from the user.++Desktop and the TUI paint every ``prompt.submit`` row as a user bubble unless the backend types it+otherwise, and the process row on the status stack already tells the human the job is running —+so a heartbeat row is ``hidden`` and ``display.background_process_notifications: off`` mutes every+process-driven wake on these surfaces exactly as it does on the messaging gateway.+"""++from __future__ import annotations++import queue+import threading+from types import SimpleNamespace++import pytest+import hermes_yaml as yaml++from tui_gateway import server++HEARTBEAT = {"type": "heartbeat", "session_id": "proc_hb", "seq": 2, "elapsed": 130.0, "interval": 60,+ "command": "npm test", "output": "1 failing\n"}+COMPLETION = {"type": "completion", "session_id": "proc_done", "command": "npm test", "exit_code": 1}+DELEGATION = {"type": "async_delegation", "delegation_id": "d1", "session_key": "s", "results": []}+++def surface(monkeypatch):+ submits: list = []+ monkeypatch.setattr("tools.async_delegation.claim_event_delivery", lambda evt, consumer: "claimed")+ monkeypatch.setattr("tools.async_delegation.complete_event_delivery", lambda *a, **k: None)+ monkeypatch.setattr(server, "_run_prompt_submit", lambda rid, sid, session, text, **kw: submits.append((text, kw)))+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)+ monkeypatch.setattr(server, "_session_owns_notification_event", lambda sid, session, evt: True)+ return submits+++def _session(profile_home=None) -> dict:+ return {"history_lock": threading.RLock(), "running": False, "history": [], "agent": None,+ "profile_home": str(profile_home) if profile_home else None}+++def test_a_heartbeat_wake_is_typed_hidden(surface):+ session = _session()+ assert server._notif_claim_turn(session) is True++ server._notif_dispatch_event("sid", session, dict(HEARTBEAT), "beat text")++ ((text, kwargs),) = surface+ assert text == "beat text"+ assert kwargs["display_kind"] == "hidden"+++def test_off_mutes_process_wakes_but_subagent_results_still_land(surface, tmp_path):+ """The same ``off`` the messaging gateway honours; a finished ``delegate_task(background=true)``+ is a result the user asked for, never a notification to opt out of."""+ (tmp_path / "config.yaml").write_text(+ yaml.safe_dump({"display": {"background_process_notifications": "off"}}), encoding="utf-8"+ )+ session = _session(tmp_path)+ registry = SimpleNamespace(completion_queue=queue.Queue(), is_completion_consumed=lambda session_id: False)+ completions: list = []++ for evt in (HEARTBEAT, COMPLETION):+ assert server._notif_handle_event("sid", session, dict(evt), set(), registry, lambda e: "t", completions) is True+ assert completions == [] and surface == [], "a muted wake never reaches a turn"+ assert session["running"] is False, "and never keeps the session claimed"++ assert server._notif_handle_event("sid", session, dict(DELEGATION), set(), registry, lambda e: "t", completions) is True+ assert [kw["display_kind"] for _, kw in surface] == ["async_delegation_complete"]diff --git a/tools/process_registry.py b/tools/process_registry.pyindex ca6232ee48a..6dfeb9739ef 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -700,14 +700,19 @@ class ProcessRegistry(ProcessCheckpointMixin):self._emit_heartbeat(session, now)def _emit_heartbeat(self, session: ProcessSession, now: float) -> None:+ """Queue a heartbeat carrying the output since the last one. A tick with nothing new is+ skipped outright: every queued event costs the owner a full model turn, and "still running,+ no output" is already visible on the process surfaces (status stack, /agents dock)."""+ session._heartbeat_last = nowwith session._lock:delta = session.total_output_chars - session._heartbeat_total_at_lastoutput = session.output_buffer[-delta:] if delta > 0 else ""session._heartbeat_total_at_last = session.total_output_chars+ if not output:+ returnif len(output) > HEARTBEAT_OUTPUT_CHARS:cut = len(output) - HEARTBEAT_OUTPUT_CHARSoutput = f"...({cut} earlier characters omitted)\n" + output[-HEARTBEAT_OUTPUT_CHARS:]- session._heartbeat_last = nowsession._heartbeat_seq += 1notification = {**self._watch_event_base(session),diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.pyindex 14494a2cec3..4df4eee2897 100644--- a/tools/process_registry_notifications.py+++ b/tools/process_registry_notifications.py@@ -349,6 +349,16 @@ def process_completion_display_text(events: list) -> str:return f"Background Process {outcome}{detail}: {cmd}" if cmd else f"Background Process {outcome}{detail}"+HEARTBEAT_DISPLAY_KIND = "hidden" # a wake, not a message: no surface paints the row+++def heartbeat_display_text(evt: dict) -> str:+ """One-line CLI receipt for a heartbeat wake; the row itself is hidden (``HEARTBEAT_DISPLAY_KIND``)."""+ cmd = _short_command(evt.get("command"))+ age = _format_age(float(evt.get("elapsed") or 0))+ return f"Background Process Output after {age}: {cmd}" if cmd else f"Background Process Output after {age}"++class TimelineNotification(str):"""Queued model text that stays string-compatible, plus the display kind and compact humantitle the surface paints instead of the raw notification wall."""@@ -414,12 +424,11 @@ def format_process_notification(evt: dict) -> "str | None":_attribution = f"Handed off to you by a subagent before it finished. Purpose: {evt['handoff_note']}"attribution = f"{_attribution}\n" if _attribution else ""if evt_type == "heartbeat":- _out = evt.get("output") or "(no new output since the last heartbeat)"return (f"[Background process {_sid} heartbeat #{evt.get('seq', '?')} — still running after "- f"{_format_age(float(evt.get('elapsed') or 0))} (next in {evt.get('interval', '?')}s; "- f"you will also be told when it exits).\n"- f"{attribution}Command: {_cmd}\nOutput since last heartbeat:\n{_out}]")+ f"{_format_age(float(evt.get('elapsed') or 0))} (next in {evt.get('interval', '?')}s when there "+ f"is new output; you will also be told when it exits).\n"+ f"{attribution}Command: {_cmd}\nOutput since last heartbeat:\n{evt.get('output', '')}]")if evt_type == "watch_match":_sup = evt.get("suppressed", 0)return (diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex 326f912ec18..43a43865ac1 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -456,6 +456,15 @@ def _notif_poll_kanban_scoped(sid: str, session: dict) -> None:**({"display_metadata": {"notification_category": "diagnostic"}} if diagnostic else {}))+def _background_notifications_off(session: dict) -> bool:+ """Whether the owning profile set ``display.background_process_notifications: off``. Same+ gate the messaging gateway applies to its process-event injection; only ``off`` matters+ here (the other modes shape gateway chat receipts, not agent wakes)."""+ with _session_profile_runtime_scope(session):+ raw = (_load_cfg().get("display") or {}).get("background_process_notifications")+ return raw is False or str(raw or "").strip().lower() == "off"++def _notif_dispatch_event(sid: str, session: dict, evt: dict, text: str) -> None:"""Run the claimed (running=True) agent turn for one notification event."""from tools.async_delegation import claim_event_delivery, complete_event_delivery, release_event_delivery@@ -470,8 +479,16 @@ def _notif_dispatch_event(sid: str, session: dict, evt: dict, text: str) -> None# from the reaper, keeps its lease, and never reaches its bot mailbox again._notif_release_turn(session)return- kwargs = ({"display_kind": "async_delegation_complete", "display_metadata": _async_delegation_display_metadata(evt)}- if evt.get("type") == "async_delegation" else {})+ evt_type = evt.get("type")+ kwargs: dict = {}+ if evt_type == "async_delegation":+ kwargs = {"display_kind": "async_delegation_complete", "display_metadata": _async_delegation_display_metadata(evt)}+ elif evt_type == "heartbeat":+ # Model-facing scaffolding: the process row on the status stack already says it is running,+ # so the wake never paints as a user bubble (Desktop, TUI and the transcript preview all+ # honour ``hidden``). Only what the agent says about the new output is visible.+ from tools.process_registry_notifications import HEARTBEAT_DISPLAY_KIND+ kwargs = {"display_kind": HEARTBEAT_DISPLAY_KIND}from agent.notification_presentation import diagnostic_process_eventif diagnostic_process_event(evt):kwargs.setdefault("display_metadata", {})["notification_category"] = "diagnostic"@@ -532,6 +549,10 @@ def _notif_handle_event(sid, session, evt, emitted, registry, fmt, deferred, comrender_notification(lambda: _emit("status.update", sid, {"kind": "process", "text": display_text}),platform="tui", diagnostic=diagnostic_process_event(evt))emitted.add(dedup_key)+ if evt_type != "async_delegation" and _background_notifications_off(session):+ # The user opted out of process-driven agent wakes: the status row above is the whole+ # delivery. Subagent results are not process notifications and still land.+ return Trueif evt_type == "completion" and completions is not None:completions.append((evt, text))return Truediff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 357ab37c050..693f6277ed8 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -207,7 +207,7 @@ Granted only to sessions of the desktop setup profile (`role: setup` in its `pro| Tool | Description | Requires environment ||------|-------------|----------------------|| `process_manage` | Manage background processes started with terminal(background=true). Actions: 'list' (show all), 'poll' (check status + new output), 'log' (full output with pagination), 'wait' (block until done or timeout), 'kill' (terminate), 'write' (sen… | — |-| `terminal` | Execute shell commands on a Linux environment. Filesystem persists between calls. Set `background=true` for long-running servers. Set `notify_on_complete=true` (with `background=true`) to get an automatic notification when the process finishes — no polling needed. Add `heartbeat=N` (seconds, min 60) to also receive a periodic notification carrying the output produced since the previous one — for long bounded jobs such as a merge train or a full test suite, so a failure is seen within N seconds instead of at exit. Do NOT use cat/head/tail — use read_file. Do NOT use grep/rg/find — use search_files. | — |+| `terminal` | Execute shell commands on a Linux environment. Filesystem persists between calls. Set `background=true` for long-running servers. Set `notify_on_complete=true` (with `background=true`) to get an automatic notification when the process finishes — no polling needed. Add `heartbeat=N` (seconds, min 60) to also receive a periodic notification carrying the output produced since the previous one — for long bounded jobs such as a merge train or a full test suite, so a failure is seen within N seconds instead of at exit; a tick with no new output is skipped, and the wake is hidden from the transcript on Desktop/TUI (only the agent's reply shows). Do NOT use cat/head/tail — use read_file. Do NOT use grep/rg/find — use search_files. | — |## `desktop_ui` toolsetdiff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.mdindex 083fa5ede7e..047bc448104 100644--- a/website/docs/user-guide/messaging/index.md+++ b/website/docs/user-guide/messaging/index.md@@ -564,7 +564,7 @@ display:| `all` | Running-output updates **and** the final status message with the output tail || `result` | Only the final status message with the output tail (regardless of exit code) || `error` | Only the final status message with the output tail when the exit code is non-zero |-| `off` | No process watcher messages at all |+| `off` | No process watcher messages at all. Also honored by the CLI, TUI and Desktop: background-process completions and heartbeats no longer wake the agent (subagent results still do) |You can also set this via environment variable: