Skip to content

The agent that grows with you

fix(audio): accept the local Desktop runtime ticket on voice stream sockets

unsupportedpastels0e74f5bd80bc
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.ts
index ad3451d5d74..5f299c077b4 100644
--- a/apps/desktop/electron/local-gateway.test.ts
+++ b/apps/desktop/electron/local-gateway.test.ts
@@ -226,6 +226,20 @@ test('private dial credential is one-use and bound to the requesting native wind
expect(dials.headers({ ...details, webContentsId: 7 })).toBeNull()
})
+test('a voice socket dialed on its own /api/ws reservation drops Origin; other paths do not', () => {
+ const dial = (path: string, dials = createLocalGatewayDials()) => {
+ const url = new URL(dials.prepare('http://127.0.0.1:1234', 'voice-ticket', 7))
+ url.searchParams.delete('ticket')
+ url.pathname = path
+
+ return dials.headers({ url: url.toString(), webContentsId: 7, resourceType: 'webSocket', requestHeaders: { Origin: 'http://renderer' } })
+ }
+
+ expect(dial('/api/audio/speak-stream')).toEqual({})
+ expect(dial('/api/audio/transcribe-stream')).toEqual({})
+ expect(dial('/api/pty')).toBeNull()
+})
+
test('a dial against a replaced local gateway forgets the cached endpoint once and re-ensures', async () => {
const { redialLocalGateway } = await import('./local-gateway')
const endpoints = [{ instance_id: 'dead' }, { instance_id: 'alive' }]
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.ts
index ba80e09a90f..2ae46bc60a3 100644
--- a/apps/desktop/electron/local-gateway.ts
+++ b/apps/desktop/electron/local-gateway.ts
@@ -322,6 +322,9 @@ function dialOf(url: string): { nonce: string; origin: string; pathname: string
}
}
+// Voice sockets dial their own fresh `/api/ws` reservation on a sibling path (sibling-ws-url.ts).
+const VOICE_DIAL_PATHS = new Set(['/api/audio/speak-stream', '/api/audio/transcribe-stream'])
+
// A one-use ticket crosses private IPC, then leaves the URL before dialing.
// Public descriptors and persisted connection state never contain credentials.
// A plugin socket's native-http grant never enters a URL at all: main attaches
@@ -355,7 +358,9 @@ export function createLocalGatewayDials() {
const dial = dialOf(details.url)
const grant = dial ? pending.get(dial.nonce) : undefined
- if (!dial || !grant || grant.pathname !== dial.pathname || grant.webContentsId !== details.webContentsId
+ const voice = grant && !grant.header && grant.pathname === '/api/ws' && dial && VOICE_DIAL_PATHS.has(dial.pathname)
+
+ if (!dial || !grant || (grant.pathname !== dial.pathname && !voice) || grant.webContentsId !== details.webContentsId
|| details.resourceType !== 'webSocket' || (grant.header && grant.origin !== dial.origin)) {return null}
pending.delete(dial.nonce)
diff --git a/apps/desktop/src/lib/voice-playback.ts b/apps/desktop/src/lib/voice-playback.ts
index af005a1e136..a8a94b6401b 100644
--- a/apps/desktop/src/lib/voice-playback.ts
+++ b/apps/desktop/src/lib/voice-playback.ts
@@ -3,6 +3,7 @@ import { resolveGatewayWsUrl } from '@hermes/shared'
import type { OwnerScope } from '@/api/client'
import { getApiRequestConnection, getApiRequestProfile, speakText } from '@/hermes'
import { directTtsConfig, type DirectTtsConfig, synthesizeSpeechClientDirect } from '@/lib/voice-client-direct'
+import { openVoiceSocket } from '@/lib/voice-stream'
import { RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'
import {
$voicePlayback,
@@ -389,7 +390,7 @@ function openClientDirectSpeechSession(tts: DirectTtsConfig, options: VoicePlayb
* stream (ChatGPT-style) with no per-sentence connection or synthesis gaps.
*/
function openSpeechStream(wsUrl: string, options: VoicePlaybackOptions): SpeechStreamSession {
- const ws = new WebSocket(wsUrl)
+ const ws = openVoiceSocket(wsUrl)
ws.binaryType = 'arraybuffer'
let context: AudioContext | null = null
diff --git a/apps/desktop/src/lib/voice-stream.test.ts b/apps/desktop/src/lib/voice-stream.test.ts
new file mode 100644
index 00000000000..30b3ba35dc8
--- /dev/null
+++ b/apps/desktop/src/lib/voice-stream.test.ts
@@ -0,0 +1,36 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { openVoiceSocket } from './voice-stream'
+
+// A local gateway admits its voice sockets on the /api/ws dial's grant, in the gateway
+// subprotocol only (RT-71, RT-80); a remote route keeps its own query credential.
+describe('openVoiceSocket', () => {
+ const dials: unknown[][] = []
+
+ afterEach(() => {
+ dials.length = 0
+ vi.unstubAllGlobals()
+ })
+
+ const open = (url: string) => {
+ vi.stubGlobal('WebSocket', function (...args: unknown[]) {
+ dials.push(args)
+ })
+ openVoiceSocket(url)
+
+ return dials[0]
+ }
+
+ it('moves a local dial ticket out of the URL into the gateway subprotocol', () => {
+ expect(open('ws://127.0.0.1:5151/api/audio/speak-stream?native_dial=n1&ticket=t1&profile=beta')).toEqual([
+ 'ws://127.0.0.1:5151/api/audio/speak-stream?native_dial=n1&profile=beta',
+ ['hermes-gateway-v1', 'hermes-gateway-ticket.t1']
+ ])
+ })
+
+ it('leaves a remote credential where the remote gateway reads it', () => {
+ expect(open('wss://gateway.example/api/audio/transcribe-stream?ticket=fresh')).toEqual([
+ 'wss://gateway.example/api/audio/transcribe-stream?ticket=fresh'
+ ])
+ })
+})
diff --git a/apps/desktop/src/lib/voice-stream.ts b/apps/desktop/src/lib/voice-stream.ts
index 4462e03f772..83e2d0fb601 100644
--- a/apps/desktop/src/lib/voice-stream.ts
+++ b/apps/desktop/src/lib/voice-stream.ts
@@ -1,6 +1,22 @@
+import { CANONICAL_GATEWAY_PROTOCOL } from '@/api/canonical-protocol'
import type { ResolvedOwner } from '@/hermes'
import { resolveSiblingWsUrl } from '@/lib/sibling-ws-url'
+/** Dial a voice socket beside `/api/ws`. A local gateway's one-use ticket leaves the URL for the
+ * gateway subprotocol, as on the `/api/ws` dial itself (api/client.ts socketFactory). */
+export function openVoiceSocket(url: string): WebSocket {
+ const parsed = new URL(url)
+ const ticket = parsed.searchParams.get('ticket')
+
+ if (!parsed.searchParams.has('native_dial') || !ticket) {
+ return new WebSocket(url)
+ }
+
+ parsed.searchParams.delete('ticket')
+
+ return new WebSocket(parsed.toString(), [CANONICAL_GATEWAY_PROTOCOL, `hermes-gateway-ticket.${ticket}`])
+}
+
/**
* Live dictation STT: mic PCM streams to the host's `/api/audio/transcribe-stream` WebSocket
* WHILE the user speaks; partial text arrives as it is recognized and the transcript lands right
@@ -43,7 +59,7 @@ export async function openDictationStream(
url.searchParams.set('profile', owner.profile)
}
- const ws = new WebSocket(url.toString())
+ const ws = openVoiceSocket(url.toString())
ws.binaryType = 'arraybuffer'
let settled = false
diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.py
index 20209b503e5..d923d8812f3 100644
--- a/hermes_cli/dashboard_auth/native_http.py
+++ b/hermes_cli/dashboard_auth/native_http.py
@@ -15,7 +15,6 @@ from starlette.responses import JSONResponse
HEADER = 'x-hermes-gateway-ticket'
-@contextmanager
def native_profile_scope(request):
"""Resolve the request's implicit selectors (omitted / '' / 'current') in the TICKET's home.
@@ -26,7 +25,12 @@ def native_profile_scope(request):
binds its home override too, so it never inherits a foreign override that happens to be
ambient in the request context.
"""
- grant = getattr(request.state, 'native_http_principal', None)
+ return grant_home_scope(getattr(request.state, 'native_http_principal', None))
+
+
+@contextmanager
+def grant_home_scope(grant):
+ """Bind *grant*'s home as the task-local home override; no-op without a grant."""
if grant is None:
yield
return
@@ -241,6 +245,34 @@ def redeem_native_ws(conn):
return grant
+AUDIO_STREAM_PATHS = frozenset({'/api/audio/speak-stream', '/api/audio/transcribe-stream'})
+
+
+def redeem_audio_ws(ws):
+ """Redeem the ``interactive`` grant a local Desktop's audio stream upgrade presents; None when refused.
+
+ The voice sockets are siblings of the Desktop's ``/api/ws`` dial and ride the same one-use
+ grant in the same gateway subprotocol (``gateway/run_api.py``), under the HTTP seam's
+ peer/Origin/served-profile rules. The upgrade's ``profile`` selectors must name the grant's home.
+ """
+ from hermes_cli.web_server_boundary import _gateway_ws_ticket_from_subprotocol
+ ticket, reason = _gateway_ws_ticket_from_subprotocol(ws)
+ gate = _native_store(ws, [ticket]) if reason == 'ok' and ws.url.path in AUDIO_STREAM_PATHS else None
+ if gate is None:
+ return None
+ runner, store = gate
+ from gateway.session_authorities import authority_for_profile_id
+ try:
+ grant = store.redeem(ticket, profile_id=None, purpose='interactive')
+ if authority_for_profile_id(runner, grant['profile_id']) is None:
+ return None
+ for value in ws.query_params.getlist('profile'):
+ _own_profile(value, grant['profile_id'])
+ except PermissionError:
+ return None
+ return grant
+
+
def authenticate_native_ws(ws):
"""The grant :func:`redeem_native_ws` admitted for this plugin socket, or None (refused).
diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.py
index 51a255c5c1d..860a9ce832c 100644
--- a/hermes_cli/web_routers/audio.py
+++ b/hermes_cli/web_routers/audio.py
@@ -17,6 +17,7 @@ import os
import urllib.parse
import urllib.request
from fastapi import APIRouter
+from hermes_cli.dashboard_auth.native_http import grant_home_scope
from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
from hermes_cli.web_server_chat import _ws_auth_ok, _ws_request_is_allowed
@@ -533,15 +534,16 @@ async def transcribe_stream_ws(ws: WebSocket) -> None:
if not _ws_request_is_allowed(ws):
await ws.close(code=4403)
return
- await ws.accept()
+ await ws.accept(subprotocol=getattr(ws, "_hermes_ws_subprotocol", None))
profile = (ws.query_params.get("profile") or "").strip() or None
+ grant = getattr(ws, "_hermes_native_grant", None)
loop = asyncio.get_running_loop()
partials: asyncio.Queue = asyncio.Queue()
def _open():
from tools.transcription_streaming import open_streaming_session
- with _config_profile_scope(profile):
+ with grant_home_scope(grant), _config_profile_scope(profile):
return open_streaming_session(on_partial=lambda text: loop.call_soon_threadsafe(partials.put_nowait, text))
session = None
@@ -580,7 +582,11 @@ async def transcribe_stream_ws(ws: WebSocket) -> None:
session.cancel()
forwarder.cancel()
return
- result = await loop.run_in_executor(None, session.finalize)
+ def _finalize():
+ with grant_home_scope(grant), _config_profile_scope(profile):
+ return session.finalize()
+
+ result = await loop.run_in_executor(None, _finalize)
await asyncio.sleep(0) # let the last partial flush before the final frame
forwarder.cancel()
with contextlib.suppress(Exception):
@@ -620,19 +626,21 @@ async def speak_stream_ws(ws: WebSocket) -> None:
if not _ws_request_is_allowed(ws):
await ws.close(code=4403)
return
- await ws.accept()
+ await ws.accept(subprotocol=getattr(ws, "_hermes_ws_subprotocol", None))
# Profile via query param, like /api/pty and /api/console: the provider
# chain + API keys must resolve from the requesting profile's config, not
- # the dashboard's own — at resolve time AND in the synthesis thread.
+ # the dashboard's own — at resolve time AND in the synthesis thread. A
+ # native grant's home owns the implicit selector (its explicit ones match it).
profile = (ws.query_params.get("profile") or "").strip() or None
+ grant = getattr(ws, "_hermes_native_grant", None)
loop = asyncio.get_running_loop()
def _resolve():
from tools.tts_streaming import resolve_streaming_provider
from tools.tts_tool import _get_provider, _load_tts_config, _resolve_max_text_length
- with _config_profile_scope(profile):
+ with grant_home_scope(grant), _config_profile_scope(profile):
cfg = _load_tts_config()
streamer = resolve_streaming_provider(cfg)
cap = _resolve_max_text_length(_get_provider(cfg), cfg)
@@ -674,7 +682,7 @@ async def speak_stream_ws(ws: WebSocket) -> None:
# Every streamer re-resolves its API key on each stream() call (tts_streaming ->
# resolve_provider_secret), so the whole synthesis body runs under the requesting
# profile's scope, not only the resolve step above (else the launch profile's key).
- with _config_profile_scope(profile):
+ with grant_home_scope(grant), _config_profile_scope(profile):
_synthesize()
def _synthesize():
diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.py
index d09b17ea4d2..12a34123035 100644
--- a/hermes_cli/web_server_chat.py
+++ b/hermes_cli/web_server_chat.py
@@ -231,9 +231,11 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False,
A socket that sends that header is judged by it alone: on a core socket
(``/api/ws``, ``/api/pty``, the audio streams) the grant is refused
(``native_invalid``) even when a valid ``token`` query credential rides along.
- That is intended; only the plugin WebSocket gate accepts the grant.
+ That is intended; only the plugin WebSocket gate accepts the grant. The audio
+ streams instead take the ``interactive`` grant of the Desktop's ``/api/ws`` dial,
+ in its gateway subprotocol (``redeem_audio_ws``), stamped on ``_hermes_native_grant``.
"""
- from hermes_cli.dashboard_auth.native_http import HEADER, authenticate_native_ws
+ from hermes_cli.dashboard_auth.native_http import HEADER, authenticate_native_ws, redeem_audio_ws
from hermes_cli.web_server import _SESSION_TOKEN, app
from hermes_cli.browser_credential import generation_of
from hermes_cli.web_session_sockets import OWN_TICKET_SOCKETS, track
@@ -251,6 +253,12 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False,
return "native_invalid", "native"
ws._hermes_auth_identity = {"user_id": grant["subject"], "provider": "local"}
return None, "native"
+ grant = redeem_audio_ws(ws)
+ if grant is not None:
+ ws._hermes_auth_identity = {"user_id": grant["subject"], "provider": "local"}
+ ws._hermes_native_grant = grant
+ ws._hermes_ws_subprotocol = _GATEWAY_WS_PROTOCOL
+ return None, "native"
if auth_required:
# Lazy import — keeps this function importable in test harnesses
# that don't bring in the dashboard_auth layer.
diff --git a/tests/hermes_cli/test_audio_stream_native_ws.py b/tests/hermes_cli/test_audio_stream_native_ws.py
new file mode 100644
index 00000000000..474ae5df248
--- /dev/null
+++ b/tests/hermes_cli/test_audio_stream_native_ws.py
@@ -0,0 +1,66 @@
+"""A local Desktop's voice sockets ride the grant of its ``/api/ws`` dial (RT-71, RT-80).
+
+Desktop dials ``/api/audio/speak-stream`` and ``/api/audio/transcribe-stream`` beside its
+``/api/ws`` socket with the same one-use ``interactive`` grant in the gateway subprotocol. Those
+upgrades were refused on a local gateway (it holds no static token), so spoken replies and live
+dictation never streamed. The grant's home, not ``?profile=``, decides whose voice config runs.
+"""
+from __future__ import annotations
+
+import pytest
+from starlette.websockets import WebSocketDisconnect
+
+from hermes_cli import web_server
+from tests.hermes_cli import test_plugin_api_consent_gate as consent_gate
+
+daemon = consent_gate.daemon # the multiplexed daemon stand-in fixture
+
+SPEAK, TRANSCRIBE = "/api/audio/speak-stream", "/api/audio/transcribe-stream"
+
+
+def _dial(home, purpose="interactive"):
+ ticket = web_server.app.state.gateway_runner.session_ticket_store.mint(
+ profile_id=str(home), subject="desktop", purpose=purpose)
+ return ["hermes-gateway-v1", f"hermes-gateway-ticket.{ticket}"]
+
+
+def stt_homes(monkeypatch):
+ from hermes_constants import get_hermes_home
+ from tools import transcription_streaming
+ homes = []
+
+ def open_streaming_session(**_): # no live STT: the socket answers an error frame and closes
+ homes.append(get_hermes_home())
+
+ monkeypatch.setattr(transcription_streaming, "open_streaming_session", open_streaming_session)
+ return homes
+
+
[email protected]("path", [SPEAK, TRANSCRIBE])
+def test_desktop_grant_opens_the_voice_sockets(daemon, stt_homes, path):
+ with daemon.client.websocket_connect(path, subprotocols=_dial(daemon.beta)) as ws:
+ assert ws.accepted_subprotocol == "hermes-gateway-v1" # the browser fails the handshake otherwise
+ if path == TRANSCRIBE:
+ assert ws.receive_json()["type"] == "error"
+ if path == TRANSCRIBE:
+ assert stt_homes == [daemon.beta] # the grant's profile, with no ?profile= selector
+
+
[email protected]("case", ["no_credential", "other_profile", "browser_origin", "wrong_purpose"])
+def test_other_upgrades_are_still_refused(daemon, stt_homes, case):
+ (daemon.launch / "profiles" / "gamma").mkdir()
+ path = TRANSCRIBE
+ kwargs: dict = {"subprotocols": _dial(daemon.beta)}
+ if case == "no_credential":
+ kwargs = {}
+ elif case == "other_profile":
+ path += "?profile=gamma"
+ elif case == "browser_origin":
+ kwargs["headers"] = {"origin": "http://evil.example"}
+ else:
+ kwargs["subprotocols"] = _dial(daemon.beta, purpose="native-http")
+ with pytest.raises(WebSocketDisconnect) as refused, daemon.client.websocket_connect(path, **kwargs):
+ pass
+ assert refused.value.code == 4401
+ assert stt_homes == []