Skip to content

The agent that grows with you

fix(gateway): a local process completion persists as a process_complete card

Tekniumff770cb76985
diff --git a/gateway/response_filters.py b/gateway/response_filters.py
index 948924e8324..a9238e2f8d0 100644
--- a/gateway/response_filters.py
+++ b/gateway/response_filters.py
@@ -28,10 +28,13 @@ _BRACKETED_SILENCE_MARKERS = tuple(
sorted(m for m in LIVE_GATEWAY_SILENT_MARKERS if m.startswith("["))
)
-# The persisted user-row kind of a self-injected MessageEvent(internal=True) turn — the only
-# machinery kind the gateway produces; only these may vanish on a bare silence marker.
+# The persisted user-row kind of a self-injected MessageEvent(internal=True) turn; only these
+# machinery kinds may vanish on a bare silence marker.
INTERNAL_NOTIFICATION_DISPLAY_KIND = "internal_notification"
-MACHINERY_DISPLAY_KINDS = frozenset({INTERNAL_NOTIFICATION_DISPLAY_KIND})
+# Async-result cards a gateway producer may name on its own internal event (with a display_text),
+# the same rows the in-process TUI persisted. A closed set: never a client-chosen presentation.
+PRODUCER_NOTICE_DISPLAY_KINDS = frozenset({"process_complete"})
+MACHINERY_DISPLAY_KINDS = frozenset({INTERNAL_NOTIFICATION_DISPLAY_KIND, *PRODUCER_NOTICE_DISPLAY_KINDS})
# Longer than any marker could plausibly be, even with stray punctuation.
_MARKER_LENGTH_CAP = 64
@@ -108,11 +111,23 @@ def display_kind_for_event(event: Any) -> str | None:
by the gateway poller, never inferred from inbound text), but it deliberately stays
non-internal so authorization and the emergency stop still apply to it.
"""
+ if getattr(event, "internal", False) and display_metadata_for_event(event):
+ return event.metadata["display_kind"]
if getattr(event, "internal", False) or getattr(event, "_heartbeat_session_id", None):
return INTERNAL_NOTIFICATION_DISPLAY_KIND
return None
+def display_metadata_for_event(event: Any) -> dict:
+ """``{"display_text": ...}`` for an internal event whose producer named an async-result card."""
+ metadata = getattr(event, "metadata", None) or {}
+ text = metadata.get("display_text")
+ if (getattr(event, "internal", False) and metadata.get("display_kind") in PRODUCER_NOTICE_DISPLAY_KINDS
+ and isinstance(text, str) and text.strip()):
+ return {"display_text": text}
+ return {}
+
+
def is_machinery_display_kind(display_kind: Any) -> bool:
"""Only a machinery turn may vanish on a bare silence marker; a human turn gets a visible fallback.
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 3eb13a3942e..dcdea67f1ce 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -1319,6 +1319,13 @@ class GatewayNotificationsMixin:
metadata["gateway_session_id"] = parent_session_id
if evt.get('_automation_identities'):
metadata['automation_identities'] = evt['_automation_identities']
+ if source.platform == Platform.LOCAL and evt.get("type", "completion") == "completion":
+ # A local completion persists as the async-result card the in-process TUI wrote;
+ # messaging rows stay internal_notification, as on main.
+ from tools.process_registry_notifications import (
+ PROCESS_COMPLETE_DISPLAY_KIND, process_completion_display_text)
+ metadata["display_kind"] = PROCESS_COMPLETE_DISPLAY_KIND
+ metadata["display_text"] = evt.get("_display_text") or process_completion_display_text([evt])
# The queued event's ``message_id`` is the message that STARTED the process, and the
# persisted origin carries the same stale id. A synthetic completion is not a reply to
# it: by delivery time the user has often continued elsewhere, and an event anchored
@@ -1701,10 +1708,13 @@ class GatewayNotificationsMixin:
entries_to_deliver = entries
synth_text = (entries_to_deliver[0][0] if len(entries_to_deliver) == 1
else self._format_coalesced_process_completions(entries_to_deliver))
+ from tools.process_registry_notifications import process_completion_display_text
+ display_text = process_completion_display_text([evt for _text, evt, _future in entries_to_deliver])
# A duplicate primary returns None from the dedupe seam; try the next identity so a fresh
# sibling is never discarded with it.
delivered = None
for _text, candidate_evt, _future in entries_to_deliver:
+ candidate_evt = dict(candidate_evt, _display_text=display_text)
if getattr(self, 'session_authority', None) is not None:
candidate_evt = dict(candidate_evt, _automation_identities=[
producer_identity(self, evt) for _text, evt, _future in entries_to_deliver])
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index c8727567788..4434db1bd6b 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -26,7 +26,8 @@ from gateway.media_repair import repair_explicit_computer_use_media_paths
from gateway.platforms.base import BasePlatformAdapter, ProcessingOutcome
from gateway.platforms.event import MessageEvent
from gateway.response_filters import (
- display_kind_for_event, is_machinery_display_kind, reply_expected_metadata, silence_allowed,
+ display_kind_for_event, display_metadata_for_event, is_machinery_display_kind, reply_expected_metadata,
+ silence_allowed,
)
from gateway.warning_notifications import diagnostic_metadata, diagnostic_turn_muted, diagnostic_wake_muted
from gateway.session import (
@@ -280,7 +281,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
persist_user_display_kind=prepared.persist_user_display_kind,
reply_expected=event.reply_expected,
persist_user_display_metadata={
- "gateway_input_owner": prepared.persistence_owner,
+ "gateway_input_owner": prepared.persistence_owner, **display_metadata_for_event(event),
**reply_expected_metadata(event.reply_expected), **diagnostic_metadata(event)},
message_type=event.message_type,
scheduled_heartbeat=bool(getattr(event, "_heartbeat_session_id", None)),
@@ -2027,6 +2028,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
persist_user_display_kind=next_display_kind,
reply_expected=next_reply_expected,
persist_user_display_metadata={
+ **display_metadata_for_event(pending_event),
**reply_expected_metadata(next_reply_expected), **diagnostic_metadata(pending_event)} or None,
)
except asyncio.CancelledError:
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index 256265d357b..658d004fe04 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -361,8 +361,11 @@ class GatewayTurnPersistenceMixin:
}
if prepared.persist_user_display_kind:
_user_entry["display_kind"] = prepared.persist_user_display_kind
- if prepared.persistence_owner:
- _user_entry["display_metadata"] = {"gateway_input_owner": prepared.persistence_owner}
+ from gateway.response_filters import display_metadata_for_event
+ display_metadata = {**({"gateway_input_owner": prepared.persistence_owner} if prepared.persistence_owner else {}),
+ **display_metadata_for_event(event)}
+ if display_metadata:
+ _user_entry["display_metadata"] = display_metadata
if getattr(event, "message_id", None):
_user_entry["message_id"] = str(event.message_id)
return _user_entry
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index 62278707b68..542e780d9d3 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -63,10 +63,27 @@ def automation_notification_metadata(metadata):
raise RuntimeStoreError('invalid_params')
return {'notification_category': category} if category == 'diagnostic' else {}
+
+_DISPLAY_TEXT_LIMIT = 2000
+
+
+def automation_display_metadata(metadata):
+ """Validate a producer's async-result card: both keys or neither, kind from the closed set."""
+ if 'display_kind' not in metadata and 'display_text' not in metadata:
+ return {}
+ from gateway.response_filters import PRODUCER_NOTICE_DISPLAY_KINDS
+ kind, text = metadata.get('display_kind'), metadata.get('display_text')
+ if (kind not in PRODUCER_NOTICE_DISPLAY_KINDS or not isinstance(text, str) or not text.strip()
+ or len(text) > _DISPLAY_TEXT_LIMIT):
+ raise RuntimeStoreError('invalid_params')
+ return {'display_kind': kind, 'display_text': text}
+
# notification_origin / original_trigger_message_id are producer debug context (#52694) and are not
-# persisted; notification_category="diagnostic" rides the snapshot so the replayed wake still mutes.
+# persisted; notification_category="diagnostic" rides the snapshot so the replayed wake still mutes,
+# and display_kind/display_text so the persisted row is the card the producer named.
_AUTOMATION_METADATA = frozenset({'gateway_session_key', 'gateway_session_id', 'automation_identities',
- 'turn_author', 'notification_origin', 'original_trigger_message_id', 'notification_category'})
+ 'turn_author', 'notification_origin', 'original_trigger_message_id', 'notification_category',
+ 'display_kind', 'display_text'})
def snapshot_automation(authority, adapter, event, identity):
@@ -76,7 +93,7 @@ def snapshot_automation(authority, adapter, event, identity):
or event.media_urls or event.prompt_response or event.source.platform == Platform.API_SERVER
or set(event.metadata) - _AUTOMATION_METADATA):
raise RuntimeStoreError('invalid_params')
- notification = automation_notification_metadata(event.metadata)
+ notification = automation_notification_metadata(event.metadata) | automation_display_metadata(event.metadata)
entry = _owner(runner, event)
if event.source.platform == Platform.LOCAL:
return snapshot_local_automation(authority, adapter, event, identity, entry)
@@ -132,6 +149,7 @@ def snapshot_local_automation(authority, adapter, event, identity, entry):
descriptor = {'identity': identity, 'owner': ref.session_id,
'route': entry.session_key, 'target': entry.session_id}
descriptor.update(automation_notification_metadata(event.metadata))
+ descriptor.update(automation_display_metadata(event.metadata))
if event.metadata.get('turn_author') is not None:
from agent.turn_author import parse_turn_author
descriptor['turn_author'] = parse_turn_author(event.metadata['turn_author'])
@@ -169,6 +187,7 @@ def restore_local_automation(authority, ref, row):
message_id=descriptor['identity'], metadata={'gateway_session_key': live.route,
'gateway_session_id': entry.session_id})
event.metadata.update(automation_notification_metadata(descriptor))
+ event.metadata.update(automation_display_metadata(descriptor))
if descriptor.get('turn_author') is not None:
event.metadata['turn_author'] = deepcopy(descriptor['turn_author'])
if descriptor.get('heartbeat'):
diff --git a/gateway/session_envelope.py b/gateway/session_envelope.py
index 826520edd37..83b0cc6ab7a 100644
--- a/gateway/session_envelope.py
+++ b/gateway/session_envelope.py
@@ -151,8 +151,9 @@ def restore_native(payload, runner=None):
event._heartbeat_session_id = envelope['automation']['heartbeat']
event.metadata = {'gateway_session_key': envelope['route'],
'gateway_session_id': envelope['automation']['owner']}
- from gateway.session_automation import automation_notification_metadata
+ from gateway.session_automation import automation_display_metadata, automation_notification_metadata
event.metadata.update(automation_notification_metadata(envelope['automation']))
+ event.metadata.update(automation_display_metadata(envelope['automation']))
return event
diff --git a/tests/gateway/fixtures/local_automation_peer.py b/tests/gateway/fixtures/local_automation_peer.py
index 70d21c4f71f..cdc8c65814f 100644
--- a/tests/gateway/fixtures/local_automation_peer.py
+++ b/tests/gateway/fixtures/local_automation_peer.py
@@ -84,9 +84,15 @@ def probe(base, source):
assert 'REAL_TERMINAL_COMPLETION' in str(texts[-1]), texts
assert sum('REAL_TERMINAL_COMPLETION' in str(text) for text in texts) == 1, texts
with sqlite3.connect(home / 'state.db') as db:
- notices = db.execute("SELECT display_kind FROM messages WHERE role='user' AND content LIKE ?",
- ('%REAL_TERMINAL_COMPLETION%',)).fetchall()
- assert notices == [('internal_notification',)], notices
+ notices = db.execute("SELECT display_kind, json_extract(display_metadata, '$.display_text') FROM messages"
+ " WHERE role='user' AND content LIKE ?", ('%REAL_TERMINAL_COMPLETION%',)).fetchall()
+ # A completion is the same async-result card the in-process TUI persisted; a watch match is not one.
+ assert len(notices) == 1, notices
+ if watch:
+ assert notices[0][0] == 'internal_notification', notices
+ else:
+ assert notices[0][0] == 'process_complete', notices
+ assert str(notices[0][1]).startswith('Background Process Finished: '), notices
prefixes = [json.dumps([m for m in r['messages'] if m['role'] in ('system', 'developer')], sort_keys=True)
for r in model.requests if r.get('messages')]
assert len(set(prefixes)) == 1, 'automation changed the cached system prefix'
diff --git a/tests/gateway/test_automation_notification_category.py b/tests/gateway/test_automation_notification_category.py
index 5953a594466..1a196767e81 100644
--- a/tests/gateway/test_automation_notification_category.py
+++ b/tests/gateway/test_automation_notification_category.py
@@ -94,6 +94,24 @@ async def test_bot_invalid_category_refuses_before_admission(tmp_path, monkeypat
authority.db.close()
+async def test_display_kind_is_a_closed_producer_set(tmp_path, monkeypatch):
+ """Only gateway-produced notice kinds ride an automation admission; anything else refuses."""
+ from gateway.response_filters import display_kind_for_event, display_metadata_for_event
+ from gateway.session_automation import automation_display_metadata
+ trusted = {'display_kind': 'process_complete', 'display_text': 'Background Process Finished: true'}
+ assert automation_display_metadata(trusted) == trusted
+ event = MessageEvent(text='notice', internal=True, metadata=dict(trusted))
+ assert display_kind_for_event(event) == 'process_complete'
+ assert display_metadata_for_event(event) == {'display_text': trusted['display_text']}
+ assert display_kind_for_event(MessageEvent(text='x', metadata=dict(trusted))) is None
+ for bad in ({'display_kind': 'hidden', 'display_text': 'x'}, {'display_kind': 'process_complete'},
+ {'display_text': 'x'}, {'display_kind': 'process_complete', 'display_text': ''},
+ {'display_kind': 'process_complete', 'display_text': 'x' * 2001}):
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ automation_display_metadata(bad)
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize('category', ['result', 'diagnostic'])
async def test_native_automation_category_roundtrip(tmp_path, monkeypatch, category):