Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: files changed crates/openhuman-core/src/modules/voice.rs,crates/openhuman-core/src/modules/vo

Steven Enamakel4617177da790
diff --git a/crates/openhuman-core/src/modules/voice.rs b/crates/openhuman-core/src/modules/voice.rs
index fc2351bed6..5af6f756e3 100644
--- a/crates/openhuman-core/src/modules/voice.rs
+++ b/crates/openhuman-core/src/modules/voice.rs
@@ -486,33 +486,6 @@ pub async fn frame_energies(
.await
}
-/// Frame 16-bit PCM samples as a WAV file, without touching the samples.
-///
-/// Distinct from [`encode_wav`] because a caller holding `i16` should not have
-/// to widen to `f32` and let the module narrow back: that round trip is lossy
-/// by one LSB for no reason. This path is exact.
-///
-/// # Errors
-///
-/// [`VoiceCallError`] when the module is unavailable or the call fails.
-pub async fn encode_wav_pcm16(
- config: &Config,
- samples: &[i16],
- sample_rate: u32,
- channels: u16,
-) -> Result<Vec<u8>, VoiceCallError> {
- use base64::Engine as _;
- let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
- let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
- let wav: String = call(
- config,
- methods::ENCODE_WAV_PCM16,
- (encoded, sample_rate, channels),
- )
- .await?;
- decode_audio(&wav)
-}
-
/// Load the voice module if it is not already serving.
///
/// Callers do not have to invoke this — every operation above does it — but a
diff --git a/crates/openhuman-core/src/modules/voice_tests.rs b/crates/openhuman-core/src/modules/voice_tests.rs
index 25ba8d1596..215d7ec2b1 100644
--- a/crates/openhuman-core/src/modules/voice_tests.rs
+++ b/crates/openhuman-core/src/modules/voice_tests.rs
@@ -283,14 +283,6 @@ async fn the_published_module_answers_through_this_client() {
.expect("frame_energies");
assert_eq!(energies.len(), 4);
- // PCM16 framing must return the caller's samples untouched.
- let pcm: Vec<i16> = vec![0, 1, -1, i16::MAX];
- let wav = super::encode_wav_pcm16(&config, &pcm, 16_000, 1)
- .await
- .expect("encode_wav_pcm16");
- let expected: Vec<u8> = pcm.iter().flat_map(|s| s.to_le_bytes()).collect();
- assert_eq!(&wav[44..], &expected[..]);
-
// A VAD session must segment across separate pushes — the whole reason it
// is a session and not a batch.
let vad = super::VadConfig {
@@ -406,10 +398,6 @@ async fn every_entry_point_degrades_rather_than_hanging_when_the_module_is_gone(
super::frame_energies(&config, &[0.1, 0.2], 1).await,
Err(VoiceCallError::Unavailable(_))
));
- assert!(matches!(
- super::encode_wav_pcm16(&config, &[1i16, 2], 16_000, 1).await,
- Err(VoiceCallError::Unavailable(_))
- ));
}
#[test]
@@ -430,7 +418,6 @@ fn every_member_this_client_calls_is_one_the_contract_declares() {
methods::PREPARE_FRAMES,
methods::FRAME_ENERGIES,
methods::ENCODE_WAV,
- methods::ENCODE_WAV_PCM16,
methods::PREPARE_CAPTURE,
methods::CAPTURE_POLL,
methods::CAPTURE_SHUTDOWN,
diff --git a/crates/openhuman-core/src/voice/streaming.rs b/crates/openhuman-core/src/voice/streaming.rs
deleted file mode 100644
index 235348c2af..0000000000
--- a/crates/openhuman-core/src/voice/streaming.rs
+++ /dev/null
@@ -1,230 +0,0 @@
-//! OpenHuman WebSocket adapter for streaming transcription.
-//!
-//! Accepts a WebSocket connection that receives PCM16 audio chunks (16kHz mono),
-//! accumulates them, and transcribes the completed utterance through the hosted
-//! STT engine when the client stops.
-//!
-//! Protocol (unchanged — the client contract predates the engine swap):
-//! Client → Server: binary frames containing PCM16 LE audio bytes (16kHz mono)
-//! Server → Client: JSON text frames:
-//! { "type": "partial", "text": "..." } — interim transcription
-//! { "type": "final", "text": "...", "raw_text": "..." } — after client sends
-//! `{"type":"stop"}` text frame
-//! { "type": "error", "message": "..." } — on error
-//! Client → Server: text frame `{"type":"stop"}` — end recording, get final result
-//!
-//! ## No partial results
-//! `partial` frames are part of the protocol but are never emitted any more.
-//! They came from the bundled in-process whisper.cpp engine, which could
-//! re-decode a 15-second sliding window every 500 ms for free. That engine is
-//! gone — STT is a hosted round trip now (`voice_server.stt_engine`) — and
-//! re-uploading the window on every tick would multiply the request count and
-//! the bill by ~30× for text the client discards a moment later. The frame type
-//! stays in the protocol so a future streaming-capable engine can start sending
-//! it without a client change; `dictation.streaming` only controls whether we
-//! log that partials were requested.
-//!
-//! # Security notes
-//!
-//! ## Authentication
-//! `GET /ws/dictation` is authenticated at the upgrade boundary (C4 / issue #1924).
-//! The browser WebSocket API cannot set arbitrary request headers on upgrade, so the
-//! check lives in `dictation_ws_handler` (`crates/openhuman-rpc/src/server/http/dictation.rs`), not here: it requires
-//! the per-process core bearer via `Authorization: Bearer <token>` (native callers) or
-//! `?token=<token>` (browser clients), plus the same origin allowlist Socket.IO enforces,
-//! and rejects the upgrade with 401/403 before this function runs. Do NOT add a
-//! Bearer-header check in this function — by the time `handle_dictation_ws` is reached the
-//! upgrade has already been authenticated, and a header check here would not work from
-//! browsers anyway.
-//!
-//! ## Memory cap
-//! The full-audio accumulation buffer (`full_audio_buf`) is bounded by
-//! `MAX_FULL_AUDIO_SAMPLES` (~5 min at 16 kHz). Clients that stream beyond this limit
-//! are disconnected with an error frame; see `append_stream_samples`.
-
-use std::sync::Arc;
-
-use axum::extract::ws::{Message, WebSocket};
-use tokio::sync::Mutex;
-
-use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
-
-use super::postprocess;
-use crate::config::Config;
-use crate::voice::{create_stt_provider, effective_stt_provider};
-
-const LOG_PREFIX: &str = "[voice-stream]";
-use tinyinference_voice::streaming::{
- append_stream_samples, decode_pcm16le_frame, is_stop_command, AUDIO_SAMPLE_RATE,
- MAX_FULL_AUDIO_SAMPLES,
-};
-
-/// Handle an upgraded WebSocket connection for streaming dictation.
-pub async fn handle_dictation_ws(mut socket: WebSocket, config: Arc<Config>) {
- log::info!("{LOG_PREFIX} new streaming dictation connection");
-
- let audio_buf: Arc<Mutex<Vec<i16>>> = Arc::new(Mutex::new(Vec::new()));
- let full_audio_buf: Arc<Mutex<Vec<i16>>> = Arc::new(Mutex::new(Vec::new()));
- if config.dictation.streaming {
- log::debug!(
- "{LOG_PREFIX} dictation.streaming is on but the configured STT engine has no partial \
- transcription path — only the final result will be sent"
- );
- }
-
- loop {
- match socket.recv().await {
- Some(Ok(Message::Binary(data))) => {
- let Some(samples) = decode_pcm16le_frame(&data) else {
- log::warn!("{LOG_PREFIX} received odd-length binary frame, skipping");
- continue;
- };
-
- let cap_exceeded = {
- let mut full = full_audio_buf.lock().await;
- let mut buf = audio_buf.lock().await;
- let ok = append_stream_samples(&mut buf, &mut full, &samples);
- if ok {
- log::trace!(
- "{LOG_PREFIX} buffered {} new samples, total {}",
- samples.len(),
- buf.len()
- );
- }
- !ok
- };
-
- if cap_exceeded {
- // Send an error frame and close — never OOM.
- let err_msg = serde_json::json!({
- "type": "error",
- "message": format!(
- "Recording limit reached: maximum {} minutes of audio per session",
- MAX_FULL_AUDIO_SAMPLES / AUDIO_SAMPLE_RATE / 60
- ),
- });
- let _ = socket.send(Message::Text(err_msg.to_string().into())).await;
- log::warn!(
- "{LOG_PREFIX} disconnecting client: full_audio_buf cap ({} samples, \
- {} min at 16 kHz) exceeded",
- MAX_FULL_AUDIO_SAMPLES,
- MAX_FULL_AUDIO_SAMPLES / AUDIO_SAMPLE_RATE / 60,
- );
- return;
- }
- }
-
- Some(Ok(Message::Text(text))) => {
- if is_stop_command(&text) {
- log::info!("{LOG_PREFIX} stop command received, running final transcription");
- break; // fall through to final transcription
- }
- }
-
- Some(Ok(Message::Close(_))) | None => {
- log::info!("{LOG_PREFIX} client disconnected");
- return;
- }
-
- Some(Err(e)) => {
- log::warn!("{LOG_PREFIX} websocket error: {e}");
- return;
- }
-
- _ => {}
- }
- }
-
- // Run the final transcription on the complete buffer.
- let final_samples = full_audio_buf.lock().await.clone();
- if final_samples.is_empty() {
- let msg = serde_json::json!({
- "type": "final",
- "text": "",
- "raw_text": "",
- });
- let _ = socket.send(Message::Text(msg.to_string().into())).await;
- return;
- }
-
- log::info!(
- "{LOG_PREFIX} transcribing {} samples ({:.1}s) via the configured STT engine",
- final_samples.len(),
- final_samples.len() as f64 / AUDIO_SAMPLE_RATE as f64
- );
-
- // The client streams headerless PCM16LE; the hosted endpoint needs a
- // container, so wrap it in a WAV before upload. `EncodeWavPcm16` keeps the
- // samples exact rather than round-tripping them through `f32`.
- let wav_bytes = match crate::modules::voice::encode_wav_pcm16(
- &config,
- &final_samples,
- AUDIO_SAMPLE_RATE as u32,
- 1,
- )
- .await
- {
- Ok(bytes) => bytes,
- Err(error) => {
- // Tell the client before dropping the socket. WAV framing became
- // fallible when it moved to the module, and a client waiting for
- // `final` or `error` would otherwise get neither — every other
- // failure path in this handler sends a frame first.
- //
- // The frame carries no module detail, matching the redaction the
- // transcription-failure path below uses: the reason is a host
- // concern and goes to the log, not to the renderer.
- log::warn!("{LOG_PREFIX} could not frame dictation audio as WAV: {error}");
- let err_msg = serde_json::json!({
- "type": "error",
- "message": "Could not prepare the recording for transcription",
- });
- let _ = socket.send(Message::Text(err_msg.to_string().into())).await;
- return;
- }
- };
- let provider_name = effective_stt_provider(&config);
- let audio_base64 = BASE64.encode(&wav_bytes);
- let raw_text = match async {
- let provider =
- create_stt_provider(&provider_name, "", &config).map_err(|error| error.to_string())?;
- provider
- .transcribe(
- &config,
- &audio_base64,
- Some("audio/wav"),
- Some("dictation.wav"),
- None,
- )
- .await
- }
- .await
- {
- Ok(outcome) => outcome.value.text,
- Err(e) => {
- log::warn!("{LOG_PREFIX} configured transcription failed: {e}");
- let msg = serde_json::json!({
- "type": "error",
- "message": format!("Transcription failed: {e}"),
- });
- let _ = socket.send(Message::Text(msg.to_string().into())).await;
- return;
- }
- };
-
- // LLM refinement if enabled
- let refined_text = if config.dictation.llm_refinement && !raw_text.is_empty() {
- postprocess::cleanup_transcription(&config, &raw_text, None).await
- } else {
- raw_text.clone()
- };
-
- let msg = serde_json::json!({
- "type": "final",
- "text": refined_text,
- "raw_text": raw_text,
- });
- let _ = socket.send(Message::Text(msg.to_string().into())).await;
- log::info!("{LOG_PREFIX} streaming session complete");
- // Socket is dropped here, which sends a close frame automatically
-}
diff --git a/crates/openhuman-core/src/voice/stub.rs b/crates/openhuman-core/src/voice/stub.rs
deleted file mode 100644
index 9daa3dbc9c..0000000000
--- a/crates/openhuman-core/src/voice/stub.rs
+++ /dev/null
@@ -1,213 +0,0 @@
-//! Disabled-voice facade.
-//!
-//! Compiled only when the `voice` Cargo feature is OFF (see the gate in
-//! [`super`]). It mirrors the subset of the real `voice` public surface that
-//! always-on / other-gated callers depend on, with no-op / disabled-error
-//! bodies so the crate still compiles, boots, and serves `/rpc` without the
-//! voice domain.
-//!
-//! The signatures here MUST match the real ones exactly (return types included).
-//! The disabled build
-//! (`cargo check --no-default-features --features "<all-but-voice>"`) is the
-//! only thing that catches drift — if a real signature changes, update the
-//! mirror below until that build is green again.
-
-use async_trait::async_trait;
-use serde::{Deserialize, Serialize};
-
-use crate::config::Config;
-use crate::core::Outcome;
-
-/// Error text returned by every disabled-path operation that must yield a
-/// `Result`. Shared so callers/log-greps see one stable string.
-const DISABLED_MSG: &str = "voice feature disabled at compile time";
-
-// ---------------------------------------------------------------------------
-// Provider factory surface (mirrors `factory::*` re-exported at the voice root)
-// ---------------------------------------------------------------------------
-
-/// Common STT result shape. Mirrors [`super::factory::SttResult`] (real build).
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct SttResult {
- pub text: String,
- /// Lowercase provider id — kept for wire-shape parity with the real type.
- pub provider: String,
-}
-
-/// Speech-to-text provider abstraction. Object-safe (via `async_trait`) so
-/// `Box<dyn SttProvider>` remains nameable at call sites; no concrete
-/// implementation exists when voice is compiled out.
-#[async_trait]
-pub trait SttProvider: Send + Sync {
- fn name(&self) -> &'static str;
-
- async fn transcribe(
- &self,
- config: &Config,
- audio_base64: &str,
- mime_type: Option<&str>,
- file_name: Option<&str>,
- language: Option<&str>,
- ) -> Result<Outcome<SttResult>, String>;
-
- #[cfg(test)]
- fn configured_model(&self) -> Option<&str> {
- None
- }
-}
-
-/// Resolve the effective STT provider string. With voice disabled the value is
-/// never used to build a real provider; the config-independent default keeps
-/// logging/telemetry callers seeing a sensible string.
-pub fn effective_stt_provider(_config: &Config) -> String {
- "cloud".to_string()
-}
-
-/// Always errors: no STT provider can be constructed when voice is compiled
-/// out. Callers `?`-propagate the error, so the boxed provider is never used.
-pub fn create_stt_provider(
- _provider: &str,
- _model: &str,
- _config: &Config,
-) -> anyhow::Result<Box<dyn SttProvider>> {
- Err(anyhow::anyhow!(DISABLED_MSG))
-}
-
-// ---------------------------------------------------------------------------
-// Event bus surface (mirrors `bus::publish_ptt_transcript_committed`)
-// ---------------------------------------------------------------------------
-
-/// No-op: with voice disabled there is no PTT dictation path to announce.
-pub fn publish_ptt_transcript_committed(
- _thread_id: String,
- _session_id: u64,
- _text_len: usize,
- _held_ms: u64,
- _finalized_by_watchdog: bool,
-) {
- log::debug!("[voice-stub] publish_ptt_transcript_committed ignored (voice disabled)");
-}
-
-// ---------------------------------------------------------------------------
-// cli::run_standalone_subcommand (kept registered as a CLI adapter)
-// ---------------------------------------------------------------------------
-
-pub mod cli {
- /// Disabled: the standalone dictation server needs the voice stack. Returns
- /// an error so `openhuman voice` reports the feature is off instead of the
- /// subcommand silently disappearing from the CLI registry.
- pub fn run_standalone_subcommand(_args: &[String]) -> anyhow::Result<()> {
- Err(anyhow::anyhow!(super::DISABLED_MSG))
- }
-}
-
-// ---------------------------------------------------------------------------
-// server::{start_if_enabled, try_global_server}
-// ---------------------------------------------------------------------------
-
-pub mod server {
- use std::sync::Arc;
-
- use crate::config::Config;
-
- /// Opaque handle; never actually constructed when voice is disabled, but
- /// kept nameable so `Option<Arc<VoiceServer>>` call sites type-check.
- pub struct VoiceServer;
-
- impl VoiceServer {
- /// No-op stop — unreachable (no server is ever created).
- pub async fn stop(&self) {}
- }
-
- /// No-op: there is no voice server to start.
- pub async fn start_if_enabled(_ctx: &crate::core::runtime::DispatchCtx, _config: &Config) {}
-
- /// Always `None`: no global voice server exists.
- pub fn try_global_server() -> Option<Arc<VoiceServer>> {
- None
- }
-}
-
-// ---------------------------------------------------------------------------
-// dictation_listener::{start_if_enabled, stop, subscribe_*}
-// ---------------------------------------------------------------------------
-
-pub mod dictation_listener {
- use once_cell::sync::Lazy;
- use serde::Serialize;
- use tokio::sync::broadcast;
-
- use crate::config::Config;
-
- /// Mirrors the real `DictationEvent` wire shape so the Socket.IO bridge's
- /// `serde_json::to_value(&event)` + `event.event_type` access type-check.
- #[derive(Debug, Clone, Serialize)]
- pub struct DictationEvent {
- #[serde(rename = "type")]
- pub event_type: String,
- pub hotkey: String,
- pub activation_mode: String,
- }
-
- // Senders are kept alive for the process lifetime so subscribers park
- // (never receive) rather than seeing an immediate `Closed`, matching the
- // real always-open broadcast bus. Nothing is ever published.
- static DICTATION_BUS: Lazy<broadcast::Sender<DictationEvent>> =
- Lazy::new(|| broadcast::channel(1).0);
- static TRANSCRIPTION_BUS: Lazy<broadcast::Sender<String>> =
- Lazy::new(|| broadcast::channel(1).0);
-
- /// Subscribe to (never-emitting) dictation events.
- pub fn subscribe_dictation_events() -> broadcast::Receiver<DictationEvent> {
- DICTATION_BUS.subscribe()
- }
-
- /// Subscribe to (never-emitting) transcription results.
- pub fn subscribe_transcription_results() -> broadcast::Receiver<String> {
- TRANSCRIPTION_BUS.subscribe()
- }
-
- /// No-op: no hotkey listener is started.
- pub async fn start_if_enabled(_ctx: &crate::core::runtime::DispatchCtx, _config: &Config) {}
-
- /// No-op: nothing to stop.
- pub async fn stop() {}
-}
-
-// ---------------------------------------------------------------------------
-// always_on::{start_if_enabled, stop}
-// ---------------------------------------------------------------------------
-
-pub mod always_on {
- use crate::config::Config;
-
- /// No-op: always-on listening does not exist when voice is disabled.
- pub async fn start_if_enabled(_ctx: &crate::core::runtime::DispatchCtx, _config: &Config) {}
-
- /// No-op: nothing to stop.
- pub fn stop() {}
-
- /// No-op: no module capture leases exist when voice is disabled.
- pub async fn shutdown() {}
-}
-
-// `live::ws::handle_live_voice_ws`: with voice off there are no live
-// providers, so the upgraded socket is dropped immediately.
-#[cfg(feature = "http-server")]
-pub mod live {
- pub mod ws {
- use std::sync::Arc;
-
- use axum::extract::ws::WebSocket;
-
- use crate::config::Config;
-
- /// Drop the upgraded socket immediately — live voice is compiled out.
- pub async fn handle_live_voice_ws(
- _socket: WebSocket,
- _ctx: crate::core::runtime::DispatchCtx,
- _config: Arc<Config>,
- ) {
- }
- }
-}
diff --git a/crates/openhuman-rpc/src/server/http/dictation.rs b/crates/openhuman-rpc/src/server/http/dictation.rs
deleted file mode 100644
index f01ca36e5e..0000000000
--- a/crates/openhuman-rpc/src/server/http/dictation.rs
+++ /dev/null
@@ -1,139 +0,0 @@
-//! `GET /ws/dictation`: the authenticated voice-dictation WebSocket.
-
-use std::sync::Arc;
-
-use axum::extract::{Query, WebSocketUpgrade};
-use axum::http::{header, StatusCode};
-use axum::response::{IntoResponse, Response};
-use axum::Json;
-use serde_json::json;
-
-use crate::core_host::core::runtime::DispatchCtx;
-
-/// Query parameters for the dictation WebSocket endpoint.
-///
-/// Browser `WebSocket` cannot attach an `Authorization` header on upgrade, so
-/// the FE forwards the per-process core bearer as a `?token=…` query param —
-/// validated against the same in-process RPC token via [`verify_bearer_token`]
-/// (single source of truth, no separate credential).
-#[derive(Debug, serde::Deserialize)]
-pub(super) struct DictationQuery {
- #[serde(default)]
- token: Option<String>,
-}
-
-/// WebSocket upgrade handler for streaming voice dictation.
-///
-/// Authenticated before upgrade (C4 / issue #1924): the request must carry the
-/// per-process core bearer either as `Authorization: Bearer <token>` (CLI /
-/// native callers) or as `?token=<token>` (browser `WebSocket`, which cannot
-/// set headers), and — when an `Origin` header is present — that origin must be
-/// on the local-app allowlist, mirroring the Socket.IO handshake check. Missing
-/// or wrong credentials are rejected with 401 and the socket is never upgraded.
-pub(super) async fn dictation_ws_handler(
- headers: axum::http::HeaderMap,
- ctx: Option<axum::extract::Extension<DispatchCtx>>,
- Query(query): Query<DictationQuery>,
- ws: WebSocketUpgrade,
-) -> Response {
- log::info!("[ws] dictation WebSocket upgrade requested");
-
- if let Err(error) = authorize_dictation_request(&headers, &query) {
- return error.into_response();
- }
-
- // The context the serving middleware attached; the upgraded socket runs on
- // its own task, so the config is read under it, not the task's.
- let ctx = ctx.map_or_else(DispatchCtx::unbound, |axum::extract::Extension(ctx)| ctx);
- ws.on_upgrade(|socket| async move {
- let config = match ctx.load_config().await {
- Ok(c) => Arc::new(c),
- Err(e) => {
- log::error!("[ws] failed to load config for dictation: {e}");
- return;
- }
- };
- crate::core_host::voice::streaming::handle_dictation_ws(socket, config).await;
- })
-}
-
-pub(super) fn authorize_dictation_request(
- headers: &axum::http::HeaderMap,
- query: &DictationQuery,
-) -> Result<(), DictationAuthError> {
- // Origin check (same allowlist Socket.IO enforces): native clients send no
- // Origin and are accepted; cross-origin browser pages are rejected even if
- // they somehow hold the bearer.
- let origin = headers
- .get(header::ORIGIN)
- .and_then(|v| v.to_str().ok())
- .map(str::trim);
- if !crate::server::socketio::origin_is_allowed(origin) {
- log::warn!("[ws] dictation upgrade rejected: disallowed origin {origin:?}");
- return Err(DictationAuthError::Forbidden);
- }
-
- // Bearer check: header first, then `?token=` for browser WebSocket clients.
- let header_token = headers
- .get(header::AUTHORIZATION)
- .and_then(|v| v.to_str().ok())
- .and_then(|v| v.strip_prefix("Bearer "))
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let bearer_ok = header_token
- .map(crate::core_host::core::auth::verify_bearer_token)
- .unwrap_or(false);
- let bearer_ok = bearer_ok
- || query
- .token
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(crate::core_host::core::auth::verify_bearer_token)
- .unwrap_or(false);
- if !bearer_ok {
- log::warn!("[ws] dictation upgrade rejected: missing or invalid bearer token");
- return Err(DictationAuthError::Unauthorized);
- }
-
- Ok(())
-}
-
-#[derive(Clone, Copy, Debug)]
-pub(super) enum DictationAuthError {
- Forbidden,
- Unauthorized,
-}
-
-impl DictationAuthError {
- fn status(self) -> StatusCode {
- match self {
- Self::Forbidden => StatusCode::FORBIDDEN,
- Self::Unauthorized => StatusCode::UNAUTHORIZED,
- }
- }
-}
-
-impl IntoResponse for DictationAuthError {
- fn into_response(self) -> Response {
- let (error, message) = match self {
- Self::Forbidden => (
- "forbidden",
- "Origin not allowed for the dictation WebSocket.",
- ),
- Self::Unauthorized => (
- "unauthorized",
- "Missing or invalid token. Supply 'Authorization: Bearer <core>' or ?token=<core>.",
- ),
- };
- (
- self.status(),
- Json(json!({"ok": false, "error": error, "message": message})),
- )
- .into_response()
- }
-}
-
-#[cfg(test)]
-#[path = "dictation_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-rpc/src/server/http/dictation_tests.rs b/crates/openhuman-rpc/src/server/http/dictation_tests.rs
deleted file mode 100644
index 13ee3063cd..0000000000
--- a/crates/openhuman-rpc/src/server/http/dictation_tests.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-use std::sync::Once;
-
-use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
-use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-
-use super::{authorize_dictation_request, DictationQuery};
-
-fn test_token() -> String {
- static INIT: Once = Once::new();
- INIT.call_once(|| {
- crate::core_host::core::auth::init_rpc_token_with_value("dictation-http-tests-token")
- .expect("initialize test bearer");
- });
- crate::core_host::core::auth::get_rpc_token()
- .expect("test bearer initialized")
- .to_string()
-}
-
-fn query(token: Option<&str>) -> DictationQuery {
- DictationQuery {
- token: token.map(str::to_string),
- }
-}
-
-#[test]
-fn dictation_rejects_disallowed_origin_before_authentication() {
- let mut headers = HeaderMap::new();
- headers.insert(
- header::ORIGIN,
- HeaderValue::from_static("https://attacker.example"),
- );
-
- let error = authorize_dictation_request(&headers, &query(Some(&test_token())))
- .expect_err("cross-origin request rejected");
-
- assert_eq!(error.status(), StatusCode::FORBIDDEN);
-}
-
-#[test]
-fn dictation_rejects_missing_and_invalid_credentials() {
- for query in [query(None), query(Some("invalid"))] {
- let error = authorize_dictation_request(&HeaderMap::new(), &query)
- .expect_err("missing or invalid token rejected");
- assert_eq!(error.status(), StatusCode::UNAUTHORIZED);
- }
-}
-
-#[test]
-fn dictation_accepts_bearer_header_and_browser_query_token() {
- let token = test_token();
- let mut headers = HeaderMap::new();
- headers.insert(
- header::AUTHORIZATION,
- HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
- );
- assert!(authorize_dictation_request(&headers, &query(None)).is_ok());
-
- assert!(authorize_dictation_request(&HeaderMap::new(), &query(Some(&token))).is_ok());
-}
-
-#[tokio::test]
-async fn dictation_handler_rejects_disallowed_origin_before_upgrade() {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let address = listener.local_addr().unwrap();
- let server = tokio::spawn(async move {
- axum::serve(listener, crate::server::http::build_core_http_router(false))
- .await
- .unwrap();
- });
-
- let socket = tokio::net::TcpStream::connect(address).await.unwrap();
- let (read_half, mut write_half) = socket.into_split();
- let request = format!(
- "GET /ws/dictation HTTP/1.1\r\nHost: {address}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nAuthorization: Bearer {}\r\nOrigin: https://attacker.example\r\n\r\n",
- test_token()
- );
- write_half.write_all(request.as_bytes()).await.unwrap();
- let mut response = String::new();
- tokio::time::timeout(
- std::time::Duration::from_secs(5),
- BufReader::new(read_half).read_line(&mut response),
- )
- .await
- .expect("HTTP rejection completes")
- .unwrap();
- server.abort();
-
- assert!(response.starts_with("HTTP/1.1 403"), "{response}");
-}
diff --git a/crates/openhuman-rpc/src/server/http/inference_route_tests.rs b/crates/openhuman-rpc/src/server/http/inference_route_tests.rs
index 4ab9fd5735..9dedbc7d27 100644
--- a/crates/openhuman-rpc/src/server/http/inference_route_tests.rs
+++ b/crates/openhuman-rpc/src/server/http/inference_route_tests.rs
@@ -135,16 +135,3 @@ async fn test_chat_completions_with_bearer_not_rejected_as_auth_error() {
);
}
-/// Dictation WebSockets accept the browser query-token transport at the
-/// handler boundary, but still reject a token that is not the process bearer.
-#[tokio::test]
-async fn test_dictation_rejects_invalid_query_token() {
- let req = Request::builder()
- .method(Method::GET)
- .uri("/ws/dictation?token=not-the-core-token")
- .body(Body::empty())
- .unwrap();
-
- let resp = dispatch(req).await;
- assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
-}
diff --git a/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs b/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs
index 69e191869e..6145d11382 100644
--- a/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs
@@ -10,13 +10,11 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use axum::body::Body;
-use axum::extract::ws::WebSocketUpgrade;
use axum::extract::State;
use axum::http::{header, HeaderMap, Response, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{get, post};
use axum::{Json, Router};
-use futures_util::{SinkExt, StreamExt};
use openhuman_core::config::schema::cloud_providers::{
AuthStyle as CloudAuthStyle, CloudProviderCreds,
};
@@ -28,10 +26,8 @@ use openhuman_core::inference::http;
use openhuman_core::security::credentials::{
AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
};
-use openhuman_core::voice::streaming::handle_dictation_ws;
use serde_json::{json, Value};
use tempfile::{tempdir, TempDir};
-use tokio_tungstenite::tungstenite::Message as WsMessage;
#[derive(Clone, Default)]
struct MockState {
@@ -169,45 +165,6 @@ async fn http_models_and_chat_use_mocked_ollama_without_real_runtime() {
.any(|(path, body)| path == "/v1/chat/completions" && body["model"] == "bare-chat"));
}
-#[tokio::test]
-async fn dictation_ws_empty_stop_and_audio_cap_do_not_load_whisper() {
- let _env = env_lock_async().await;
- let tmp = tempdir().expect("tempdir");
- let mut config = temp_config(&tmp);
- config.dictation.streaming = false;
- config.dictation.llm_refinement = false;
-
- let ws_url = serve_dictation_ws(config).await;
-
- let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url)
- .await
- .expect("connect empty dictation ws");
- ws.send(WsMessage::Text(r#"{"type":"stop"}"#.into()))
- .await
- .expect("send stop");
- let final_msg = ws.next().await.expect("final frame").expect("final ok");
- let final_json: Value =
- serde_json::from_str(final_msg.to_text().expect("text frame")).expect("final json");
- assert_eq!(final_json["type"], "final");
- assert_eq!(final_json["text"], "");
- assert_eq!(final_json["raw_text"], "");
-
- let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url)
- .await
- .expect("connect capped dictation ws");
- ws.send(WsMessage::Binary(vec![0u8; 9_600_002].into()))
- .await
- .expect("send oversized pcm");
- let error_msg = ws.next().await.expect("error frame").expect("error ok");
- let error_json: Value =
- serde_json::from_str(error_msg.to_text().expect("text frame")).expect("error json");
- assert_eq!(error_json["type"], "error");
- assert!(error_json["message"]
- .as_str()
- .unwrap_or_default()
- .contains("Recording limit reached"));
-}
-
#[tokio::test]
async fn local_service_reports_endpoint_state_from_mocked_ollama_without_spawning() {
let _env = env_lock_async().await;
@@ -292,28 +249,6 @@ async fn serve_app(app: Router) -> String {
format!("http://{addr}")
}
-async fn serve_dictation_ws(config: Config) -> String {
- let config = Arc::new(config);
- let app = Router::new().route(
- "/ws/dictation",
- get({
- let config = config.clone();
- move |ws: WebSocketUpgrade| {
- let config = config.clone();
- async move { ws.on_upgrade(move |socket| handle_dictation_ws(socket, config)) }
- }
- }),
- );
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
- .await
- .expect("bind ws");
- let addr = listener.local_addr().expect("ws addr");
- tokio::spawn(async move {
- axum::serve(listener, app).await.expect("serve ws");
- });
- format!("ws://{addr}/ws/dictation")
-}
-
async fn ollama_chat_completions(
State(state): State<MockState>,
headers: HeaderMap,