Skip to content

The agent that grows with you

fix(gateway): fence late subagent events and scope fallback rosters to the owning profile

yoniebansd22ccfecd27c
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 432e4079b83..4e10210e454 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -125,8 +125,7 @@ export type GatewayEventPayload = {
install_warning?: string
personality?: string
usage?: Partial<UsageStats>
- // Canonical session.usage ticks carry cumulative counters at the payload
- // top level; older ticker frames nest the desktop Usage shape above.
+ // Canonical session.usage ticks carry cumulative counters at the payload top level; older ticker frames nest the desktop Usage shape above.
api_calls?: number | null
cache_read_tokens?: number | null
completion_tokens?: number | null
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.py
index 92b8c23fa3e..6c0faf71242 100644
--- a/gateway/local_viewer_events.py
+++ b/gateway/local_viewer_events.py
@@ -62,25 +62,56 @@ def show_reasoning(turn) -> bool:
return getattr(live, "show_reasoning", None) is True
+def _is_active_session_subagent(turn, session_id: str, payload: dict) -> bool:
+ subagent_id = payload.get("subagent_id")
+ if not isinstance(subagent_id, str) or not subagent_id:
+ return False
+ import sys
+ registry = sys.modules.get("tools.delegate_tool_registry")
+ if registry is None:
+ return False
+ ctx = getattr(turn, "_ctx", None)
+ holder = getattr(ctx, "agent_holder", None)
+ turn_agent = holder[0] if isinstance(holder, list) and holder else None
+ target_sid = getattr(ctx, "session_id", None) or session_id
+ with registry._active_subagents_lock:
+ record = registry._active_subagents.get(subagent_id)
+ if record is None:
+ return False
+ if turn_agent is not None and registry._is_descendant_of(record.get("agent"), turn_agent):
+ return True
+ return bool(target_sid and record.get("owner_agent_session_id") == target_sid)
+
+
def _publish_subagent(turn, event_type, payload) -> None:
owner = getattr(turn, "_approval_owner", None)
if owner is not None:
authority, session_id, generation = owner
executing = getattr(authority, "executing", None)
if isinstance(executing, dict) and executing.get(session_id) != generation:
- # A background delegate_task outlives the spawning turn's running claim.
- live = authority.sessions.get(session_id)
- if live is not None and hasattr(live, "event_stream"):
- live.event_stream.publish(session_id, payload, event_type=event_type)
+ if not _is_active_session_subagent(turn, session_id, payload):
return
+ # A background delegate_task outlives the spawning turn's running claim; publish without borrowing a later turn's execution identity.
+ live = authority.sessions.get(session_id)
+ stream = getattr(live, "event_stream", None)
+ if stream is not None:
+ import contextlib
+ lock = getattr(stream, "lock", None)
+ with lock if lock is not None else contextlib.nullcontext():
+ saved = getattr(stream, "execution", None)
+ if isinstance(saved, dict):
+ stream.execution = {}
+ try:
+ stream.publish(session_id, payload, event_type=event_type)
+ finally:
+ if isinstance(saved, dict):
+ stream.execution = saved
+ return
turn._publish_execution(event_type, payload)
def publish_progress(turn, event_type, name, preview, kwargs) -> None:
- """``subagent.*``, ``reasoning.available`` and the MoA facade events from the agent's progress
- callback. A classic CLI renders MoA references whatever its reasoning display (main's
- ``_on_tool_progress``); other viewers get them, like the TUI gateway's own emitters, only with
- reasoning shown."""
+ """``subagent.*``, ``reasoning.available`` and the MoA facade events from the agent's progress callback; a classic CLI renders MoA references whatever its reasoning display (main's ``_on_tool_progress``), while other viewers get them only with reasoning shown."""
if isinstance(event_type, str) and event_type.startswith("subagent."):
if event_type == "subagent.text":
return
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 56cae47d8f5..1b156968e62 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -1679,7 +1679,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
if _agent.model == _cfg_model or self._is_intentional_model_switch(session_key, _agent, _cfg_model):
return
with suppress(Exception):
- _agent._evicted_on_fallback = True
+ _agent._evicted_on_fallback = session_key or True
self._evict_cached_agent(session_key)
async def _run_agent_finalize_streaming_tts(self, turn_ctx: TurnContext, adapter: Any) -> None:
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index 5f93d5e622e..003e3234966 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -139,8 +139,9 @@ class GatewayTurnProgressMixin:
"""Callback invoked by agent on tool lifecycle events."""
ctx = self._ctx
if local_viewer_turn(self):
- from gateway import local_viewer_events
- local_viewer_events.publish_progress(self, event_type, tool_name, preview, kwargs)
+ with suppress(Exception):
+ from gateway import local_viewer_events
+ local_viewer_events.publish_progress(self, event_type, tool_name, preview, kwargs)
# Failed subagent → one clean user-facing notice, handled FIRST, before every progress-queue
# gate: platforms with tool_progress off must still hear about a dead delegation.
if event_type == "subagent.complete":
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 42448b087c2..769028b6795 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -1315,13 +1315,15 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
**usage,
**({"persisted_turn": persisted_turn} if persisted_turn else {}),
}
- was_delivered = getattr(agent, "_interim_text_was_delivered", None)
- previewed = bool(result.get("response_previewed") or (
- callable(was_delivered) and bool(final_response) and was_delivered(final_response) is True))
- viewer_meta = {
- **({"billing_block": result["billing_block"]} if isinstance(result.get("billing_block"), dict) else {}),
- **({"warning": result["warning"]} if isinstance(result.get("warning"), str) and result["warning"] else {}),
- }
+ previewed = bool(result.get("response_previewed"))
+ viewer_meta = {}
+ if local_sinks is not None:
+ was_delivered = getattr(agent, "_interim_text_was_delivered", None)
+ previewed = bool(previewed or (callable(was_delivered) and bool(final_response) and was_delivered(final_response) is True))
+ viewer_meta = {
+ **({"billing_block": result["billing_block"]} if isinstance(result.get("billing_block"), dict) else {}),
+ **({"warning": result["warning"]} if isinstance(result.get("warning"), str) and result["warning"] else {}),
+ }
if not final_response:
final_response = _normalize_empty_agent_response(result, final_response or "", history_len=len(agent_history))
final_response = _sanitize_gateway_final_response(ctx.source.platform, final_response)
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.py
index 33cb3e9a8d5..1a5fcd4e4c5 100644
--- a/gateway/session_ancillary.py
+++ b/gateway/session_ancillary.py
@@ -321,7 +321,9 @@ def _owner_objects(authority, ref, *, include_fallback_evicted=False):
raise RuntimeStoreError('unsupported_projection')
agent = authority.agent(ref)
session_id = physical_target(authority, ref) if include_fallback_evicted else None
- return agent, subagent_records(agent, session_id=session_id, include_fallback_evicted=include_fallback_evicted)
+ route = authority.sessions[ref.session_id].route if include_fallback_evicted else None
+ return agent, subagent_records(
+ agent, session_id=session_id, route=route, include_fallback_evicted=include_fallback_evicted)
def physical_target(authority, ref):
@@ -363,7 +365,7 @@ def control_snapshot(authority, ref):
'updated_at': _snapshot_updated_at(*states)}
-def _has_fallback_evicted_ancestor(agent, target_sid, registry):
+def _has_fallback_evicted_ancestor(agent, target_sid, expected_db, route, registry):
if not target_sid:
return False
current = agent
@@ -372,23 +374,31 @@ def _has_fallback_evicted_ancestor(agent, target_sid, registry):
current = ref() if callable(ref) else None
if current is None:
return False
- if getattr(current, '_evicted_on_fallback', False) is True and getattr(current, 'session_id', None) == target_sid:
- return True
+ marker = getattr(current, '_evicted_on_fallback', False)
+ if not (marker is True or (isinstance(marker, str) and bool(marker))):
+ continue
+ if getattr(current, 'session_id', None) != target_sid:
+ continue
+ if expected_db is not None and getattr(current, '_session_db', None) is not expected_db:
+ continue
+ if route is not None and isinstance(marker, str) and marker != route:
+ continue
+ return True
return False
-def subagent_records(parent, session_id=None, *, include_fallback_evicted=True):
+def subagent_records(parent, session_id=None, *, session_db=None, route=None, include_fallback_evicted=True):
registry = sys.modules.get('tools.delegate_tool_registry')
target_sid = (session_id or getattr(parent, 'session_id', None)) if include_fallback_evicted else None
if registry is None or (parent is None and not target_sid):
return []
+ expected_db = session_db if session_db is not None else getattr(parent, '_session_db', None)
+ effective_route = route if route is not None else getattr(parent, 'gateway_session_key', None)
with registry._active_subagents_lock:
- # Deliberately no unconditional durable-ID fallback: equal IDs cannot transfer a live
- # old parent's transcript or control to a replacement execution object. Only a parent
- # evicted by this session's own fallback keeps its children visible in the read-only roster.
+ # Deliberately no unconditional durable-ID fallback: only a parent evicted by this session's own fallback keeps its children visible in the read-only roster.
return [dict(record) for record in registry._active_subagents.values()
if (parent is not None and registry._is_descendant_of(record.get('agent'), parent))
- or _has_fallback_evicted_ancestor(record.get('agent'), target_sid, registry)]
+ or _has_fallback_evicted_ancestor(record.get('agent'), target_sid, expected_db, effective_route, registry)]
def subagent_tail(records, subagent_id):
diff --git a/tests/gateway/test_local_viewer_events_turn.py b/tests/gateway/test_local_viewer_events_turn.py
index 6b6aabd9ff0..7764b486ead 100644
--- a/tests/gateway/test_local_viewer_events_turn.py
+++ b/tests/gateway/test_local_viewer_events_turn.py
@@ -298,8 +298,7 @@ async def test_service_tier_is_a_session_scoped_fast_override(tmp_path, monkeypa
def test_completion_payload_forwards_billing_failure_and_response_flags():
- """TUI-6: ``message.complete`` carries ``billing``, ``failure_reason``, ``warning``,
- ``response_previewed`` and ``response_transformed`` from the turn result."""
+ """TUI-6: ``message.complete`` carries ``billing``, ``failure_reason``, ``warning``, ``response_previewed`` and ``response_transformed`` from the turn result."""
from gateway.session import SessionSource
from gateway.session_results import execution_result
from gateway.session_settlement_recovery import completion_payload
@@ -342,9 +341,10 @@ def test_completion_payload_forwards_billing_failure_and_response_flags():
def test_progress_publishes_subagent_lifecycle_events_for_local_viewers():
- """TUI-4: ``_ChildProgressRelay`` events reach the viewer stream on ``Platform.LOCAL``
- (including after the spawning turn's generation settles) and never on messaging platforms."""
+ """TUI-4: ``_ChildProgressRelay`` events reach the viewer stream on ``Platform.LOCAL`` (including registered background children after the spawning turn settles, without borrowing a later turn's execution identity) and never on messaging platforms."""
+ from gateway.session_events import SessionEvents
from tools.delegate_tool_progress import _build_child_progress_callback
+ from tools.delegate_tool_registry import _register_subagent, _unregister_subagent
from tui_gateway.contracts.registry import EVENTS
published = []
@@ -385,13 +385,24 @@ def test_progress_publishes_subagent_lifecycle_events_for_local_viewers():
assert published[4][1]['text'] == 'visible chain of thought'
assert published[6][1]['status'] == 'completed' and published[6][1]['summary'] == 'all clear'
- # Background delegation outliving the spawning turn's running claim still publishes to the stream.
- stream_events = []
- live.event_stream = SimpleNamespace(
- publish=lambda sid, payload, *, event_type='message.complete': stream_events.append((sid, event_type, payload)))
+ # Registered background child outliving the spawning turn publishes without borrowing the next turn's execution identity; unregistered stale callbacks are rejected.
+ stream_frames = []
+ live.event_stream = SessionEvents()
+ live.event_stream.execution = {'admission_id': 'turn-b', 'execution_generation': 2}
+ live.event_stream.observers.add(stream_frames.append)
turn._approval_owner[0].executing = {'s': 2}
- relay('subagent.complete', status='completed', summary='late finish')
- assert len(stream_events) == 1 and stream_events[0][1] == 'subagent.complete'
+ stale_relay = _build_child_progress_callback(0, 'stale goal', parent, subagent_id='sa-stale')
+ stale_relay('subagent.complete', status='completed', summary='stale finish')
+ assert stream_frames == []
+ _register_subagent({'subagent_id': 'sa-0-abc12345', 'agent': SimpleNamespace(), 'owner_agent_session_id': 's'})
+ try:
+ relay('subagent.complete', status='completed', summary='late finish')
+ finally:
+ _unregister_subagent('sa-0-abc12345')
+ assert len(stream_frames) == 1
+ params = stream_frames[0]['params']
+ assert params['type'] == 'subagent.complete' and 'admission_id' not in params and 'execution_generation' not in params
+ assert live.event_stream.execution == {'admission_id': 'turn-b', 'execution_generation': 2}
# Messaging routes never publish subagent.* viewer frames.
msg_published = []
@@ -405,9 +416,7 @@ def test_progress_publishes_subagent_lifecycle_events_for_local_viewers():
def test_subagent_roster_retains_running_child_after_fallback_evicts_parent():
- """TUI-4 fallback roster: when ``_run_agent_evict_on_fallback`` evicts the parent after a
- successful provider fallback, ``subagent_records`` keeps the child visible for the read-only
- roster without transferring control/tail ownership to an unrelated replacement object."""
+ """TUI-4 fallback roster: when ``_run_agent_evict_on_fallback`` evicts the parent after a successful provider fallback, ``subagent_records`` keeps the child visible for the owning profile and route without transferring control/tail ownership or leaking across profiles."""
import weakref
from gateway.run_turn import GatewayTurnMixin
from gateway.session_ancillary import subagent_records
@@ -416,22 +425,35 @@ def test_subagent_roster_retains_running_child_after_fallback_evicts_parent():
class Parent:
pass
+ db_a, db_b = object(), object()
original = Parent()
original.session_id = 'same-parent'
- original._session_db = None
+ original._session_db = db_a
+ original.gateway_session_key = 'route'
original.model = 'fallback-model'
original._provider_fallback_active = True
replacement = Parent()
replacement.session_id = original.session_id
- replacement._session_db = None
+ replacement._session_db = db_a
+ replacement.gateway_session_key = 'route'
+
+ foreign_parent = Parent()
+ foreign_parent.session_id = original.session_id
+ foreign_parent._session_db = db_b
+ foreign_parent.gateway_session_key = 'foreign-route'
+ foreign_parent.model = 'fallback-model'
+ foreign_parent._provider_fallback_active = True
unevicted = Parent()
unevicted.session_id = original.session_id
+ unevicted._session_db = db_a
child = SimpleNamespace(_delegate_parent_ref=weakref.ref(original))
+ foreign_child = SimpleNamespace(_delegate_parent_ref=weakref.ref(foreign_parent))
stale_child = SimpleNamespace(_delegate_parent_ref=weakref.ref(unevicted))
_register_subagent({'subagent_id': 'fallback-child', 'agent': child, 'owner_agent_session_id': original.session_id})
+ _register_subagent({'subagent_id': 'foreign-child', 'agent': foreign_child, 'owner_agent_session_id': foreign_parent.session_id})
_register_subagent({'subagent_id': 'stale-child', 'agent': stale_child, 'owner_agent_session_id': unevicted.session_id})
try:
assert [r['subagent_id'] for r in subagent_records(original)] == ['fallback-child']
@@ -440,13 +462,18 @@ def test_subagent_roster_retains_running_child_after_fallback_evicts_parent():
SimpleNamespace(_evict_cached_agent=evicted.append),
SimpleNamespace(session_key='route', agent_holder=[original], result_holder=[{'failed': False}]),
)
- assert evicted == ['route']
- # After a replacement parent is built, and while no resident parent is cached, the fallback
- # child stays in the read-only roster; the un-evicted same-ID object's child never does.
+ GatewayTurnMixin._run_agent_evict_on_fallback(
+ SimpleNamespace(_evict_cached_agent=evicted.append),
+ SimpleNamespace(session_key='foreign-route', agent_holder=[foreign_parent], result_holder=[{'failed': False}]),
+ )
+ assert evicted == ['route', 'foreign-route']
+ # After a replacement parent is built, and while no resident parent is cached, only this profile/route's fallback child stays in the read-only roster.
assert [r['subagent_id'] for r in subagent_records(replacement)] == ['fallback-child']
- assert [r['subagent_id'] for r in subagent_records(None, session_id=original.session_id)] == ['fallback-child']
+ assert [r['subagent_id'] for r in subagent_records(None, session_id=original.session_id, session_db=db_a, route='route')] == ['fallback-child']
+ assert [r['subagent_id'] for r in subagent_records(None, session_id=original.session_id, session_db=db_b, route='foreign-route')] == ['foreign-child']
# Control and tail require exact resident-parent identity.
assert subagent_records(replacement, include_fallback_evicted=False) == []
finally:
_unregister_subagent('fallback-child')
+ _unregister_subagent('foreign-child')
_unregister_subagent('stale-child')
diff --git a/tests/gateway/test_local_viewer_usage.py b/tests/gateway/test_local_viewer_usage.py
index f1d36c63b4a..8a9f1863e18 100644
--- a/tests/gateway/test_local_viewer_usage.py
+++ b/tests/gateway/test_local_viewer_usage.py
@@ -148,9 +148,7 @@ def test_turn_end_publishes_the_agents_banner_info():
@pytest.mark.asyncio
async def test_local_viewer_admission_settles_with_tui_usage_on_message_complete(tmp_path, monkeypatch):
- """End-to-end through ``session_ingress``: ``publish_usage(record=True)`` writes
- ``captured['session_usage']`` during the turn, and the admission packing must carry it
- into ``pending_results`` so ``completion_payload`` attaches ``usage`` to ``message.complete``."""
+ """End-to-end through ``session_ingress``: ``publish_usage(record=True)`` writes ``captured['session_usage']`` during the turn, and the admission packing carries it into ``pending_results`` so ``completion_payload`` attaches ``usage`` to ``message.complete``."""
from gateway.session_controls import AuthorityConnection
from gateway.session_usage import publish_usage
from tests.gateway.test_surface_admission import _authority