Skip to content

The agent that grows with you

fix(gateway): HUD and live-voice submits are admitted and noted to the model

teknium164596711da28
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 44633c74626..cf715bb9756 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -234,7 +234,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
self._merge_turn_request_overrides(agent, turn_route)
# Must-deliver notes for THIS turn ride the current user message (api_content sidecar), never
# the system prompt. Assigned unconditionally so a reused agent never replays a stale note.
- agent._gateway_turn_context_notes = "\n\n".join(runner._consume_pending_turn_sidecar_notes(ctx.session_key))
+ from gateway.session_surface import surface_turn_note
+ agent._gateway_turn_context_notes = "\n\n".join(
+ note for note in (*runner._consume_pending_turn_sidecar_notes(ctx.session_key), surface_turn_note(agent)) if note)
agent.background_review_callback, bg_release = self._make_bg_review_callbacks()
# Register the release hook on the adapter so base.py's finally block fires it after the
# main response is delivered.
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 92f270e5297..126b4e3851c 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -230,13 +230,15 @@ class SessionAuthority:
async def submit(self, actor: Principal, request: Submission):
self.authorize(actor, request.ref, 'session:submit')
self._require_admission_open()
- if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {'text', 'attachments', 'finite'}
+ if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {
+ 'text', 'attachments', 'finite', 'surface', 'voice_context', 'interrupted'}
or not isinstance(request.payload['text'], str)):
raise RuntimeStoreError('invalid_params')
from gateway.session_ingress_media import admit_attachments
from gateway.session_finite import admit_finite
+ from gateway.session_surface import admit_surface
finite = admit_finite(request.payload)
- payload = {'text': request.payload['text'], **finite,
+ payload = {'text': request.payload['text'], **finite, **admit_surface(request.payload),
**admit_attachments(request.payload.get('attachments'))}
from gateway.config import Platform
source = self.sessions[request.ref.session_id].source
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 3be89c2eea6..085c43b51dd 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -267,14 +267,16 @@ class AuthorityConnection:
async def submit(self, ref, params):
if ref.session_id not in self.subscriptions:
raise RuntimeStoreError('permission_denied')
- forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued', 'attachments', 'finite'}
+ forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued', 'attachments', 'finite',
+ 'surface', 'voice_context', 'interrupted'}
if forbidden:
raise RuntimeStoreError('invalid_params')
request_id = params.get('submission_id') or params.get('input_id')
if not isinstance(request_id, str) or not request_id:
raise RuntimeStoreError('invalid_params')
from gateway.session_finite import admit_finite
- payload = {'text': params.get('text'), **admit_finite(params)}
+ from gateway.session_surface import submit_surface_fields
+ payload = {'text': params.get('text'), **admit_finite(params), **submit_surface_fields(params)}
if 'attachments' in params:
payload['attachments'] = params['attachments']
receipt = await self.authority.submit(self.actor, Submission(request_id, ref, payload, 'queue'))
diff --git a/gateway/session_finite.py b/gateway/session_finite.py
index 44c8a7af2d7..4ae16340bef 100644
--- a/gateway/session_finite.py
+++ b/gateway/session_finite.py
@@ -32,5 +32,7 @@ def admit_finite(params):
async def execute_finite_admission(authority, ref, row):
from gateway.session_ingress import execute_admission
- with finite_turn_scope(row['payload'].get('finite', False)):
+ from gateway.session_surface import surface_turn_scope
+ with finite_turn_scope(row['payload'].get('finite', False)), \
+ surface_turn_scope(row['payload'].get('surface_v1')):
return await execute_admission(authority, ref, row)
diff --git a/gateway/session_operator.py b/gateway/session_operator.py
index 8a494a9f78f..da5c43d43a1 100644
--- a/gateway/session_operator.py
+++ b/gateway/session_operator.py
@@ -10,7 +10,7 @@ from hermes_state_runtime import RuntimeStoreError
def check_local_input(authority, ref, row):
payload = row['payload']
- allowed = {'text', 'attachments_v1', 'finite'}
+ allowed = {'text', 'attachments_v1', 'finite', 'surface_v1'}
if 'local_operator_v1' in payload:
allowed.add('local_operator_v1')
if payload['local_operator_v1'] != {
diff --git a/gateway/session_surface.py b/gateway/session_surface.py
new file mode 100644
index 00000000000..373cfcf2bbf
--- /dev/null
+++ b/gateway/session_surface.py
@@ -0,0 +1,85 @@
+"""Per-turn client surface (floating HUD, live voice) carried through canonical admission.
+
+A surface is a fact about ONE turn, never about the session: the same session alternates
+between the app window, the HUD and a spoken delegation. It is committed with the admission
+row and reaches the model as a note on the user message (api_content sidecar), so the
+persisted user row stays the words the user typed and the frozen system prefix is untouched.
+"""
+from contextlib import contextmanager
+from contextvars import ContextVar
+
+from hermes_state_runtime import RuntimeStoreError
+
+SURFACES = frozenset({'hud', 'voice-live'})
+_VOICE_CONTEXT_LIMIT = 6000
+_SUBMIT_FIELDS = ('surface', 'voice_context', 'interrupted')
+_surface_turn = ContextVar('surface_turn', default=None)
+
+
+def submit_surface_fields(params):
+ """The raw per-turn surface fields of a ``prompt.submit`` request, forwarded to admission."""
+ return {key: params[key] for key in _SUBMIT_FIELDS if key in params}
+
+
+def admit_surface(params):
+ """Wire ``surface`` / ``voice_context`` / ``interrupted`` -> committed ``surface_v1`` (``{}`` when absent)."""
+ surface, context, interrupted = (params.get(key) for key in _SUBMIT_FIELDS)
+ if surface is not None and surface not in SURFACES:
+ raise RuntimeStoreError('invalid_params')
+ # The spoken transcript only makes sense for a live-voice delegation; anywhere else it is
+ # a client smuggling model input past the persisted row.
+ if context is not None and (surface != 'voice-live' or not isinstance(context, str)):
+ raise RuntimeStoreError('invalid_params')
+ if interrupted is not None and type(interrupted) is not bool:
+ raise RuntimeStoreError('invalid_params')
+ committed = {}
+ if surface:
+ committed['surface'] = surface
+ if context:
+ committed['voice_context'] = context[:_VOICE_CONTEXT_LIMIT]
+ if interrupted:
+ committed['interrupted'] = True
+ return {'surface_v1': committed} if committed else {}
+
+
+def _hud_note(committed, valid_tool_names):
+ from agent.prompt_builder import hud_surface_note
+ return hud_surface_note(valid_tool_names)
+
+
+def _voice_live_note(committed, valid_tool_names):
+ from tools.voice_live import voice_live_turn_note
+ return voice_live_turn_note(committed.get('voice_context') or '')
+
+
+_SURFACE_NOTES = {'hud': _hud_note, 'voice-live': _voice_live_note}
+
+
+def surface_note(committed, valid_tool_names=None):
+ """The model-bound note for a committed surface (``""`` for the plain app window): barge-in
+ first, then the HUD read-the-window-below prior or the spoken-delegation contract."""
+ notes = []
+ if committed.get('interrupted'):
+ from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE
+ notes.append(SPEECH_INTERRUPTED_NOTE)
+ render = _SURFACE_NOTES.get(committed.get('surface'))
+ if render is not None:
+ notes.append(render(committed, valid_tool_names))
+ return '\n\n'.join(note for note in notes if note)
+
+
+@contextmanager
+def surface_turn_scope(committed):
+ token = _surface_turn.set(committed)
+ try:
+ yield
+ finally:
+ _surface_turn.reset(token)
+
+
+def surface_turn_note(agent):
+ """The executing admission's surface note, gated on the tools this agent actually has."""
+ committed = _surface_turn.get()
+ if not committed:
+ return ''
+ return surface_note(committed, getattr(agent, 'valid_tool_names', None))
diff --git a/tests/gateway/test_surface_admission.py b/tests/gateway/test_surface_admission.py
new file mode 100644
index 00000000000..ab8c98aacba
--- /dev/null
+++ b/tests/gateway/test_surface_admission.py
@@ -0,0 +1,148 @@
+"""HUD / live-voice submit fields survive canonical admission and reach the model as a per-turn note."""
+import asyncio
+from contextlib import closing
+from http.server import ThreadingHTTPServer
+import json
+from pathlib import Path
+import sqlite3
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+
+
+async def _authority(tmp_path, monkeypatch, answer):
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionSource, SessionStore
+ from gateway.session_authority import LiveSession, initialize_session_authority
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False,
+ _handle_message=answer, _adapter_for_source=lambda source: None)
+ authority = await initialize_session_authority(runner, profile_id='p', instance_id='owner')
+ store._db.create_session('s', source='telegram')
+ authority.sessions['s'] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id='c'), 's')
+ return authority
+
+
+async def test_surface_fields_are_admitted_and_scoped_to_their_own_turn(tmp_path, monkeypatch):
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_surface import surface_turn_note
+ from hermes_state_runtime import list_session_admissions
+ from tools.voice_live import VOICE_LIVE_TURN_NOTE
+
+ seen = []
+ async def answer(event):
+ # The note is rendered against the executing agent's tools; a live-voice turn needs none.
+ seen.append((event.text, surface_turn_note(SimpleNamespace(valid_tool_names=set()))))
+ 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'}})
+ reply = await connection.dispatch({'id': 2, 'method': 'prompt.submit', 'params': {
+ 'session_id': 's', 'submission_id': 'spoken', 'text': "what's the weather",
+ 'surface': 'voice-live', 'voice_context': "Voice assistant: Hi\nUser: what's the weather"}})
+ assert reply['result']['status'] == 'queued', reply
+ await authority.sessions['s'].task
+ plain = await connection.dispatch({'id': 3, 'method': 'prompt.submit', 'params': {
+ 'session_id': 's', 'submission_id': 'typed', 'text': 'and tomorrow?'}})
+ assert plain['result']['status'] == 'queued', plain
+ await authority.sessions['s'].task
+ rejected = await connection.dispatch({'id': 4, 'method': 'prompt.submit', 'params': {
+ 'session_id': 's', 'submission_id': 'smuggled', 'text': 'x', 'voice_context': 'User: smuggled'}})
+ assert rejected['error']['message'] == 'invalid_params', rejected
+ finally:
+ await connection.close()
+
+ rows = {row['request_id']: row for row in list_session_admissions(authority.db, session_id='s', pending_only=False)}
+ assert rows['spoken']['payload']['surface_v1'] == {
+ 'surface': 'voice-live', 'voice_context': "Voice assistant: Hi\nUser: what's the weather"}
+ assert 'surface_v1' not in rows['typed']['payload'] and 'smuggled' not in rows
+ (spoken_text, spoken_note), (typed_text, typed_note) = seen
+ assert spoken_text == "what's the weather", 'the persisted user row stays the words the user said'
+ assert spoken_note.startswith(VOICE_LIVE_TURN_NOTE) and "User: what's the weather" in spoken_note
+ assert (typed_text, typed_note) == ('and tomorrow?', '')
+
+
+def _admissions(home):
+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:
+ return dict(db.execute('SELECT request_id, status FROM session_admissions'))
+
+
+def _wait_for(predicate):
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ if predicate():
+ return
+ time.sleep(.05)
+ pytest.fail('Timed out waiting for the admitted turn')
+
+
+def test_real_daemon_accepts_hud_and_voice_live_submits_and_notes_the_model(tmp_path, monkeypatch):
+ from tools.voice_live import VOICE_LIVE_TURN_NOTE
+
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ monkeypatch.setenv('HOME', str(user))
+ monkeypatch.setenv('USERPROFILE', str(user))
+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ model.requests = []
+ model.blocked, model.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=model.serve_forever, daemon=True)
+ thread.start()
+ base = f'http://127.0.0.1:{model.server_port}/v1'
+ (home / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ 'platform_toolsets': {'gui': []}, 'terminal': {'cwd': str(home)},
+ }))
+ env = child_env() | dict(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),
+ PYTHONPATH=str(root), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1')
+
+ async def drive(desc):
+ async with websocket(home, desc) as ws:
+ created = await rpc(ws, 'session.create', request_id='surface-target', source='gui', cwd=str(home), toolsets=[])
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ replies = {}
+ for name, extra in (('window', {}), ('hud', {'surface': 'hud'}),
+ ('voice', {'surface': 'voice-live', 'voice_context': 'User: earlier words'})):
+ replies[name] = await rpc(ws, 'prompt.submit', session_id=sid, submission_id=name, text=name.upper() + '_TURN', **extra)
+ await asyncio.to_thread(_wait_for, lambda: _admissions(home).get(name) == 'terminal')
+ return replies
+
+ try:
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ replies = asyncio.run(drive(desc))
+ finally:
+ model.release.set()
+ model.shutdown()
+ model.server_close()
+ thread.join(timeout=5)
+
+ assert all(reply.get('result', {}).get('status') == 'queued' for reply in replies.values()), replies
+ users = {}
+ for request in model.requests:
+ content = next(m['content'] for m in reversed(request['messages']) if m['role'] == 'user')
+ text = content if isinstance(content, str) else ''.join(p.get('text', '') for p in content)
+ for name in ('window', 'hud', 'voice'):
+ if name.upper() + '_TURN' in text:
+ users[name] = text
+ assert set(users) == {'window', 'hud', 'voice'}, users
+ # Live voice: the delegation contract + the spoken context ride the model input, never the row.
+ assert VOICE_LIVE_TURN_NOTE in users['voice'] and 'User: earlier words' in users['voice']
+ assert VOICE_LIVE_TURN_NOTE not in users['window'] and VOICE_LIVE_TURN_NOTE not in users['hud']
+ # HUD without read_window_below (toolsets=[]) is accepted and withholds the tool-gated note.
+ assert 'HUD mode' not in users['hud'] and 'HUD mode' not in users['window']
+ assert all(request['messages'][0]['role'] == 'system' for request in model.requests)
+ assert len({request['messages'][0]['content'] for request in model.requests}) == 1, 'frozen system prefix must not vary per surface'
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index bdb0a40b929..294bdfbdcb2 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -537,8 +537,9 @@ def _lock_in_submit_turn(
return None, fields
-# Per-turn client surfaces that carry a model-bound note (session_notifications._surface_note).
-_CLIENT_SURFACES = frozenset({"hud", "voice-live"})
+# Per-turn client surfaces that carry a model-bound note (session_notifications._hud_surface_note);
+# the canonical admission path shares the same set (gateway.session_surface).
+from gateway.session_surface import SURFACES as _CLIENT_SURFACES
@method("prompt.submit")
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index d69c8c19909..e81f054970f 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -630,11 +630,11 @@ def _start_notification_poller(sid: str, session: dict) -> threading.Event:
def _hud_surface_note(session: dict) -> str:
- """The HUD-mode note for this turn, or "" when it was not typed there."""
- if session.get("client_surface") != "hud":
- return ""
- from agent.prompt_builder import hud_surface_note
- return hud_surface_note(getattr(session.get("agent"), "valid_tool_names", None))
+ """The per-surface note for this turn ("" for the plain app window): HUD -> the read-the-window-below
+ prior; voice-live -> the spoken-delegation contract with the recent transcript."""
+ from gateway.session_surface import surface_note
+ committed = {"surface": session.get("client_surface"), "voice_context": session.get("voice_live_context")}
+ return surface_note(committed, getattr(session.get("agent"), "valid_tool_names", None))
def _prepend_note(run_message: Any, note: str) -> Any: