The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(voice): a typed stop phrase ends the voice chat on the shared gateway
Teknium24b0b4d9a1e7
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex d4f135967a7..b24689ad870 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -5139,6 +5139,12 @@ export interface CanonicalModelOverride {provider?: string | nullreasoning?: string | null}+/** ``prompt.submit``: the admission receipt, or ``{voice_stopped: true}``. */+export type CanonicalSubmitResult = AdmissionStatus | CanonicalVoiceStopped+/** A bare stop phrase typed while the session's voice chat is on: the chat ended, nothing was admitted (TUI-26). */+export interface CanonicalVoiceStopped {+ voice_stopped: true+}export interface CanonicalApprovalParams {profile?: string | nullsession_id: string@@ -6767,7 +6773,7 @@ export interface CanonicalRpcMethods {'prompt.resolve_unknown': { params: PromptResolveUnknownParams; result: AdmissionStatus }/** Hand a still-queued admission's text to the running turn's agent as a steer. The admission reads 'started' with that turn (pending snapshots mark it 'steering') and never runs on its own; it settles terminal 'steered' when the turn completes with its text, else 'interrupted' (its completion frame says 'cancelled', as an interrupted turn's does); a text the turn never consumed goes back to its queue place. Refusals: admission_started, session_idle, steer_unavailable (no agent to take it: the admission stays queued), unsupported_control, not_found. */'prompt.steer_queued': { params: CanonicalSteerQueuedParams; result: AdmissionStatus }- 'prompt.submit': { params: CanonicalSubmitParams; result: AdmissionStatus }+ 'prompt.submit': { params: CanonicalSubmitParams; result: CanonicalSubmitResult }/** The classic CLI's /diff session: everything changed since the session's earliest retained checkpoint, as data for its terminal renderer. */'rollback.session_diff': { params: RollbackSessionDiffParams; result: RollbackSessionDiffResult }/** Owner identity and the canonical capabilities a client may rely on. */diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 35bdca5173d..5c3db010103 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -11357,6 +11357,18 @@"title": "CanonicalSubmitParams","type": "object"},+ "CanonicalSubmitResult": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/AdmissionStatus"+ },+ {+ "$ref": "#/components/schemas/CanonicalVoiceStopped"+ }+ ],+ "description": "``prompt.submit``: the admission receipt, or ``{voice_stopped: true}``.",+ "title": "CanonicalSubmitResult"+ },"CanonicalTurnAuthor": {"additionalProperties": false,"properties": {@@ -11405,6 +11417,22 @@"title": "CanonicalTurnAuthor","type": "object"},+ "CanonicalVoiceStopped": {+ "additionalProperties": false,+ "description": "A bare stop phrase typed while the session's voice chat is on: the chat ended, nothing was\nadmitted (TUI-26).",+ "properties": {+ "voice_stopped": {+ "const": true,+ "title": "Voice Stopped",+ "type": "boolean"+ }+ },+ "required": [+ "voice_stopped"+ ],+ "title": "CanonicalVoiceStopped",+ "type": "object"+ },"CapabilityEntry": {"additionalProperties": false,"properties": {@@ -47478,7 +47506,7 @@"result": {"name": "result","schema": {- "$ref": "#/components/schemas/AdmissionStatus"+ "$ref": "#/components/schemas/CanonicalSubmitResult"}}},diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex f7aad5bcfcb..daae1a48cf4 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -690,11 +690,29 @@ class AuthorityConnection:return self.authority.sessions[ref.session_id].event_stream.since(epoch, sequence)async def submit(self, ref, params):+ if await self._typed_voice_stop(ref, params):+ return {'voice_stopped': True}# The interactive WS is the one surface a restart's after-turn wait admits (#139041).receipt = await self.authority.submit(self.actor, self.submission(ref, params),queue_while_restarting=self._operator is True)return asdict(receipt)+ async def _typed_voice_stop(self, ref, params):+ """TUI-26: a bare stop phrase typed while the session's voice chat is on ends the chat+ (the sidecar's ``methods_prompt._consume_typed_stop_phrase``, its typed twin of the spoken+ stop) and is never admitted. Only a submitter attached to the session may end it."""+ text = params.get('text')+ if not isinstance(text, str):+ return False+ if ref.session_id not in self.subscriptions:+ return False # submission() refuses it as permission_denied+ self.authority.authorize(self.actor, ref, 'session:submit')+ from gateway.session_config import local_voice_enabled+ if not local_voice_enabled(ref.session_id):+ return False+ from tui_gateway import server+ return await asyncio.to_thread(server._consume_typed_stop_phrase, text, ref.session_id, emit=False)+def submission(self, ref, params):"""The admission a ``prompt.submit``-shaped request asks for (``prompt.replace_queued`` too)."""if ref.session_id not in self.subscriptions:diff --git a/tests/gateway/test_canonical_typed_voice_stop.py b/tests/gateway/test_canonical_typed_voice_stop.pynew file mode 100644index 00000000000..90e488780e0--- /dev/null+++ b/tests/gateway/test_canonical_typed_voice_stop.py@@ -0,0 +1,75 @@+"""TUI-26: a bare stop phrase TYPED into a voice chat on the shared gateway ends the voice chat+instead of reaching the agent. Ink sends prompts to the canonical ``prompt.submit``; the request+goes through the real ``AuthorityConnection.dispatch`` (contract parse, handler, result check)."""+import pytest++from gateway import run_api+from hermes_state_runtime import list_session_admissions+from tests.gateway.test_prompt_queued_controls import _call, _connection+from tests.gateway.test_session_authority_cancel_settlement import _authority+++def voice_owner(tmp_path, monkeypatch):+ from types import SimpleNamespace++ from tui_gateway import server+ db, authority = _authority(tmp_path, monkeypatch)+ # The owner's voice mode is keyed by the session's source (``_voice_key_for_source``). Ending the+ # LOCAL push-to-talk capture is ``set_local_voice_mode``'s job, pinned in+ # tests/tui_gateway/test_canonical_voice_mode_writers.py.+ authority.sessions['s'].source.chat_id = 's'+ monkeypatch.setattr(authority, '_schedule', lambda ref: None) # admit only; never run a turn+ runner = authority.runner+ runner._voice_mode = {}+ runner._voice_key_for_source = lambda src: src.chat_id+ runner._save_voice_modes = lambda: None+ runner.session_authority = authority+ monkeypatch.setattr(run_api, '_ACTIVE_RUNNER', runner)+ monkeypatch.setattr(server, '_tts_stream_stop', lambda user_barge=False: None)+ return SimpleNamespace(db=db, authority=authority, runner=runner)+++def _ledger(db):+ return [row['request_id'] for row in list_session_admissions(db, session_id='s', pending_only=False)]++[email protected]('typed', ['stop', ' Stop! '])+async def test_typed_stop_phrase_ends_the_voice_chat_and_admits_nothing(voice_owner, typed):+ voice_owner.runner._voice_mode['s'] = 'voice_only'+ with voice_owner.db:+ reply = await _call(_connection(voice_owner.authority), 'prompt.submit', text=typed, submission_id='r1')+ assert reply.get('result') == {'voice_stopped': True}, reply+ assert voice_owner.runner._voice_mode['s'] == 'off'+ assert _ledger(voice_owner.db) == [], 'the stop phrase must never reach the agent'++[email protected]('mode, text', [('off', 'stop'), ('voice_only', 'stop doing that')])+async def test_other_text_or_voice_off_is_admitted_as_a_turn(voice_owner, mode, text):+ voice_owner.runner._voice_mode['s'] = mode+ with voice_owner.db:+ reply = await _call(_connection(voice_owner.authority), 'prompt.submit', text=text, submission_id='r1')+ assert reply['result']['status'] == 'queued', reply+ assert voice_owner.runner._voice_mode['s'] == mode+ assert len(list_session_admissions(voice_owner.db, session_id='s', pending_only=False)) == 1+++async def test_a_stranger_cannot_end_the_voice_chat(voice_owner):+ voice_owner.runner._voice_mode['s'] = 'voice_only'+ conn = _connection(voice_owner.authority)+ conn.subscriptions.pop('s')+ with voice_owner.db:+ reply = await _call(conn, 'prompt.submit', text='stop', submission_id='r1')+ assert reply['error']['data']['reason'] == 'permission_denied', reply+ assert voice_owner.runner._voice_mode['s'] == 'voice_only'+++def test_the_canonical_contract_declares_the_voice_stopped_reply():+ from tui_gateway.contracts.registry import CANONICAL_METHODS+ contract = CANONICAL_METHODS['prompt.submit']+ contract.result.model_validate({'voice_stopped': True})+ with pytest.raises(Exception):+ contract.result.model_validate({'voice_stopped': False})diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.pyindex b6734f17395..de1973d9aa9 100644--- a/tui_gateway/contracts/canonical_sessions.py+++ b/tui_gateway/contracts/canonical_sessions.py@@ -4,6 +4,8 @@ Reuse upstream authority-only value shapes; these overrides do not widen METHODS"""from typing import Literal+from pydantic import RootModel+from .base import JsonValue, Params, Resultfrom .common import ProfileParams, TranscriptMessagefrom .connectors_operation import ConnectionRequestPayload@@ -225,6 +227,17 @@ class CanonicalSubmitParams(CanonicalSessionParams):clarify_batch: bool = False+class CanonicalVoiceStopped(Result):+ """A bare stop phrase typed while the session's voice chat is on: the chat ended, nothing was+ admitted (TUI-26)."""++ voice_stopped: Literal[True]+++class CanonicalSubmitResult(RootModel[AdmissionStatus | CanonicalVoiceStopped]):+ """``prompt.submit``: the admission receipt, or ``{voice_stopped: true}``."""++class CanonicalSteerQueuedParams(CanonicalSessionParams):admission_id: str@@ -296,7 +309,7 @@ for _name, _params, _result in (('session.steer', CanonicalCorrectionParams, CanonicalCorrectionResult),('session.redirect', CanonicalCorrectionParams, CanonicalCorrectionResult),('session.events.since', CanonicalEventsParams, CanonicalEventsResult),- ('prompt.submit', CanonicalSubmitParams, AdmissionStatus),+ ('prompt.submit', CanonicalSubmitParams, CanonicalSubmitResult),('approval.respond', CanonicalApprovalParams, PromptResponseResult),):canonical_method(_name, params=_params, result=_result)diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex bc648f181f0..66dc551533e 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -236,25 +236,36 @@ def _pending_reaction_notes(session: dict) -> str:# ── prompt.submit pieces ────────────────────────────────────────────────────-def _typed_stop_phrase_response(rid, text, sid=None):- """RPC reply ending the voice chat when a bare stop phrase is TYPED while the session's voice- mode is on (typed twin of the spoken stop phrase), or None for a normal message."""+def _consume_typed_stop_phrase(text, sid=None, *, emit: bool = True) -> bool:+ """End *sid*'s voice chat when *text* is a bare stop phrase TYPED while its voice mode is on+ (typed twin of the spoken stop phrase) -> True; False for a normal message. *emit* sends the+ ``voice.transcript`` stop event to the voice client; the canonical ``prompt.submit`` path+ (``gateway/session_controls.py``) answers its submitter in the reply instead (TUI-26)."""if not (isinstance(text, str) and _session_voice_enabled(sid)):- return None+ return Falsetry:# Typed bare stop phrase while backend voice mode is active ends the voice chat instead of sending- # "stop" to the agent — the typed twin of the spoken stop phrase (PR #73106), applied at the ONE- # server-side choke point every TUI submit passes through. (The desktop's voice conversation is- # renderer-owned and never flips the backend flag, so it handles its own typed stop client-side.)+ # "stop" to the agent — the typed twin of the spoken stop phrase (PR #73106), applied at the+ # server-side choke point every TUI submit passes through: this sidecar handler and the shared+ # owner's canonical prompt.submit. (The desktop's voice conversation is renderer-owned and never+ # flips the backend flag, so it handles its own typed stop client-side.)from tools.voice_mode_transcript import is_voice_stop_phraseif not is_voice_stop_phrase(text):- return None- except Exception:- return None+ return False+ except Exception: # an unreadable voice config never swallows the message: it reaches the agent+ logger.debug("typed stop-phrase check failed; submitting the text", exc_info=True)+ return False_end_session_voice_chat(sid, stop_loop=True, stop_tts=True)- _voice_emit("voice.transcript", {"stop_phrase": True, "typed": True})+ if emit:+ _voice_emit("voice.transcript", {"stop_phrase": True, "typed": True})logger.info("prompt.submit: typed stop phrase — voice chat ended")- return _ok(rid, {"voice_stopped": True})+ return True+++def _typed_stop_phrase_response(rid, text, sid=None):+ """RPC reply ending the voice chat when a bare stop phrase is TYPED while the session's voice+ mode is on (typed twin of the spoken stop phrase), or None for a normal message."""+ return _ok(rid, {"voice_stopped": True}) if _consume_typed_stop_phrase(text, sid) else None_HOSTED_TASK_FIELDS = {"room_id", "task_id", "thread_id", "turn_id", "execution_generation", "member_id"}diff --git a/ui-tui/src/__tests__/submissionCore.test.ts b/ui-tui/src/__tests__/submissionCore.test.tsindex b43f7209f06..21f831a6668 100644--- a/ui-tui/src/__tests__/submissionCore.test.ts+++ b/ui-tui/src/__tests__/submissionCore.test.ts@@ -259,3 +259,44 @@ describe('submissionCore.submitPrompt — voice marker ownership', () => {await vi.waitFor(() => expect(request.mock.calls.at(-1)?.[1]).toMatchObject({ voice_turn: true }))})})++describe('submissionCore.submitPrompt — typed voice stop on the shared gateway (TUI-26)', () => {+ beforeEach(() => {+ resetUiState()+ patchUiState({ sid: 'sess-1' })+ })++ it('renders the voice_stopped reply as the stop-phrase event, settles the item, never as an unconfirmed admission', async () => {+ const request = vi.fn(async () => ({ voice_stopped: true }))+ const publishLocalEvent = vi.fn()+ const gw = { isCanonical: true, publishLocalEvent, request } as unknown as GatewayClient+ const sys = vi.fn()+ const settle = vi.fn()++ submitPrompt('stop', makeDeps(gw, { sys }), true, undefined, {+ destination: captureDestination(),+ queueItem: { settle, submissionId: 's1', text: 'stop' } as never,+ skipDetectDrop: true+ })++ await vi.waitFor(() => expect(settle).toHaveBeenCalledWith(true))+ expect(publishLocalEvent).toHaveBeenCalledWith({+ payload: { stop_phrase: true, typed: true },+ session_id: 'sess-1',+ type: 'voice.transcript'+ })+ expect(getUiState().busy).toBe(false)+ expect(sys).not.toHaveBeenCalled()+ })++ it('the sidecar already emitted the event: no second local one', async () => {+ const request = vi.fn(async () => ({ voice_stopped: true }))+ const publishLocalEvent = vi.fn()+ const gw = { isCanonical: false, publishLocalEvent, request } as unknown as GatewayClient++ submitPrompt('stop', makeDeps(gw), true, undefined, { skipDetectDrop: true })++ await vi.waitFor(() => expect(getUiState().busy).toBe(false))+ expect(publishLocalEvent).not.toHaveBeenCalled()+ })+})diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.tsindex 6692ec3edb7..0752d1d7cd8 100644--- a/ui-tui/src/app/submissionCore.ts+++ b/ui-tui/src/app/submissionCore.ts@@ -354,15 +354,31 @@ export function submitPrompt(return}- if (item) {- settleAdmissionReply(item, r, { deps, destination, focused, owner, sid })+ // The gateway consumed a typed voice stop phrase server-side (voice+ // chat ended, nothing admitted) — release the busy latch. The sidecar+ // sends a voice.transcript {stop_phrase} event for the mode flags and+ // notice; the shared gateway answers in this reply only (TUI-26), so+ // render that same event locally.+ if (r?.voice_stopped === true) {+ item?.settle?.(true)++ if (deps.gw.isCanonical) {+ deps.gw.publishLocalEvent({+ payload: { stop_phrase: true, typed: true },+ session_id: sid,+ type: 'voice.transcript'+ })+ }++ if (focused()) {+ patchUiState({ busy: false, status: 'ready' })+ }++ return}- // The gateway consumed a typed voice stop phrase server-side (voice- // chat ended, no turn started) — release the busy latch; the- // voice.transcript {stop_phrase} event handles the mode flags + notice.- if (r?.voice_stopped && focused()) {- patchUiState({ busy: false, status: 'ready' })+ if (item) {+ settleAdmissionReply(item, r, { deps, destination, focused, owner, sid })}}).catch(async (e: Error & { code?: number }) => {