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
refactor(channels): route progressive delivery only through the registered callback
Steven Enamakel33ec60744cfc
diff --git a/crates/openhuman-core/src/channels/bus/delivery.rs b/crates/openhuman-core/src/channels/bus/delivery.rsindex ebb4b94afe..f547d05ca7 100644--- a/crates/openhuman-core/src/channels/bus/delivery.rs+++ b/crates/openhuman-core/src/channels/bus/delivery.rs@@ -1,10 +1,6 @@-//! Captured managed transport for module-owned progressive replies.-use crate::backend::{BackendApiError, BackendClient};+//! Transport for module-owned progressive replies: delivery goes through the+//! registered channel callback (`channels::callback_slot`).use crate::modules::channel_runtime::ChannelRuntimeLease;-use crate::security::credentials::session_support::{- get_session_token, is_local_session_token, BackendCredential,-};-use serde_json::json;#[cfg(test)]use serde_json::Value;use tinybus::module::ModuleCallError;@@ -14,102 +10,6 @@ use tinychannels_bus::module_progressive::{};use tinychannels_bus::{methods, ChannelBackendRequest, ChannelBackendResult};-/// Transport refusals are typed facts; recovery and retry budgets belong to the module.-pub(super) fn map_backend_error(error: anyhow::Error) -> ProgressiveTransportResult {- match error.downcast_ref::<BackendApiError>() {- Some(BackendApiError::ChannelEditUnsupported { .. }) => {- ProgressiveTransportResult::EditUnsupported- }- Some(BackendApiError::MessageNotFound { .. }) => ProgressiveTransportResult::MessageGone,- _ => ProgressiveTransportResult::Failed,- }-}--#[derive(Clone)]-struct ManagedTransport {- client: BackendClient,- credential: BackendCredential,- channel: String,- session: tokio_util::sync::CancellationToken,-}--impl ManagedTransport {- fn capture(- config: &crate::config::Config,- channel: String,- session: tokio_util::sync::CancellationToken,- ) -> anyhow::Result<Self> {- anyhow::ensure!(!session.is_cancelled(), "Channel session closed");- let credential = match get_session_token(config)- .map_err(|_| anyhow::anyhow!("Hosted channel credential unavailable"))?- {- Some(token) if !is_local_session_token(&token) => BackendCredential::Session(token),- _ => anyhow::bail!("Hosted channel credential unavailable"),- };- Ok(Self {- client: BackendClient::from_config(config)?,- credential,- channel,- session,- })- }-- async fn execute(&self, request: ProgressiveTransportRequest) -> ProgressiveTransportResult {- if request_channel(&request) != self.channel {- return ProgressiveTransportResult::Failed;- }- tokio::select! {- biased;- _ = self.session.cancelled() => ProgressiveTransportResult::Unavailable,- result = self.execute_transport(request) => result,- }- }-- async fn execute_transport(- &self,- request: ProgressiveTransportRequest,- ) -> ProgressiveTransportResult {- let result = match request {- ProgressiveTransportRequest::Send { channel, message } => {- self.client- .send_channel_message(&channel, &self.credential, message)- .await- }- ProgressiveTransportRequest::Edit {- channel,- message_id,- text,- } => {- self.client- .send_channel_edit(- &channel,- &message_id,- &self.credential,- json!({"text":text}),- )- .await- }- ProgressiveTransportRequest::Delete {- channel,- message_id,- } => {- self.client- .send_channel_delete(&channel, &message_id, &self.credential)- .await- }- ProgressiveTransportRequest::Typing { channel } => {- self.client- .send_channel_typing(&channel, &self.credential)- .await- }- };- match result {- Ok(value) => ProgressiveTransportResult::Success(value),- Err(error) => map_backend_error(error),- }- }-}-fn request_channel(request: &ProgressiveTransportRequest) -> &str {match request {ProgressiveTransportRequest::Send { channel, .. }@@ -119,24 +19,10 @@ fn request_channel(request: &ProgressiveTransportRequest) -> &str {}}-#[tinybus::interface(name = "ai.tinyhumans.tinychannels.ChannelsHost")]-impl ManagedTransport {- async fn dispatch_controller_backend(- &self,- request: ChannelBackendRequest,- ) -> tinybus::Result<ChannelBackendResult> {- let ChannelBackendRequest::ProgressiveTransport(request) = request else {- return Err(tinybus::Error::failed("callback capability unavailable"));- };- Ok(ChannelBackendResult::ProgressiveTransport(- self.execute(request).await,- ))- }-}--/// The callback a registered channel callback-/// ([`crate::channels::callback_slot`]) serves progressive delivery through,-/// in place of [`ManagedTransport`].+/// The transport progressive delivery runs through: a registered channel+/// callback ([`crate::channels::callback_slot`]). Transport refusals are typed+/// facts the callback maps itself; recovery and retry budgets belong to the+/// module.#[derive(Clone)]struct SlotTransport {callback: crate::channels::callback_slot::ChannelCallback,@@ -175,7 +61,7 @@ impl SlotTransport {Err(error) => {tracing::debug!(%error, "[channels][delivery] registered callback failed");Ok(ChannelBackendResult::ProgressiveTransport(- map_backend_error(error),+ ProgressiveTransportResult::Failed,))}},@@ -195,21 +81,22 @@ impl ModuleProgressiveReply {channel: String,session: tokio_util::sync::CancellationToken,) -> anyhow::Result<Self> {- if let Some(callback) = crate::channels::callback_slot::current() {- tracing::debug!(- "[channels][delivery] progressive delivery via the registered callback"+ let Some(callback) = crate::channels::callback_slot::current() else {+ tracing::debug!("[channels][delivery] no channel callback registered");+ anyhow::bail!(+ "{} no channel transport registered",+ crate::core::observability::BACKEND_UNAVAILABLE_PREFIX);- anyhow::ensure!(!session.is_cancelled(), "Channel session closed");- let transport = SlotTransport {- callback,- config: config.clone(),- channel: channel.clone(),- session,- };- return Self::open_with(config, channel, transport).await;- }- let callback = ManagedTransport::capture(&config, channel.clone(), session)?;- Self::open_with(config, channel, callback).await+ };+ tracing::debug!("[channels][delivery] progressive delivery via the registered callback");+ anyhow::ensure!(!session.is_cancelled(), "Channel session closed");+ let transport = SlotTransport {+ callback,+ config: config.clone(),+ channel: channel.clone(),+ session,+ };+ Self::open_with(config, channel, transport).await}async fn open_with(diff --git a/crates/openhuman-tinyhumans/src/voice/cloud_transcribe.rs b/crates/openhuman-tinyhumans/src/voice/cloud_transcribe.rsnew file mode 100644index 0000000000..878263cf95--- /dev/null+++ b/crates/openhuman-tinyhumans/src/voice/cloud_transcribe.rs@@ -0,0 +1,77 @@+//! OpenHuman authentication adapter for hosted speech-to-text.++use openhuman_embed::__host::config::Config;+use openhuman_embed::__host::core::Outcome;+use openhuman_embed::__host::security::credentials::session_support::resolve_backend_credential;++use crate::client::{+ flatten_authed_error, is_managed_endpoint_for_api_key, is_safe_endpoint_for_managed_bearer,+ BackendClient,+};++use tinyinference_voice::cloud::{CloudTranscribeOptions, CloudTranscribeResult};++/// The route this module posts to.+const TRANSCRIPTIONS_PATH: &str = "/openai/v1/audio/transcriptions";++/// 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 = 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(TRANSCRIPTIONS_PATH)+ .map_err(|error| error.to_string())?;+ let safe_for_bearer = is_safe_endpoint_for_managed_bearer(url.as_str());+ let managed_for_api_key = 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(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-tinyhumans/src/voice/cloud_transcribe_tests.rs b/crates/openhuman-tinyhumans/src/voice/cloud_transcribe_tests.rsnew file mode 100644index 0000000000..121ab6e89f--- /dev/null+++ b/crates/openhuman-tinyhumans/src/voice/cloud_transcribe_tests.rs@@ -0,0 +1,125 @@+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-tinyhumans/src/voice/realtime.rs b/crates/openhuman-tinyhumans/src/voice/realtime.rsnew file mode 100644index 0000000000..19c0bea744--- /dev/null+++ b/crates/openhuman-tinyhumans/src/voice/realtime.rs@@ -0,0 +1,143 @@+//! 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 openhuman_embed::__host::config::Config;+use openhuman_embed::__host::core::Outcome;+use openhuman_embed::__host::security::credentials::session_support::resolve_backend_credential;++use crate::client::{flatten_authed_error, BackendClient};++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 = resolve_backend_credential(config)?;++ let client = BackendClient::from_config(config).map_err(|e| e.to_string())?;+ ensure_secure_backend_url(client.base_url())?;++ let raw = client+ .authed_json(+ &credential,+ Method::GET,+ "/voice-agent/get-signed-url",+ None,+ )+ .await+ .map_err(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-tinyhumans/src/voice/realtime_tests.rs b/crates/openhuman-tinyhumans/src/voice/realtime_tests.rsnew file mode 100644index 0000000000..7c9447c72a--- /dev/null+++ b/crates/openhuman-tinyhumans/src/voice/realtime_tests.rs@@ -0,0 +1,115 @@+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-tinyhumans/src/voice/reply_speech.rs b/crates/openhuman-tinyhumans/src/voice/reply_speech.rsnew file mode 100644index 0000000000..d3d60a6e5f--- /dev/null+++ b/crates/openhuman-tinyhumans/src/voice/reply_speech.rs@@ -0,0 +1,214 @@+//! 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 openhuman_embed::__host::config::Config;+use openhuman_embed::__host::core::Outcome;+use openhuman_embed::__host::security::credentials::session_support::resolve_backend_credential;++use crate::client::{flatten_authed_error, BackendClient};++const LOG_PREFIX: &str = "[voice_reply]";++/// The route this module posts to.+const SPEECH_PATH: &str = "/openai/v1/audio/speech";++/// 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 = resolve_backend_credential(config)?;+ let client = BackendClient::from_config(config).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,+ SPEECH_PATH,+ Some(Value::Object(body)),+ )+ .await+ .map_err(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-tinyhumans/src/voice/reply_speech_tests.rs b/crates/openhuman-tinyhumans/src/voice/reply_speech_tests.rsnew file mode 100644index 0000000000..ba951c5f2e--- /dev/null+++ b/crates/openhuman-tinyhumans/src/voice/reply_speech_tests.rs@@ -0,0 +1,58 @@+#[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}"+ );+}