The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed crates/openhuman-core/src/voice/cloud_transcribe.rs,crates/openhuman-core/src/v
Steven Enamakelabb53a3ccb0c
diff --git a/crates/openhuman-core/src/voice/cloud_transcribe.rs b/crates/openhuman-core/src/voice/cloud_transcribe.rsdeleted file mode 100644index 8a35ed599a..0000000000--- a/crates/openhuman-core/src/voice/cloud_transcribe.rs+++ /dev/null@@ -1,76 +0,0 @@-//! OpenHuman authentication adapter for hosted speech-to-text.--use crate::backend::BackendClient;-use crate::config::Config;-use crate::core::Outcome;--use tinyinference_voice::cloud::{CloudTranscribeOptions, CloudTranscribeResult};--/// Transcribe renderer-supplied base64 audio through the hosted backend.-pub async fn transcribe_cloud(- config: &Config,- audio_base64: &str,- options: &CloudTranscribeOptions,-) -> Result<Outcome<CloudTranscribeResult>, String> {- // The session JWT or the TinyHumans API key. The vendored client sends it- // as `Authorization: Bearer`, which the backend accepts for either.- let credential =- crate::security::credentials::session_support::resolve_backend_credential(config)?;- let is_api_key = credential.is_api_key();- let client = BackendClient::from_config(config).map_err(|error| error.to_string())?;- let url = client- .url_for("/openai/v1/audio/transcriptions")- .map_err(|error| error.to_string())?;- let safe_for_bearer =- crate::inference::provider::openhuman_backend_model::is_safe_endpoint_for_managed_bearer(- url.as_str(),- );- let managed_for_api_key =- crate::inference::provider::openhuman_backend_model::is_managed_endpoint_for_api_key(- url.as_str(),- );- if !safe_for_bearer || (is_api_key && !managed_for_api_key) {- return Err(- "refusing to send the TinyHumans API key over a non-HTTPS, non-loopback endpoint"- .to_string(),- );- }- let http = client- .raw_client()- .map_err(crate::backend::flatten_authed_error)?;- let result = tinyinference_voice::cloud::transcribe(- &http,- url,- credential.secret(),- audio_base64,- options,- )- .await- .map_err(|error| classify_transcribe_error(error, is_api_key))?;- Ok(Outcome::single_log(- result,- "cloud STT via POST /openai/v1/audio/transcriptions",- ))-}--/// Tag a backend 401 with the `SESSION_EXPIRED` sentinel. The request carries-/// the app-session JWT to the hosted backend, so a 401 here is the session-/// lapsing — the JSON-RPC layer then re-auths instead of paging Sentry with-/// the raw `transcription request failed (401 …)` string.-fn classify_transcribe_error(error: String, is_api_key: bool) -> String {- if error.starts_with("transcription request failed (401") {- if is_api_key {- log::info!("[voice][cloud_stt] backend rejected the API key (401)");- format!("API_KEY_REJECTED: {error}")- } else {- log::info!("[voice][cloud_stt] backend rejected the session (401)");- format!("SESSION_EXPIRED: {error}")- }- } else {- error- }-}--#[cfg(test)]-#[path = "cloud_transcribe_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/voice/cloud_transcribe_tests.rs b/crates/openhuman-core/src/voice/cloud_transcribe_tests.rsdeleted file mode 100644index 121ab6e89f..0000000000--- a/crates/openhuman-core/src/voice/cloud_transcribe_tests.rs+++ /dev/null@@ -1,125 +0,0 @@-use super::*;-use wiremock::matchers::{method, path};-use wiremock::{Mock, MockServer, ResponseTemplate};--#[test]-fn backend_401_is_tagged_as_session_expiry() {- let tagged = classify_transcribe_error(- "transcription request failed (401 Unauthorized): {\"error\":\"Invalid token\"}"- .to_string(),- false,- );- assert!(tagged.starts_with("SESSION_EXPIRED: "));- assert!(crate::core::observability::is_session_expired_message(- &tagged- ));-}--#[test]-fn other_failures_pass_through_unchanged() {- let error = "transcription request failed (500 Internal Server Error): boom".to_string();- assert_eq!(classify_transcribe_error(error.clone(), false), error);-}--#[test]-fn backend_401_with_api_key_does_not_expire_session() {- let tagged = classify_transcribe_error(- "transcription request failed (401 Unauthorized)".to_string(),- true,- );- assert!(tagged.starts_with("API_KEY_REJECTED: "));- assert!(!crate::core::observability::is_session_expired_message(- &tagged- ));-}--#[tokio::test]-async fn offline_local_session_refuses_without_a_request() {- let tmp = tempfile::TempDir::new().unwrap();- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- crate::security::credentials::AuthService::from_config(&config)- .store_provider_token(- crate::security::credentials::APP_SESSION_PROVIDER,- crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,- "desktop.test.local",- std::collections::HashMap::new(),- true,- )- .unwrap();- let err = transcribe_cloud(&config, "AAAA", &CloudTranscribeOptions::default())- .await- .unwrap_err();- assert!(- crate::core::observability::is_backend_unavailable_message(&err),- "{err}"- );-}--#[tokio::test]-async fn api_key_refuses_remote_plaintext_endpoint_before_request() {- let tmp = tempfile::TempDir::new().unwrap();- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- api_url: Some("http://backend.example.test".to_string()),- ..Config::default()- };- crate::security::credentials::api_key::store_api_key(&config, "test-api-key").unwrap();-- let err = transcribe_cloud(&config, "AAAA", &CloudTranscribeOptions::default())- .await- .unwrap_err();- assert!(err.contains("refusing to send"), "{err}");-}--#[tokio::test]-async fn api_key_transcribes_via_safe_backend_with_bearer_and_multipart_audio() {- let server = MockServer::start().await;- Mock::given(method("POST"))- .and(path("/openai/v1/audio/transcriptions"))- .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({- "text": "recognized words"- })))- .mount(&server)- .await;-- let tmp = tempfile::TempDir::new().unwrap();- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- api_url: Some(server.uri()),- ..Config::default()- };- crate::security::credentials::api_key::store_api_key(&config, "test-api-key").unwrap();-- let outcome = transcribe_cloud(&config, "AQID", &CloudTranscribeOptions::default())- .await- .unwrap()- .value;- assert_eq!(outcome.text, "recognized words");- let requests = server.received_requests().await.unwrap();- assert_eq!(requests.len(), 1);- let request = &requests[0];- assert_eq!(- request.headers.get("authorization").unwrap(),- "Bearer test-api-key"- );- assert!(request- .headers- .get("content-type")- .unwrap()- .to_str()- .unwrap()- .starts_with("multipart/form-data; boundary="));- assert!(request.body.windows(3).any(|bytes| bytes == [1, 2, 3]));- let body = String::from_utf8_lossy(&request.body);- assert!(body.contains("name=\"file\""));- assert!(body.contains("name=\"model\""));-}diff --git a/crates/openhuman-core/src/voice/factory/mod.rs b/crates/openhuman-core/src/voice/factory/mod.rsindex 1acfba820c..23c0da8de6 100644--- a/crates/openhuman-core/src/voice/factory/mod.rs+++ b/crates/openhuman-core/src/voice/factory/mod.rs@@ -54,9 +54,7 @@ mod tts_providers;mod tests;// Re-export the public API — exact visibility preserved from the original file.-pub use entry::{- create_stt_provider, create_tts_provider, DEFAULT_PIPER_VOICE, DEFAULT_STT_MODEL,-};+pub use entry::{create_stt_provider, create_tts_provider, DEFAULT_PIPER_VOICE, DEFAULT_STT_MODEL};pub use helpers::{effective_stt_provider, effective_tts_provider};pub use stt_providers::ExternalSttProvider;pub use traits::{SttProvider, SttResult, TtsProvider};diff --git a/crates/openhuman-core/src/voice/mod.rs b/crates/openhuman-core/src/voice/mod.rsindex 54303d55be..9673b7f7c9 100644--- a/crates/openhuman-core/src/voice/mod.rs+++ b/crates/openhuman-core/src/voice/mod.rs@@ -70,8 +70,9 @@ pub mod streaming;#[cfg(feature = "voice")]pub use factory::{- create_stt_provider, create_tts_provider, effective_stt_provider, effective_tts_provider, ExternalSttProvider, ExternalTtsProvider,- SttProvider, SttResult, TtsProvider, DEFAULT_PIPER_VOICE, DEFAULT_STT_MODEL,+ create_stt_provider, create_tts_provider, effective_stt_provider, effective_tts_provider,+ ExternalSttProvider, ExternalTtsProvider, SttProvider, SttResult, TtsProvider,+ DEFAULT_PIPER_VOICE, DEFAULT_STT_MODEL,};#[cfg(feature = "voice")]pub use ops::*;diff --git a/crates/openhuman-core/src/voice/realtime.rs b/crates/openhuman-core/src/voice/realtime.rsdeleted file mode 100644index c5128aac73..0000000000--- a/crates/openhuman-core/src/voice/realtime.rs+++ /dev/null@@ -1,143 +0,0 @@-//! Realtime voice-agent session bootstrap — mints a short-lived signed-//! WebSocket URL from the hosted backend's `/voice-agent/get-signed-url`-//! endpoint so the desktop client can open an ElevenLabs Agents-//! (Conversational AI) session directly. The provider API key stays-//! server-side; the client only ever sees the signed URL (#5399).-//!-//! Approval gate (#1339) classification: **internal** — the user's own-//! assistant listening/speaking through the user's own mic/speakers, with no-//! third-party outbound effect.--use log::debug;-use reqwest::Method;-use serde::{Deserialize, Serialize};-use serde_json::Value;--use crate::backend::BackendClient;-use crate::config::Config;-use crate::core::Outcome;--const LOG_PREFIX: &str = "[voice-realtime]";--/// A short-lived signed URL for a realtime voice-agent session plus the agent-/// it was minted for. Mirrors the backend `/voice-agent/get-signed-url` shape.-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct VoiceAgentSignedUrl {- pub signed_url: String,- pub agent_id: String,- /// Short-lived token binding this session to the signed-in user. The- /// renderer echoes it back as the ElevenLabs `userId`, which the backend- /// relay verifies — so the Custom-LLM relay never trusts a raw user id- /// (#5399). Empty only against an older backend that predates the binding.- #[serde(default)]- pub user_token: String,-}--/// Reject a plaintext backend URL for this credentialed request: the session-/// token is a bearer credential, so it must not travel over `http://` to a-/// remote host (CWE-319). Loopback stays allowed so local-backend development-/// (`http://localhost:5005`) still works.-pub(crate) fn ensure_secure_backend_url(api_url: &str) -> Result<(), String> {- let lowered = api_url.trim().to_ascii_lowercase();- if lowered.starts_with("https://") {- return Ok(());- }- let is_loopback = lowered- .strip_prefix("http://")- .map(authority_host)- .map(|host| matches!(host, "localhost" | "127.0.0.1" | "::1"))- .unwrap_or(false);- if is_loopback {- return Ok(());- }- Err(format!(- "refusing to send the session token to a non-HTTPS backend ({api_url}); \- set a https:// api_url"- ))-}--/// Extract the host from an `http://`-stripped remainder, preserving a bracketed-/// IPv6 literal. Splitting on the first `:` (as the previous impl did) turned-/// `[::1]:5005` into `"["`, so the documented IPv6 loopback backend could never-/// match. Parse the authority structurally instead: `[::1]:5005` → `::1`,-/// `127.0.0.1:5005` → `127.0.0.1`, `localhost/path` → `localhost`.-fn authority_host(rest: &str) -> &str {- // The authority ends at the first path separator.- let authority = rest.split('/').next().unwrap_or("");- if let Some(after_bracket) = authority.strip_prefix('[') {- // Bracketed IPv6 literal: the host sits between '[' and ']'.- return after_bracket.split(']').next().unwrap_or("");- }- // Otherwise the host is everything before the optional `:port`.- authority.split(':').next().unwrap_or("")-}--/// Mint a realtime voice-agent signed URL by proxying the hosted backend.-///-/// Follows the `reply_speech::synthesize_reply` auth pattern: backend credential →-/// [`BackendClient`] → `authed_json`, with `flatten_authed_error` so a-/// lapsed-session 401 classifies as `SESSION_EXPIRED` and skips Sentry rather-/// than leaking as a raw error string.-pub async fn mint_voice_agent_signed_url(- config: &Config,-) -> Result<Outcome<VoiceAgentSignedUrl>, String> {- // API key (sent as `x-api-key`) or live session JWT (sent as Bearer).- let credential =- crate::security::credentials::session_support::resolve_backend_credential(config)?;-- let api_url = crate::backend::require_base_url(&config.api_url)?;- ensure_secure_backend_url(&api_url)?;- let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;-- let raw = client- .authed_json(- &credential,- Method::GET,- "/voice-agent/get-signed-url",- None,- )- .await- .map_err(crate::backend::flatten_authed_error)?;-- let result = parse_signed_url_response(&raw)?;- debug!("{LOG_PREFIX} minted signed url agent={}", result.agent_id);- Ok(Outcome::single_log(- result,- "voice agent signed url minted via GET /voice-agent/get-signed-url",- ))-}--/// Translate the backend's `{ success, data: { signedUrl, agentId } }` envelope-/// (or a bare object) into the UI contract. Kept separate so the parsing is-/// unit-testable without a live backend.-fn parse_signed_url_response(raw: &Value) -> Result<VoiceAgentSignedUrl, String> {- let data = raw.get("data").unwrap_or(raw);- let signed_url = data- .get("signedUrl")- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();- let agent_id = data- .get("agentId")- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();- let user_token = data- .get("userToken")- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();-- if signed_url.is_empty() {- return Err("backend returned no signed_url for the voice agent".to_string());- }- Ok(VoiceAgentSignedUrl {- signed_url,- agent_id,- user_token,- })-}--#[cfg(test)]-#[path = "realtime_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/voice/realtime_tests.rs b/crates/openhuman-core/src/voice/realtime_tests.rsdeleted file mode 100644index 7c9447c72a..0000000000--- a/crates/openhuman-core/src/voice/realtime_tests.rs+++ /dev/null@@ -1,115 +0,0 @@-use super::*;-use serde_json::json;--#[test]-fn parses_the_wrapped_success_envelope() {- let raw = json!({ "success": true, "data": { "signedUrl": "wss://x", "agentId": "a1", "userToken": "tok" } });- let out = parse_signed_url_response(&raw).unwrap();- assert_eq!(out.signed_url, "wss://x");- assert_eq!(out.agent_id, "a1");- assert_eq!(out.user_token, "tok");-}--#[test]-fn tolerates_a_bare_object() {- let raw = json!({ "signedUrl": "wss://y", "agentId": "a2" });- let out = parse_signed_url_response(&raw).unwrap();- assert_eq!(out.signed_url, "wss://y");- assert_eq!(out.agent_id, "a2");-}--#[test]-fn user_token_defaults_empty_against_an_older_backend() {- let raw = json!({ "data": { "signedUrl": "wss://y", "agentId": "a2" } });- let out = parse_signed_url_response(&raw).unwrap();- assert_eq!(out.user_token, "");-}--#[test]-fn secure_url_guard_allows_https_and_loopback_http_only() {- assert!(ensure_secure_backend_url("https://api.tinyhumans.ai").is_ok());- assert!(ensure_secure_backend_url("http://localhost:5005").is_ok());- assert!(ensure_secure_backend_url("http://127.0.0.1:5005/").is_ok());- let err = ensure_secure_backend_url("http://api.tinyhumans.ai").unwrap_err();- assert!(err.contains("non-HTTPS"), "{err}");-}--#[test]-fn secure_url_guard_allows_ipv6_loopback() {- // Bracketed IPv6 loopback must be accepted — the previous first-`:`- // split turned `[::1]:5005` into `"["` and wrongly rejected it.- assert!(ensure_secure_backend_url("http://[::1]:5005").is_ok());- assert!(ensure_secure_backend_url("http://[::1]:5005/").is_ok());- assert!(ensure_secure_backend_url("http://[::1]").is_ok());- // A non-loopback bracketed IPv6 host is still rejected over http://.- let err = ensure_secure_backend_url("http://[2001:db8::1]:5005").unwrap_err();- assert!(err.contains("non-HTTPS"), "{err}");-}--#[test]-fn errors_when_signed_url_is_absent() {- let raw = json!({ "data": { "agentId": "a3" } });- let err = parse_signed_url_response(&raw).unwrap_err();- assert!(err.contains("no signed_url"), "{err}");-}--#[test]-fn result_serializes_snake_case_for_the_wire() {- let json = serde_json::to_value(VoiceAgentSignedUrl {- signed_url: "wss://z".into(),- agent_id: "a4".into(),- user_token: "tok".into(),- })- .unwrap();- assert_eq!(json.get("signed_url").unwrap(), "wss://z");- assert_eq!(json.get("agent_id").unwrap(), "a4");- assert_eq!(json.get("user_token").unwrap(), "tok");-}--/// A runtime holding only a TinyHumans API key (no session) can mint a-/// realtime voice-agent URL; the key rides `x-api-key`, never `Authorization`.-#[tokio::test]-async fn mint_signed_url_authenticates_with_the_api_key() {- use axum::{http::HeaderMap, routing::get, Json, Router};- use std::sync::{Arc, Mutex};-- type SeenHeaders = Option<(Option<String>, Option<String>)>;- let seen: Arc<Mutex<SeenHeaders>> = Arc::default();- let app = Router::new().route(- "/voice-agent/get-signed-url",- get({- let seen = Arc::clone(&seen);- move |headers: HeaderMap| async move {- let header = |name: &str| {- headers- .get(name)- .and_then(|v| v.to_str().ok())- .map(str::to_owned)- };- *seen.lock().unwrap() = Some((header("x-api-key"), header("authorization")));- Json(json!({- "success": true,- "data": { "signedUrl": "wss://voice", "agentId": "a1", "userToken": "u" }- }))- }- }),- );- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });-- let dir = tempfile::tempdir().unwrap();- let mut config = Config::default();- config.workspace_dir = dir.path().join("workspace");- config.config_path = dir.path().join("config.toml");- config.api_url = Some(format!("http://{addr}"));- crate::security::credentials::api_key::store_api_key(&config, "tiny_test_voice").unwrap();-- let out = mint_voice_agent_signed_url(&config)- .await- .expect("an API key alone mints a voice-agent URL");- assert_eq!(out.value.signed_url, "wss://voice");- let (api_key, authorization) = seen.lock().unwrap().clone().expect("request reached mock");- assert_eq!(api_key.as_deref(), Some("tiny_test_voice"));- assert_eq!(authorization, None);-}diff --git a/crates/openhuman-core/src/voice/reply_speech.rs b/crates/openhuman-core/src/voice/reply_speech.rsdeleted file mode 100644index f9d640066a..0000000000--- a/crates/openhuman-core/src/voice/reply_speech.rs+++ /dev/null@@ -1,212 +0,0 @@-//! Reply-speech synthesis — proxies the hosted backend's-//! `/openai/v1/audio/speech` endpoint (ElevenLabs under the hood) so the-//! desktop UI does not have to talk to it directly. Returns base64-encoded-//! audio + an Oculus-15 viseme alignment timeline the mascot uses for-//! lip-sync.-//!-//! Lives in the voice domain because the response is consumed by the-//! mascot's lipsync pipeline (`useHumanMascot` → `findActiveFrame` →-//! `oculusVisemeToShape`).-//!-//! Approval gate (#1339) classification: **internal**. Reply-speech is-//! the user's own assistant speaking through the user's own speakers-//! — there is no outbound side effect visible to a third party.-//! Coordinate with #1206 voice work: if `reply_speech` is ever wrapped-//! in a `Tool` impl, the `external_effect()` method MUST stay `false`-//! (the trait's default) so the approval gate never prompts on TTS.--use log::{debug, warn};-use reqwest::Method;-use serde_json::{json, Value};--use crate::backend::BackendClient;-use crate::config::Config;-use crate::core::Outcome;--const LOG_PREFIX: &str = "[voice_reply]";--/// Env var that activates the [`test_seam`] short-circuit at runtime. When-/// set to `1` / `true`, [`synthesize_reply`] records the requested text-/// into [`test_seam::OBSERVED_CALLS`] and returns a stub-/// [`ReplySpeechResult`] *without* contacting the hosted backend. Anything-/// else (unset, `0`, `false`, …) leaves the production code path-/// untouched.-///-/// The env-var gate (rather than a `#[cfg(test)]` gate) is deliberate:-/// integration tests in `tests/` are compiled against the production-/// `openhuman_core` crate, so a unit-only `cfg(test)` block would not be-/// visible from there. The observer module itself is always compiled,-/// but its only producer is this env-gated branch and its only consumer-/// is the test harness, so production callers never touch it.-pub const TEST_SEAM_ENV: &str = "OPENHUMAN_TEST_REPLY_SPEECH_SEAM";--fn test_seam_enabled() -> bool {- matches!(- std::env::var(TEST_SEAM_ENV).ok().as_deref(),- Some("1") | Some("true") | Some("TRUE")- )-}--/// Test seam observation log. See [`TEST_SEAM_ENV`] for the activation-/// gate. Always compiled (the visibility lets `tests/json_rpc_e2e.rs`-/// inspect calls), but only written to when the env gate is on.-pub mod test_seam {- use once_cell::sync::Lazy;- use std::sync::Mutex;-- /// FIFO log of every `text` argument that flowed through the test-seam- /// short-circuit in [`super::synthesize_reply`]. Cleared between tests- /// with [`clear`].- pub static OBSERVED_CALLS: Lazy<Mutex<Vec<String>>> = Lazy::new(|| Mutex::new(Vec::new()));-- /// Clear the observation log.- pub fn clear() {- OBSERVED_CALLS.lock().unwrap().clear();- }-- /// Snapshot of the observation log.- pub fn observed() -> Vec<String> {- OBSERVED_CALLS.lock().unwrap().clone()- }-}--// The response types and the tolerant-shape parsers live in-// `tinyinference_voice::reply`; the UI contract is unchanged.-use tinyinference_voice::reply::{normalize_response, ReplySpeech as ReplySpeechResult};--/// Caller-tunable knobs.-#[derive(Debug, Default, Clone)]-pub struct ReplySpeechOptions {- pub voice_id: Option<String>,- pub model_id: Option<String>,- pub output_format: Option<String>,- /// ElevenLabs `voice_settings` blob — passed through verbatim.- /// Typical fields: `stability`, `similarity_boost`, `style`,- /// `use_speaker_boost`. The backend forwards this to ElevenLabs;- /// unknown keys are dropped server-side.- pub voice_settings: Option<Value>,-}--/// Synthesize the agent's reply through the hosted backend.-///-/// Uses [`BackendClient`] for the same reason `referral` does: the-/// desktop WebView's `fetch` to the backend can fail with an opaque-/// "Load failed" (CORS/TLS quirks), and routing through the core gives us-/// a consistent auth + retry surface.-pub async fn synthesize_reply(- config: &Config,- text: &str,- opts: &ReplySpeechOptions,-) -> Result<Outcome<ReplySpeechResult>, String> {- let trimmed = text.trim();- if trimmed.is_empty() {- return Err("text is required".to_string());- }-- // Test seam: when OPENHUMAN_TEST_REPLY_SPEECH_SEAM is set (and only in- // debug builds — the seam is structurally dead in release), record the- // call and short-circuit before hitting the backend.- // See `test_seam` module docs and `TEST_SEAM_ENV` for the activation gate.- if cfg!(debug_assertions) && test_seam_enabled() {- warn!(- "[voice_reply] TEST SEAM ACTIVE — synthesize_reply short-circuited ({} is set); skipping backend call",- TEST_SEAM_ENV- );- let _ = (config, opts);- test_seam::OBSERVED_CALLS- .lock()- .unwrap()- .push(trimmed.to_string());- return Ok(Outcome::single_log(- ReplySpeechResult {- audio_base64: String::new(),- audio_mime: "audio/mpeg".to_string(),- visemes: Vec::new(),- alignment: None,- },- "voice reply synthesized (test seam short-circuit)",- ));- }-- // API key (sent as `x-api-key`) or live session JWT (sent as Bearer).- let credential =- crate::security::credentials::session_support::resolve_backend_credential(config)?;-- let api_url = crate::backend::require_base_url(&config.api_url)?;- let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;-- let mut body = serde_json::Map::new();- body.insert("text".to_string(), json!(trimmed));- body.insert("with_visemes".to_string(), json!(true));- if let Some(v) = opts- .voice_id- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty())- {- body.insert("voice_id".to_string(), json!(v));- }- if let Some(v) = opts- .model_id- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty())- {- body.insert("model_id".to_string(), json!(v));- }- if let Some(v) = opts- .output_format- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty())- {- body.insert("output_format".to_string(), json!(v));- }- if let Some(settings) = opts.voice_settings.as_ref() {- if !settings.is_null() {- body.insert("voice_settings".to_string(), settings.clone());- }- }-- debug!(- "{LOG_PREFIX} synthesize chars={} voice={}",- trimmed.len(),- opts.voice_id.as_deref().unwrap_or("default")- );-- // `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`- // (expected session-lapse 401 from `authed_json`) onto the `SESSION_EXPIRED`- // sentinel so the JSON-RPC layer (`core/jsonrpc.rs::is_session_expired_error`)- // classifies it as session expiry and skips Sentry, matching the #3384- // team/billing pattern. The previous `e.to_string()` produced the raw- // "backend rejected session token on POST /openai/v1/audio/speech" Display- // string, which matched none of the session-expiry classifiers and leaked- // every lapsed-session TTS 401 to Sentry (TAURI-RUST-8X1). Every other error- // keeps its full `{e:#}` anyhow chain so genuine TTS failures still report.- let raw = client- .authed_json(- &credential,- Method::POST,- "/openai/v1/audio/speech",- Some(Value::Object(body)),- )- .await- .map_err(crate::backend::flatten_authed_error)?;-- let result = normalize_response(&raw);- debug!(- "{LOG_PREFIX} synthesized audio_bytes={} visemes={} alignment={}",- result.audio_base64.len(),- result.visemes.len(),- result.alignment.as_ref().map_or(0, Vec::len)- );-- Ok(Outcome::single_log(- result,- "voice reply synthesized via POST /openai/v1/audio/speech",- ))-}--#[cfg(test)]-#[path = "reply_speech_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/voice/reply_speech_tests.rs b/crates/openhuman-core/src/voice/reply_speech_tests.rsdeleted file mode 100644index ba951c5f2e..0000000000--- a/crates/openhuman-core/src/voice/reply_speech_tests.rs+++ /dev/null@@ -1,58 +0,0 @@-#[test]-fn tts_unauthorized_flattens_to_session_expiry_not_hard_error() {- // TAURI-RUST-8X1: a lapsed-session 401 on the TTS endpoint- // (`POST /openai/v1/audio/speech`) used to be flattened with- // `e.to_string()`, producing the raw "backend rejected session token …"- // Display string that matched none of the session-expiry classifiers and- // leaked to Sentry as a hard error. `synthesize_reply` now flattens the- // typed `BackendApiError::Unauthorized` via `crate::backend::flatten_authed_error`- // (the #3384 team/billing pattern), so it carries the SESSION_EXPIRED- // sentinel and is recognised + demoted by the JSON-RPC dispatcher.- //- // This test couples the exact TTS endpoint's typed 401 to the live- // classifier: build the typed error → flatten → classify. If either the- // sentinel mapping or the classifier drifts, this fails instead of- // silently re-leaking the TTS 401.- let flat = crate::backend::flatten_authed_error(anyhow::Error::new(- crate::backend::BackendApiError::Unauthorized {- method: "POST".to_string(),- path: "/openai/v1/audio/speech".to_string(),- },- ));-- assert!(- flat.contains("SESSION_EXPIRED"),- "flattened TTS 401 must carry the sentinel, got: {flat}"- );- assert!(- flat.contains("/openai/v1/audio/speech"),- "path preserved for logs: {flat}"- );- assert!(- crate::core::observability::is_session_expired_message(&flat),- "flattened TTS Unauthorized must classify as session expiry (demoted, \- not a hard error): {flat}"- );-}--#[test]-fn tts_non_auth_error_is_not_demoted_to_session_expiry() {- // A genuine TTS failure (timeout, 5xx, …) must keep its full anyhow chain- // and NOT be demoted — real backend/TTS breakage must still reach Sentry.- let flat = crate::backend::flatten_authed_error(- anyhow::anyhow!("connect timeout").context("backend request POST /openai/v1/audio/speech"),- );-- assert!(- !flat.contains("SESSION_EXPIRED"),- "non-auth TTS error must not be demoted: {flat}"- );- assert!(- flat.contains("connect timeout"),- "underlying cause preserved: {flat}"- );- assert!(- !crate::core::observability::is_session_expired_message(&flat),- "non-auth TTS error must NOT classify as session expiry: {flat}"- );-}diff --git a/crates/openhuman-core/src/voice/stub.rs b/crates/openhuman-core/src/voice/stub.rsindex 58fdad2dc1..04ef8650b8 100644--- a/crates/openhuman-core/src/voice/stub.rs+++ b/crates/openhuman-core/src/voice/stub.rs@@ -231,96 +231,3 @@ pub mod live {}}}--// ----------------------------------------------------------------------------// reply_speech::{synthesize_reply, ReplySpeechOptions, ReplySpeechResult, ...}-// -----------------------------------------------------------------------------pub mod reply_speech {- use serde::{Deserialize, Serialize};- use serde_json::Value;-- use crate::config::Config;- use crate::core::Outcome;-- /// One frame on the viseme timeline. Mirrors the real type.- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]- pub struct VisemeFrame {- pub viseme: String,- pub start_ms: u64,- pub end_ms: u64,- }-- /// Char-level timing frame. Mirrors the real type.- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]- pub struct AlignmentFrame {- pub char: String,- pub start_ms: u64,- pub end_ms: u64,- }-- /// Normalized TTS response. Mirrors the real type.- #[derive(Debug, Clone, Serialize, Deserialize)]- pub struct ReplySpeechResult {- pub audio_base64: String,- pub audio_mime: String,- pub visemes: Vec<VisemeFrame>,- #[serde(skip_serializing_if = "Option::is_none")]- pub alignment: Option<Vec<AlignmentFrame>>,- }-- /// Caller-tunable knobs. Mirrors the real type (fields + `Default`).- #[derive(Debug, Default, Clone)]- pub struct ReplySpeechOptions {- pub voice_id: Option<String>,- pub model_id: Option<String>,- pub output_format: Option<String>,- pub voice_settings: Option<Value>,- }-- /// Disabled: reply-speech synthesis is unavailable when voice is compiled- /// out. Callers log the error and skip the spoken reply.- pub async fn synthesize_reply(- _config: &Config,- _text: &str,- _opts: &ReplySpeechOptions,- ) -> Result<Outcome<ReplySpeechResult>, String> {- Err(super::DISABLED_MSG.to_string())- }-}--// ----------------------------------------------------------------------------// cloud_transcribe::{transcribe_cloud, CloudTranscribeOptions, ...}-// (provided by the real voice host adapter)-// -----------------------------------------------------------------------------pub mod cloud_transcribe {- use serde::{Deserialize, Serialize};-- use crate::config::Config;- use crate::core::Outcome;-- /// Caller-tunable knobs. Mirrors the real type (fields + `Default`).- #[derive(Debug, Default, Clone)]- pub struct CloudTranscribeOptions {- pub model: Option<String>,- pub language: Option<String>,- pub mime_type: Option<String>,- pub file_name: Option<String>,- }-- /// Transcription result. Mirrors the real type.- #[derive(Debug, Clone, Serialize, Deserialize)]- pub struct CloudTranscribeResult {- pub text: String,- }-- /// Disabled: cloud STT is unavailable when voice is compiled out.- pub async fn transcribe_cloud(- _config: &Config,- _audio_base64: &str,- _opts: &CloudTranscribeOptions,- ) -> Result<Outcome<CloudTranscribeResult>, String> {- Err(super::DISABLED_MSG.to_string())- }-}