Skip to content

The agent that grows with you

fix(gateway): gate completion_payload viewer fields on local_viewer and close subagent lock race

yoniebans7fc91194a526
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.py
index fca02f53d14..6765d4ef3c4 100644
--- a/gateway/local_viewer_events.py
+++ b/gateway/local_viewer_events.py
@@ -82,25 +82,27 @@ def _publish_subagent(turn, event_type, payload) -> 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:
- if not _is_active_session_subagent(turn, payload):
+ if not (isinstance(executing, dict) and executing.get(session_id) != generation):
+ if turn._publish_execution(event_type, payload) is not False:
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
+ if not _is_active_session_subagent(turn, 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)
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 3516a95ee43..6dec437d811 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -1121,7 +1121,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
cli_fields = self.__dict__.pop("_cli_result_fields", None)
# A classic CLI viewer reads the run_conversation-shaped dict from the receipt; the
# delivered reply (message.complete text) keeps the gateway's own copy.
- captured['result'] = {**result, **cli_fields} if cli_fields else result
+ captured['result'] = (
+ {**result, **cli_fields, **({'response_previewed': True} if result.get('response_previewed') else {})}
+ if cli_fields else result
+ )
return result
def _run_sync_scoped(self):
@@ -1321,6 +1324,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
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 = {
+ "local_viewer": True,
**({"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 {}),
}
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.py
index 0f8f99ec698..51af5bc8691 100644
--- a/gateway/session_ancillary.py
+++ b/gateway/session_ancillary.py
@@ -371,7 +371,7 @@ def _has_fallback_evicted_ancestor(agent, target_sid, expected_db, route, regist
if not target_sid:
return False
current = agent
- for _ in range(getattr(registry, '_MAX_ANCESTOR_HOPS', 16)):
+ for _ in range(getattr(registry, '_MAX_ANCESTOR_HOPS', 8)):
ref = getattr(current, '_delegate_parent_ref', None) if current is not None else None
current = ref() if callable(ref) else None
if current is None:
diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.py
index f61a0c89e1f..37292c1788c 100644
--- a/gateway/session_settlement_recovery.py
+++ b/gateway/session_settlement_recovery.py
@@ -49,16 +49,17 @@ def completion_payload(row, settled, response, captured):
captured_result = (captured or {}).get('result') or {}
if response and captured_result.get('response_reused'):
complete['response_reused'] = True
- if captured_result.get('response_previewed'):
- complete['response_previewed'] = True
- if captured_result.get('response_transformed'):
- complete['response_transformed'] = True
- if isinstance(captured_result.get('warning'), str) and captured_result['warning']:
- complete['warning'] = captured_result['warning']
- if isinstance(captured_result.get('billing_block'), dict):
- complete['billing'] = captured_result['billing_block']
- if isinstance(captured_result.get('failure_reason'), str) and captured_result['failure_reason']:
- complete['failure_reason'] = captured_result['failure_reason']
+ if captured_result.get('local_viewer'):
+ if captured_result.get('response_previewed'):
+ complete['response_previewed'] = True
+ if captured_result.get('response_transformed'):
+ complete['response_transformed'] = True
+ if isinstance(captured_result.get('warning'), str) and captured_result['warning']:
+ complete['warning'] = captured_result['warning']
+ if isinstance(captured_result.get('billing_block'), dict):
+ complete['billing'] = captured_result['billing_block']
+ if isinstance(captured_result.get('failure_reason'), str) and captured_result['failure_reason']:
+ complete['failure_reason'] = captured_result['failure_reason']
# The committed row addresses of the turn: a viewer binds the streamed reply to
# its stored row, so a transcript read racing this frame never paints it twice.
# ``submission_id`` names whose turn it is: the sending viewer binds its optimistic
diff --git a/tests/gateway/test_local_viewer_events_turn.py b/tests/gateway/test_local_viewer_events_turn.py
index bb66227416e..b8d15a8a92d 100644
--- a/tests/gateway/test_local_viewer_events_turn.py
+++ b/tests/gateway/test_local_viewer_events_turn.py
@@ -353,7 +353,7 @@ def test_completion_payload_forwards_billing_failure_and_response_flags():
EVENTS['message.complete'].payload.model_validate(
{k: v for k, v in complete.items() if k not in ('content', 'admission_id', 'outcome')})
- # Non-viewer (messaging) turns do not probe _interim_text_was_delivered or attach viewer_meta.
+ # Non-viewer (messaging) turns do not probe _interim_text_was_delivered, attach viewer_meta, or emit TUI-6 completion fields.
interim_probes.clear()
msg_ctx = TurnContext(
source=SessionSource(platform=Platform.TELEGRAM, chat_id='sid', user_id='u'),
@@ -363,12 +363,16 @@ def test_completion_payload_forwards_billing_failure_and_response_flags():
msg_captured = {}
token = execution_result.set(msg_captured)
try:
- TurnRunner(_gateway_runner(), msg_ctx).run_sync()
+ msg_delivered = TurnRunner(_gateway_runner(), msg_ctx).run_sync()
finally:
execution_result.reset(token)
assert interim_probes == []
assert 'billing_block' not in msg_captured['result'] and 'warning' not in msg_captured['result']
assert msg_captured['result']['response_previewed'] is False
+ msg_complete = completion_payload(
+ {'admission_id': 'a2', 'request_id': 'r2'}, {'outcome': 'failed'}, msg_delivered['final_response'], msg_captured)
+ for viewer_key in ('billing', 'failure_reason', 'warning', 'response_previewed', 'response_transformed'):
+ assert viewer_key not in msg_complete
def test_progress_publishes_subagent_lifecycle_events_for_local_viewers():