Skip to content

The agent that grows with you

feat(gateway): local-viewer turns publish thinking, reaction, reasoning and MoA progress

Tekniuma51e6cf578b5
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index a15c8f76fb4..3b68c5df35d 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4971,7 +4971,7 @@ export interface CanonicalConfigGetResult {
export interface CanonicalConfigSetParams {
profile?: string | null
session_id: string
- key: 'busy' | 'verbose' | 'yolo' | 'model'
+ key: 'busy' | 'verbose' | 'yolo' | 'show_reasoning' | 'model'
value?: unknown
confirm_expensive_model?: boolean | null
}
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 39fb2b21ef7..26f8dca9dfa 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -8403,6 +8403,7 @@
"busy",
"verbose",
"yolo",
+ "show_reasoning",
"model"
],
"title": "Key",
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.py
index cb85645249b..de18b94ccbb 100644
--- a/gateway/local_viewer_events.py
+++ b/gateway/local_viewer_events.py
@@ -15,7 +15,12 @@ from __future__ import annotations
import time
# Attributes ``wire`` may overwrite on the cached agent for one local-viewer turn.
-_TURN_ATTRS = ("tool_gen_callback", "_print_fn")
+_TURN_ATTRS = ("tool_gen_callback", "_print_fn", "thinking_callback", "reaction_callback", "reasoning_callback")
+# MoA facade progress (agent/moa_loop._RELAY_EVENTS) -> the payload tui_gateway/tool_progress emits.
+_MOA_KEYS = {"moa.reference": {"moa_index": "index", "moa_count": "count"},
+ "moa.progress": {"moa_refs_done": "refs_done", "moa_refs_total": "refs_total"},
+ "moa.phase": {"moa_phase": "phase", "moa_refs_done": "refs_done", "moa_refs_total": "refs_total"},
+ "moa.aggregating": {}}
def wire(turn, agent) -> dict:
@@ -27,9 +32,48 @@ def wire(turn, agent) -> dict:
def print_fn(*args, **kwargs):
publish("agent.print", {"text": str(kwargs.get("sep", " ")).join(str(a) for a in args)})
agent._print_fn = print_fn
+ # Kawaii spinner text ("" clears it) and hearts; neither changes what the provider is sent.
+ agent.thinking_callback = lambda text: publish("thinking.delta", {"text": str(text or "")})
+ agent.reaction_callback = lambda kind: publish("reaction", {"kind": str(kind or "")})
+ if show_reasoning(turn):
+ # Only on request: a reasoning sink makes the agent ask the provider for reasoning.
+ agent.reasoning_callback = lambda text: publish("reasoning.delta", {"text": str(text or "")})
return previous
+def show_reasoning(turn) -> bool:
+ """The session's ``show_reasoning`` display flag (``config.set``), off until a viewer sets it."""
+ owner = getattr(turn, "_approval_owner", None)
+ live = owner[0].sessions.get(owner[1]) if owner is not None else None
+ return getattr(live, "show_reasoning", None) is True
+
+
+def publish_progress(turn, event_type, name, preview, kwargs) -> None:
+ """``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."""
+ if event_type != "reasoning.available" and event_type not in _MOA_KEYS:
+ return
+ from gateway.session_cli_turn import classic_cli_turn
+ if not (show_reasoning(turn) or (event_type != "reasoning.available" and classic_cli_turn(turn))):
+ return
+ if event_type == "reasoning.available":
+ payload = {"text": str(preview or "")}
+ elif event_type == "moa.reference":
+ payload = {"label": str(name or ""), "text": str(preview or "")}
+ elif event_type in ("moa.aggregating", "moa.phase"):
+ payload = {"aggregator": str(name or "")} if name or event_type == "moa.aggregating" else {}
+ else:
+ payload = {"label": str(name or "")}
+ payload.update({out: kwargs[key] for key, out in _MOA_KEYS.get(event_type, {}).items()
+ if kwargs.get(key) is not None})
+ if event_type == "moa.progress" and not {"refs_done", "refs_total"} <= set(payload):
+ return
+ if event_type == "moa.phase" and not payload.get("phase"):
+ return
+ turn._publish_execution(event_type, payload)
+
+
def restore(agent, previous: dict | None) -> None:
if not previous:
return
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index 61e817e6ab9..e66a5e17211 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -133,6 +133,9 @@ class GatewayTurnProgressMixin:
if event_type == "subagent.complete":
self._progress_subagent_notice(preview, kwargs)
return
+ if local_viewer_turn(self):
+ from gateway import local_viewer_events
+ local_viewer_events.publish_progress(self, event_type, tool_name, preview, kwargs)
self._progress_live_status(event_type, tool_name, args)
# "log" mode: append tool.started lines to the log queue, silent in chat. Handled before
# the progress_queue guard because log mode runs without a chat progress queue.
diff --git a/gateway/session_busy_controls.py b/gateway/session_busy_controls.py
index 96c239e92a2..13ee02f1443 100644
--- a/gateway/session_busy_controls.py
+++ b/gateway/session_busy_controls.py
@@ -35,6 +35,8 @@ async def busy_config(connection, ref, params, *, write=False):
allowed = {'session_id', 'profile', 'key'} | ({'value'} if write else set())
if params.get('key') == 'verbose' and not set(params) - allowed and ref.session_id:
return verbose_config(connection, ref, params, write)
+ if params.get('key') == 'show_reasoning' and not set(params) - allowed and ref.session_id:
+ return show_reasoning_config(connection, ref, params, write)
if params.get('key') == 'yolo' and not set(params) - allowed and ref.session_id:
return await yolo_config(connection, ref, params, write)
if (set(params) - allowed or not ref.session_id or params.get('key') != 'busy'
@@ -76,6 +78,22 @@ def verbose_config(connection, ref, params, write):
return {'key': 'verbose', 'value': current, 'scope': 'session'}
+def show_reasoning_config(connection, ref, params, write):
+ """Session-scoped reasoning display (the classic CLI's ``/reasoning show|hide`` and verbose
+ reasoning): whether a local-viewer turn of this session streams ``reasoning.delta``. Off until
+ set, because a reasoning sink changes what the provider is asked for. Never a settings write."""
+ value = params.get('value')
+ word = str(value).strip().lower()
+ if write and word not in _YOLO_WORDS:
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control' if write else 'session:read')
+ live = connection.authority.sessions[ref.session_id]
+ if write:
+ live.show_reasoning = _YOLO_WORDS[word]
+ return {'key': 'show_reasoning', 'value': '1' if getattr(live, 'show_reasoning', None) is True else '0',
+ 'scope': 'session'}
+
+
_YOLO_WORDS = {'1': True, 'on': True, 'true': True, '0': False, 'off': False, 'false': False}
diff --git a/gateway/session_config.py b/gateway/session_config.py
index 9abb57e621b..f16985a225f 100644
--- a/gateway/session_config.py
+++ b/gateway/session_config.py
@@ -53,7 +53,7 @@ async def config_get(connection, ref, params):
key = params.get('key')
if not isinstance(key, str):
raise RuntimeStoreError('invalid_params')
- if key in ('busy', 'verbose', 'yolo'):
+ if key in ('busy', 'verbose', 'yolo', 'show_reasoning'):
from gateway.session_busy_controls import busy_config
return await busy_config(connection, ref, params)
policy = _authorize(connection, ref, params)
diff --git a/tests/gateway/test_local_viewer_events_turn.py b/tests/gateway/test_local_viewer_events_turn.py
index fe7b76c3bec..9e443204084 100644
--- a/tests/gateway/test_local_viewer_events_turn.py
+++ b/tests/gateway/test_local_viewer_events_turn.py
@@ -24,7 +24,8 @@ def _turn(platform, published, *, live=None):
interim_assistant_messages_enabled=False, user_config={},
resolve_display_setting=lambda *a: None, _run_still_current=lambda: True,
_voice_ack_guild=[None], _native_slack_task_cards=False, progress_mode='all',
- session_id='s', progress_queue=None,
+ session_id='s', progress_queue=None, _live_status_adapter=None, _live_status_mode='off',
+ log_queue=None,
)
turn._runner = SimpleNamespace(config=None, _delivery_adapter_for=lambda source: None)
live = live or SimpleNamespace(tool_progress_mode=None)
@@ -102,3 +103,84 @@ def test_wire_contract_accepts_the_boundary_frame():
EVENTS['tool.generating'].payload.model_validate({'name': 'terminal'})
EVENTS['agent.print'].payload.model_validate({'text': 'line'})
EVENTS['tool.complete'].payload.model_validate({'tool_id': 'c', 'name': 'n', 'duration_s': 0.1})
+
+
+def test_thinking_and_reaction_publish_and_reasoning_waits_for_the_session_flag():
+ from gateway import local_viewer_events
+ published = []
+ live = SimpleNamespace(tool_progress_mode=None)
+ turn = _turn(Platform.LOCAL, published, live=live)
+ agent = SimpleNamespace(tool_gen_callback=None, _print_fn=None, thinking_callback=None,
+ reaction_callback=None, reasoning_callback=None)
+ previous = local_viewer_events.wire(turn, agent)
+ agent.thinking_callback('(◕‿◕) pondering...')
+ agent.thinking_callback('')
+ agent.reaction_callback('vibe')
+ # No sink unless the viewer asked: a reasoning callback changes the provider request.
+ assert agent.reasoning_callback is None
+ local_viewer_events.restore(agent, previous)
+ assert (agent.thinking_callback, agent.reaction_callback) == (None, None)
+ live.show_reasoning = True
+ local_viewer_events.wire(turn, agent)
+ agent.reasoning_callback('step 1')
+ assert published == [('thinking.delta', {'text': '(◕‿◕) pondering...'}), ('thinking.delta', {'text': ''}),
+ ('reaction', {'kind': 'vibe'}), ('reasoning.delta', {'text': 'step 1'})]
+
+
[email protected]('classic', [True, False])
+def test_progress_projects_reasoning_available_and_moa(monkeypatch, classic):
+ from gateway import session_cli_turn
+ monkeypatch.setattr(session_cli_turn, 'classic_cli_turn', lambda turn: classic)
+ published = []
+ live = SimpleNamespace(tool_progress_mode=None)
+ turn = _turn(Platform.LOCAL, published, live=live)
+ turn.progress_callback('reasoning.available', '_thinking', 'because', None)
+ turn.progress_callback('moa.reference', 'gpt-x', 'ref answer', None, moa_index=1, moa_count=2)
+ turn.progress_callback('moa.progress', 'gpt-x', None, None, moa_refs_done=1, moa_refs_total=2)
+ turn.progress_callback('moa.phase', 'agg', None, None, moa_phase='aggregator', moa_refs_done=2, moa_refs_total=2)
+ turn.progress_callback('moa.aggregating', 'agg', None, None, moa_ref_count=2)
+ moa = [('moa.reference', {'label': 'gpt-x', 'text': 'ref answer', 'index': 1, 'count': 2}),
+ ('moa.progress', {'label': 'gpt-x', 'refs_done': 1, 'refs_total': 2}),
+ ('moa.phase', {'aggregator': 'agg', 'phase': 'aggregator', 'refs_done': 2, 'refs_total': 2}),
+ ('moa.aggregating', {'aggregator': 'agg'})]
+ # main's CLI renders MoA references whatever its reasoning display; reasoning.available only when shown.
+ assert published == (moa if classic else [])
+ published.clear()
+ live.show_reasoning = True
+ turn.progress_callback('reasoning.available', '_thinking', 'because', None)
+ assert published == [('reasoning.available', {'text': 'because'})]
+ from tui_gateway.contracts.registry import EVENTS
+ for kind, payload in moa:
+ EVENTS[kind].payload.model_validate(payload)
+
+
+def test_messaging_progress_never_publishes_reasoning():
+ published = []
+ turn = _turn(Platform.TELEGRAM, published, live=SimpleNamespace(tool_progress_mode=None, show_reasoning=True))
+ turn.progress_callback('reasoning.available', '_thinking', 'because', None)
+ turn.progress_callback('moa.aggregating', 'agg', None, None)
+ assert published == []
+
+
+async def test_show_reasoning_is_a_session_scoped_config_key(tmp_path, monkeypatch):
+ from gateway.session_controls import AuthorityConnection
+ from tests.gateway.test_surface_admission import _authority
+
+ async def answer(event):
+ return 'ok'
+ authority = await _authority(tmp_path, monkeypatch, answer)
+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
+ try:
+ await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})
+ get = {'id': 2, 'method': 'config.get', 'params': {'session_id': 's', 'key': 'show_reasoning'}}
+ assert (await connection.dispatch(get))['result']['value'] == '0'
+ set_on = await connection.dispatch({'id': 3, 'method': 'config.set', 'params': {
+ 'session_id': 's', 'key': 'show_reasoning', 'value': 'on'}})
+ assert set_on['result'] == {'key': 'show_reasoning', 'value': '1', 'scope': 'session'}, set_on
+ assert authority.sessions['s'].show_reasoning is True
+ bad = await connection.dispatch({'id': 4, 'method': 'config.set', 'params': {
+ 'session_id': 's', 'key': 'show_reasoning', 'value': 'loud'}})
+ assert bad['error']['message'] == 'invalid_params', bad
+ finally:
+ await connection.close()
diff --git a/tui_gateway/contracts/canonical_projections.py b/tui_gateway/contracts/canonical_projections.py
index 9fae63374d5..aff897b0ee7 100644
--- a/tui_gateway/contracts/canonical_projections.py
+++ b/tui_gateway/contracts/canonical_projections.py
@@ -20,7 +20,7 @@ class CanonicalConfigSetParams(CanonicalSessionParams):
"""``model`` is recognised only to be refused with ``use_session_mutation_model``: a model pick is
the revision-fenced ``session.mutate`` operation, never a config write."""
- key: Literal['busy', 'verbose', 'yolo', 'model']
+ key: Literal['busy', 'verbose', 'yolo', 'show_reasoning', 'model']
value: JsonValue = None
confirm_expensive_model: bool | None = None