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
fix(voice): correct schema handler wiring and memory test expectations
Steven Enamakel2961d7a22bc5
diff --git a/crates/openhuman-core/src/memory/engine_tests.rs b/crates/openhuman-core/src/memory/engine_tests.rsindex e4de716b10..c2f8712622 100644--- a/crates/openhuman-core/src/memory/engine_tests.rs+++ b/crates/openhuman-core/src/memory/engine_tests.rs@@ -12,16 +12,10 @@ fn off_reason(binding: Binding) -> String {}#[test]-fn tinyhumans_without_a_credential_is_off() {+fn tinyhumans_with_nothing_registered_is_unavailable() {let tmp = tempfile::tempdir().unwrap();let mut config = config_in(&tmp);config.memory.engine = TINYHUMANS_ENGINE.to_string();- config- .memory- .engines- .entry(TINYHUMANS_ENGINE.to_string())- .or_default()- .endpoint = Some("https://memory.example.test".to_string());let binding = resolve(&config);assert!(!binding.is_on());assert!(!is_on(&config));@@ -30,7 +24,7 @@ fn tinyhumans_without_a_credential_is_off() {engine, endpoint, ..} => {assert_eq!(engine.as_deref(), Some(TINYHUMANS_ENGINE));- assert_eq!(endpoint.as_deref(), Some("https://memory.example.test"));+ assert_eq!(endpoint, None);}Binding::On(_) => unreachable!(),}@@ -39,16 +33,9 @@ fn tinyhumans_without_a_credential_is_off() {}#[test]-fn tinyhumans_with_a_local_session_token_is_off() {+fn a_local_session_token_is_not_a_tinyhumans_credential() {let tmp = tempfile::tempdir().unwrap();- let mut config = config_in(&tmp);- config.memory.engine = TINYHUMANS_ENGINE.to_string();- config- .memory- .engines- .entry(TINYHUMANS_ENGINE.to_string())- .or_default()- .endpoint = Some("https://memory.example.test".to_string());+ let config = config_in(&tmp);AuthService::from_config(&config).store_provider_token(APP_SESSION_PROVIDER,@@ -58,38 +45,7 @@ fn tinyhumans_with_a_local_session_token_is_off() {true,).unwrap();-- let binding = resolve(&config);-- assert!(!binding.is_on());assert!(!has_key(&config, TINYHUMANS_ENGINE));- assert!(off_reason(binding).contains("sign in"));-}--#[test]-fn tinyhumans_with_the_host_credential_binds_and_caches() {- let _stable = CACHE_STABLE- .write()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let tmp = tempfile::tempdir().unwrap();- let mut config = config_in(&tmp);- config- .memory- .engines- .entry(TINYHUMANS_ENGINE.to_string())- .or_default()- .endpoint = Some("https://memory.example.test".to_string());- store_api_key(&config, "test-api-key-not-real").unwrap();- assert!(has_key(&config, TINYHUMANS_ENGINE));-- let first = resolve(&config).engine().expect("bound");- assert_eq!(first.id, TINYHUMANS_ENGINE);- assert_eq!(first.endpoint, "https://memory.example.test");- let second = resolve(&config).engine().expect("bound again");- assert!(- Arc::ptr_eq(&first.engine, &second.engine),- "cached engine reused"- );}#[test]@@ -179,42 +135,6 @@ fn the_cache_fingerprint_never_contains_the_key() {assert_ne!(digest, key_digest("another-key"));}-#[tokio::test]-async fn host_bearer_reads_the_credential_per_request() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- let source = HostBearer {- config: Arc::new(config.clone()),- };- let error = source.bearer().await.unwrap_err();- assert!(matches!(error, tinymemory_api::Error::Unauthorized(_)));-- store_api_key(&config, "test-api-key-not-real").unwrap();- assert_eq!(source.bearer().await.unwrap(), "test-api-key-not-real");-}--#[tokio::test]-async fn host_bearer_rejects_a_local_session_token() {- let tmp = tempfile::tempdir().unwrap();- let config = config_in(&tmp);- AuthService::from_config(&config)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "desktop.test.local",- std::collections::HashMap::new(),- true,- )- .unwrap();- let source = HostBearer {- config: Arc::new(config),- };-- let error = source.bearer().await.unwrap_err();-- assert!(matches!(error, tinymemory_api::Error::Unauthorized(_)));-}-#[test]fn an_installed_test_engine_wins_and_is_reported_on() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/openhuman-core/src/voice/live/providers.rs b/crates/openhuman-core/src/voice/live/providers.rsindex 75effcae1e..7804cf9bed 100644--- a/crates/openhuman-core/src/voice/live/providers.rs+++ b/crates/openhuman-core/src/voice/live/providers.rs@@ -1,44 +1,38 @@//! Live provider catalogue, configuration and connection preparation.//!-//! Four providers, two of them hosted by the TinyHumans backend:+//! Two built-in providers, both bring-your-own-key://!//! | id | reached through | credential |//! | --- | --- | --- |-//! | `gemini-hosted` | backend Gemini Live relay ticket | the backend credential |-//! | `elevenlabs-hosted` | backend-signed ElevenLabs agent URL | the backend credential |//! | `gemini` | Google directly | `provider:google` |//! | `sarvam` | Sarvam directly | `provider:sarvam` |//!-//! Minting tickets and signed URLs happens here, against the backend, because-//! `tinyliveagents` deliberately holds no backend or credential code.--use reqwest::Method;-use serde_json::{json, Value};-use tinyagents_live::tinyliveagents::elevenlabs::ElevenLabsConvai;-use tinyagents_live::tinyliveagents::gemini::{self, GeminiLive, GeminiRelay};+//! Hosted providers (`gemini-hosted`, `elevenlabs-hosted`) are not built in:+//! the hosted-backend layer registers them through [`super::registry`], where+//! they mint tickets and signed URLs against the backend, because+//! `tinyliveagents` deliberately holds no backend or credential code. With none+//! registered those ids resolve to an "unknown live provider" error.++use serde_json::json;+use tinyagents_live::tinyliveagents::gemini::GeminiLive;use tinyagents_live::tinyliveagents::sarvam::SarvamCascade;use tinyagents_live::tinyliveagents::{AudioFormat, LiveConfig, LiveProvider};use super::error::LiveVoiceError;use super::types::{LiveProviderInfo, LiveProviderKind};-use crate::backend::BackendClient;use crate::config::schema::voice_live::{- LIVE_PROVIDERS, LIVE_PROVIDER_ELEVENLABS_HOSTED, LIVE_PROVIDER_GEMINI,- LIVE_PROVIDER_GEMINI_HOSTED, LIVE_PROVIDER_SARVAM,+ LIVE_PROVIDERS, LIVE_PROVIDER_GEMINI, LIVE_PROVIDER_SARVAM,};use crate::config::Config;const LOG_PREFIX: &str = "[voice-live]";-/// The backend route that mints a Gemini Live relay ticket.-pub(crate) const GEMINI_LIVE_SESSIONS_PATH: &str = "/agent-integrations/gemini/live/sessions";-/// Gemini Live prebuilt voices.-const GEMINI_VOICES: &[&str] = &[+pub const GEMINI_VOICES: &[&str] = &["Puck", "Charon", "Kore", "Fenrir", "Aoede", "Leda", "Orus", "Zephyr",];/// Languages Gemini Live speaks well (it understands more).-const GEMINI_LANGUAGES: &[&str] = &[+pub const GEMINI_LANGUAGES: &[&str] = &["en-US", "en-IN", "en-GB", "hi-IN", "es-US", "es-ES", "fr-FR", "de-DE", "it-IT", "pt-BR","ja-JP", "ko-KR", "cmn-CN", "ar-XA", "id-ID", "ru-RU", "pl-PL", "bn-IN",];@@ -69,41 +63,24 @@ pub(crate) fn stored_key(slug: &str, config: &Config) -> Option<String> {.filter(|key| !key.trim().is_empty())}-/// Whether a backend credential is available for hosted providers.-fn backend_ready(config: &Config) -> bool {- crate::security::credentials::session_support::resolve_backend_credential(config).is_ok()-}-fn strings(items: &[&str]) -> Vec<String> {items.iter().map(|s| (*s).to_string()).collect()}/// The provider catalogue with each provider's readiness.pub(crate) fn provider_infos(config: &Config) -> Vec<LiveProviderInfo> {- let hosted = backend_ready(config);- let mut infos = built_in_provider_infos(config, hosted);+ let mut infos = built_in_provider_infos(config);super::registry::merge_provider_infos(&mut infos, config);infos}-fn built_in_provider_infos(config: &Config, hosted: bool) -> Vec<LiveProviderInfo> {+fn built_in_provider_infos(config: &Config) -> Vec<LiveProviderInfo> {LIVE_PROVIDERS.iter()+ .filter(|id| key_slug(id).is_some()).map(|id| {let slug = key_slug(id);let (label, kind, voices, languages) = match *id {- LIVE_PROVIDER_GEMINI_HOSTED => (- "Gemini Live (TinyHumans)",- LiveProviderKind::Hosted,- strings(GEMINI_VOICES),- strings(GEMINI_LANGUAGES),- ),- LIVE_PROVIDER_ELEVENLABS_HOSTED => (- "ElevenLabs Agent (TinyHumans)",- LiveProviderKind::Hosted,- Vec::new(),- Vec::new(),- ),LIVE_PROVIDER_GEMINI => ("Gemini Live (Google API key)",LiveProviderKind::Byok,@@ -117,10 +94,7 @@ fn built_in_provider_infos(config: &Config, hosted: bool) -> Vec<LiveProviderInfstrings(SARVAM_LANGUAGES),),};- let configured = match slug {- Some(slug) => stored_key(slug, config).is_some(),- None => hosted,- };+ let configured = slug.is_some_and(|slug| stored_key(slug, config).is_some());LiveProviderInfo {id: (*id).to_string(),label: label.to_string(),@@ -145,7 +119,7 @@ pub(crate) fn live_config(let mut live = LiveConfig::new();live.input_format = AudioFormat::pcm16(input_sample_rate);match provider {- LIVE_PROVIDER_GEMINI_HOSTED | LIVE_PROVIDER_GEMINI => {+ LIVE_PROVIDER_GEMINI => {live.system_instruction = Some(system_instruction.to_string());live.model = settings.gemini.model.clone();live.voice = settings.gemini.voice.clone();@@ -163,21 +137,12 @@ pub(crate) fn live_config(other => live.language = Some(other.unwrap_or("en-IN").to_string()),}}- LIVE_PROVIDER_ELEVENLABS_HOSTED => {- // The hosted agent owns its prompt and its brain (OpenHuman over- // the Custom-LLM relay); only the voice may be overridden.- live.voice = non_empty(settings.elevenlabs.voice_id.clone());- }_ => {}}super::registry::configure(config, provider, system_instruction, &mut live);live}-fn non_empty(value: Option<String>) -> Option<String> {- value.filter(|v| !v.trim().is_empty())-}-/// A provider ready to connect, with the configuration it must connect with.pub struct PreparedProvider {pub provider: Box<dyn LiveProvider>,@@ -185,46 +150,17 @@ pub struct PreparedProvider {}/// Resolves `provider` to something `tinyagents-live` can connect, minting a-/// backend ticket or signed URL for the hosted ones.+/// backend ticket or signed URL for the hosted ones (registered, see+/// [`super::registry`]).pub(crate) async fn prepare(config: &Config,provider: &str,- mut live: LiveConfig,+ live: LiveConfig,) -> Result<PreparedProvider, LiveVoiceError> {if let Some(entry) = super::registry::lookup(provider) {return super::registry::prepare_with(&entry, provider, config, live).await;}match provider {- LIVE_PROVIDER_GEMINI_HOSTED => {- let ticket = mint_gemini_ticket(config, &live).await?;- tracing::debug!(- "{LOG_PREFIX} minted gemini live ticket session={} model={}",- ticket.session_id,- ticket.model- );- let relay = GeminiRelay::connect_url(ticket.ws_url)- .with_session(ticket.session_id, ticket.model);- Ok(PreparedProvider {- provider: Box::new(relay),- config: live,- })- }- LIVE_PROVIDER_ELEVENLABS_HOSTED => {- let signed = crate::voice::realtime::mint_voice_agent_signed_url(config)- .await- .map_err(LiveVoiceError::backend)?- .value;- // `user_token` is the identity the backend's Custom-LLM relay- // verifies on every relayed turn (#5399).- live.provider_options = json!({- "user_id": signed.user_token,- "custom_llm_extra_body": { "user": signed.user_token },- });- Ok(PreparedProvider {- provider: Box::new(ElevenLabsConvai::connect_url(signed.signed_url)),- config: live,- })- }LIVE_PROVIDER_GEMINI => {let key = stored_key("google", config).ok_or_else(|| {LiveVoiceError::not_configured("add a Google API key for Gemini Live")@@ -248,58 +184,6 @@ pub(crate) async fn prepare(}}-/// A minted relay ticket.-#[derive(Debug, Clone, PartialEq, Eq)]-pub(crate) struct GeminiTicket {- pub(crate) ws_url: String,- pub(crate) session_id: String,- pub(crate) model: String,-}--/// Parses the backend's ticket response (`data`-wrapped or bare).-pub(crate) fn parse_ticket(raw: &Value) -> Result<GeminiTicket, LiveVoiceError> {- let data = raw.get("data").unwrap_or(raw);- let field = |name: &str| {- data.get(name)- .and_then(Value::as_str)- .filter(|v| !v.is_empty())- .map(str::to_string)- };- let ws_url = field("wsUrl").ok_or_else(|| {- LiveVoiceError::backend("backend returned no wsUrl for the live session".to_string())- })?;- Ok(GeminiTicket {- ws_url,- session_id: field("sessionId").unwrap_or_default(),- model: field("model").unwrap_or_default(),- })-}--async fn mint_gemini_ticket(- config: &Config,- live: &LiveConfig,-) -> Result<GeminiTicket, LiveVoiceError> {- let credential =- crate::security::credentials::session_support::resolve_backend_credential(config)- .map_err(LiveVoiceError::not_configured)?;- let api_url =- crate::backend::require_base_url(&config.api_url).map_err(LiveVoiceError::backend)?;- crate::voice::realtime::ensure_secure_backend_url(&api_url).map_err(LiveVoiceError::backend)?;- let client =- BackendClient::new(&api_url).map_err(|e| LiveVoiceError::backend(e.to_string()))?;- let body = gemini::ticket_request(live);- let raw = client- .authed_json(- &credential,- Method::POST,- GEMINI_LIVE_SESSIONS_PATH,- Some(body),- )- .await- .map_err(|error| LiveVoiceError::backend(crate::backend::flatten_authed_error(error)))?;- parse_ticket(&raw)-}-#[cfg(test)]#[path = "providers_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/voice/schemas/handlers.rs b/crates/openhuman-core/src/voice/schemas/handlers.rsindex 8301649bc2..616265b5a7 100644--- a/crates/openhuman-core/src/voice/schemas/handlers.rs+++ b/crates/openhuman-core/src/voice/schemas/handlers.rs@@ -13,7 +13,7 @@ pub(super) use provider_server::{handle_voice_test_provider, handle_voice_update_provider_settings,};pub(super) use transcribe_tts::{- handle_voice_agent_signed_url, handle_voice_cloud_transcribe, handle_voice_reply_synthesize,+ handle_voice_reply_synthesize,handle_voice_status, handle_voice_stt_dispatch, handle_voice_transcribe,handle_voice_transcribe_bytes, handle_voice_tts, handle_voice_tts_dispatch,};diff --git a/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rs b/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rsindex 25fe0b048b..01dd52c673 100644--- a/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rs+++ b/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rs@@ -9,7 +9,7 @@ use crate::voice::schemas::helpers::{deserialize_params, effective_stt_provider, effective_tts_provider, to_json,};use crate::voice::schemas::params::{- CloudTranscribeParams, ReplySynthesizeParams, SttDispatchParams, TranscribeBytesParams,+ ReplySynthesizeParams, SttDispatchParams, TranscribeBytesParams,TranscribeParams, TtsDispatchParams, TtsParams,};@@ -23,18 +23,6 @@ pub(crate) fn handle_voice_status(})}-/// Mint a realtime voice-agent signed WebSocket URL (#5399). Takes no params —-/// the agent is server-configured; the desktop only asks for a fresh signed URL.-pub(crate) fn handle_voice_agent_signed_url(- ctx: DispatchCtx,- _params: Map<String, Value>,-) -> ControllerFuture {- Box::pin(async move {- let config = ctx.load_config().await?;- to_json(crate::voice::realtime::mint_voice_agent_signed_url(&config).await?)- })-}-pub(crate) fn handle_voice_transcribe(ctx: DispatchCtx,params: Map<String, Value>,@@ -130,26 +118,6 @@ pub(crate) fn handle_voice_reply_synthesize(})}-pub(crate) fn handle_voice_cloud_transcribe(- ctx: DispatchCtx,- params: Map<String, Value>,-) -> ControllerFuture {- Box::pin(async move {- let config = ctx.load_config().await?;- let p = deserialize_params::<CloudTranscribeParams>(params)?;- let opts = tinyinference_voice::cloud::CloudTranscribeOptions {- model: p.model,- language: p.language,- mime_type: p.mime_type,- file_name: p.file_name,- };- to_json(- crate::voice::cloud_transcribe::transcribe_cloud(&config, &p.audio_base64, &opts)- .await?,- )- })-}-pub(crate) fn handle_voice_stt_dispatch(ctx: DispatchCtx,params: Map<String, Value>,diff --git a/crates/openhuman-core/src/voice/schemas/params.rs b/crates/openhuman-core/src/voice/schemas/params.rsindex c1a55fe5d5..a961a0ae77 100644--- a/crates/openhuman-core/src/voice/schemas/params.rs+++ b/crates/openhuman-core/src/voice/schemas/params.rs@@ -33,19 +33,6 @@ pub(super) struct TtsParams {pub(super) output_path: Option<String>,}-#[derive(Debug, Deserialize)]-pub(super) struct CloudTranscribeParams {- pub(super) audio_base64: String,- #[serde(default)]- pub(super) mime_type: Option<String>,- #[serde(default)]- pub(super) file_name: Option<String>,- #[serde(default)]- pub(super) model: Option<String>,- #[serde(default)]- pub(super) language: Option<String>,-}-/// Factory-dispatched STT request. The caller can either pin a provider/// explicitly (`"cloud"` / `"<slug>[:<model>]"`) or let the controller resolve the/// effective provider from `config.local_ai.stt_provider`. Keeps thediff --git a/crates/openhuman-core/src/voice/schemas/registry.rs b/crates/openhuman-core/src/voice/schemas/registry.rsindex 2604215cb1..0ac00c9505 100644--- a/crates/openhuman-core/src/voice/schemas/registry.rs+++ b/crates/openhuman-core/src/voice/schemas/registry.rs@@ -4,8 +4,7 @@ use crate::core::all::RegisteredController;use crate::core::{ControllerSchema, FieldSchema, TypeSchema};use super::handlers::{- handle_overlay_stt_notify, handle_voice_agent_signed_url, handle_voice_cloud_transcribe,- handle_voice_list_models, handle_voice_reply_synthesize, handle_voice_server_start,+ handle_overlay_stt_notify, handle_voice_list_models, handle_voice_reply_synthesize, handle_voice_server_start,handle_voice_server_status, handle_voice_server_stop, handle_voice_set_providers,handle_voice_status, handle_voice_stt_dispatch, handle_voice_test_provider,handle_voice_transcribe, handle_voice_transcribe_bytes, handle_voice_tts,@@ -16,12 +15,10 @@ use super::helpers::{json_output, optional_bool, optional_string, required_strinpub fn all_voice_controller_schemas() -> Vec<ControllerSchema> {vec![voice_schemas("voice_status"),- voice_schemas("voice_agent_signed_url"),voice_schemas("voice_transcribe"),voice_schemas("voice_transcribe_bytes"),voice_schemas("voice_tts"),voice_schemas("voice_reply_synthesize"),- voice_schemas("voice_cloud_transcribe"),voice_schemas("voice_stt_dispatch"),voice_schemas("voice_tts_dispatch"),voice_schemas("voice_set_providers"),@@ -44,10 +41,6 @@ pub fn all_voice_registered_controllers() -> Vec<RegisteredController> {schema: voice_schemas("voice_status"),handler: handle_voice_status,},- RegisteredController {- schema: voice_schemas("voice_agent_signed_url"),- handler: handle_voice_agent_signed_url,- },RegisteredController {schema: voice_schemas("voice_transcribe"),handler: handle_voice_transcribe,@@ -64,10 +57,6 @@ pub fn all_voice_registered_controllers() -> Vec<RegisteredController> {schema: voice_schemas("voice_reply_synthesize"),handler: handle_voice_reply_synthesize,},- RegisteredController {- schema: voice_schemas("voice_cloud_transcribe"),- handler: handle_voice_cloud_transcribe,- },RegisteredController {schema: voice_schemas("voice_stt_dispatch"),handler: handle_voice_stt_dispatch,@@ -123,16 +112,6 @@ pub fn voice_schemas(function: &str) -> ControllerSchema {inputs: vec![],outputs: vec![json_output("status", "Voice availability status.")],},- "voice_agent_signed_url" => ControllerSchema {- namespace: "voice",- function: "agent_signed_url",- description: "Mint a short-lived signed URL for a realtime voice-agent session.",- inputs: vec![],- outputs: vec![- json_output("signed_url", "Signed WebSocket URL for the voice-agent session."),- json_output("agent_id", "The voice agent the URL was minted for."),- ],- },"voice_transcribe" => ControllerSchema {namespace: "voice",function: "transcribe",@@ -354,24 +333,6 @@ pub fn voice_schemas(function: &str) -> ControllerSchema {"{ ok: bool, detail: string, latency_ms?: number }",)],},- "voice_cloud_transcribe" => ControllerSchema {- namespace: "voice",- function: "cloud_transcribe",- description:- "Transcribe audio bytes via the hosted backend's STT endpoint. Used by the \- mascot's mic-only composer so we don't ship a provider API key in the desktop app.",- inputs: vec![- required_string(- "audio_base64",- "Base64-encoded audio bytes (e.g. webm/opus from MediaRecorder).",- ),- optional_string("mime_type", "Audio MIME type (default: audio/webm)."),- optional_string("file_name", "Original filename hint (default: audio.webm)."),- optional_string("model", "Backend STT model id (default: whisper-v1)."),- optional_string("language", "BCP-47 language hint, e.g. 'en'."),- ],- outputs: vec![json_output("result", "CloudTranscribeResult: { text }.")],- },"voice_server_start" => ControllerSchema {namespace: "voice",function: "server_start",diff --git a/crates/openhuman-tinyhumans/src/memory/mod_tests.rs b/crates/openhuman-tinyhumans/src/memory/mod_tests.rsnew file mode 100644index 0000000000..779c478263--- /dev/null+++ b/crates/openhuman-tinyhumans/src/memory/mod_tests.rs@@ -0,0 +1,425 @@+use super::*;+use crate::hosted::test_support;+use openhuman_embed::__host::memory_engines::Binding;+use openhuman_embed::__host::security::credentials::session_support::BackendCredential;+use openhuman_embed::__host::security::credentials::{+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,+};+use serde_json::json;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::{Duration, Instant};++use billing::{active_with_cache, digest, fetch, parse_active, Answer, CACHE_TTL};+use engine::HostBearer;++const KEY: &str = "https://backend.test";++fn config_with_endpoint(+ tmp: &tempfile::TempDir,+ endpoint: &str,+) -> openhuman_embed::__host::config::Config {+ let mut config = test_support::config(tmp, "http://127.0.0.1:9");+ config.memory.engine = TINYHUMANS_ENGINE.to_string();+ config+ .memory+ .engines+ .entry(TINYHUMANS_ENGINE.to_string())+ .or_default()+ .endpoint = Some(endpoint.to_string());+ config+}++fn request<'a>(+ config: &'a openhuman_embed::__host::config::Config,+ root: Option<&'a str>,+) -> openhuman_embed::__host::memory_engines::EngineRequest<'a> {+ openhuman_embed::__host::memory_engines::EngineRequest { config, root }+}++fn store_key(config: &openhuman_embed::__host::config::Config, key: &str) {+ test_support::store_session(config, key);+}++fn off_reason(binding: Binding) -> String {+ match binding {+ Binding::Off { reason, .. } => reason,+ Binding::On(bound) => panic!("expected off, bound {}", bound.id),+ }+}++// ── engine ──────────────────────────────────────────────────────────────────++#[test]+fn without_a_credential_the_engine_is_off_and_reports_its_endpoint() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_with_endpoint(&tmp, "https://memory.example.test");+ match engine::bind(&request(&config, None)) {+ Binding::Off {+ engine, endpoint, ..+ } => {+ assert_eq!(engine.as_deref(), Some(TINYHUMANS_ENGINE));+ assert_eq!(endpoint.as_deref(), Some("https://memory.example.test"));+ }+ Binding::On(_) => panic!("expected off"),+ }+}++#[test]+fn a_local_session_token_is_off() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_with_endpoint(&tmp, "https://memory.example.test");+ store_key(&config, "desktop.test.local");+ let reason = off_reason(engine::bind(&request(&config, None)));+ assert!(reason.contains("sign in"), "{reason}");+}++#[test]+fn the_host_credential_binds_below_the_endpoint_and_is_cached() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_with_endpoint(&tmp, "https://memory.example.test");+ store_key(&config, "jwt.memory.test");+ let first = match engine::bind(&request(&config, None)) {+ Binding::On(bound) => bound,+ Binding::Off { reason, .. } => panic!("expected bound: {reason}"),+ };+ assert_eq!(first.id, TINYHUMANS_ENGINE);+ assert_eq!(first.endpoint, "https://memory.example.test");+ let second = match engine::bind(&request(&config, None)) {+ Binding::On(bound) => bound,+ Binding::Off { reason, .. } => panic!("expected bound: {reason}"),+ };+ assert!(+ std::sync::Arc::ptr_eq(&first.engine, &second.engine),+ "cached engine reused"+ );+}++#[test]+fn the_layout_root_gets_its_own_cached_engine() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_with_endpoint(&tmp, "https://memory.example.test");+ store_key(&config, "jwt.memory.layout");+ let legacy = engine::bind(&request(&config, None));+ let rooted = engine::bind(&request(&config, Some("org:42")));+ match (legacy, rooted) {+ (Binding::On(legacy), Binding::On(rooted)) => {+ assert!(!std::sync::Arc::ptr_eq(&legacy.engine, &rooted.engine));+ }+ _ => panic!("both layouts bind"),+ }+}++#[test]+fn the_default_endpoint_is_the_control_plane_origin() {+ let tmp = tempfile::tempdir().unwrap();+ let mut config = test_support::config(&tmp, "https://api.override.test");+ config.memory.engine = TINYHUMANS_ENGINE.to_string();+ assert_eq!(+ engine::endpoint_for(&config),+ crate::backend::url::effective_backend_api_url(&config.api_url)+ );+}++#[tokio::test]+async fn host_bearer_reads_the_credential_per_request() {+ let tmp = tempfile::tempdir().unwrap();+ let config = test_support::config(&tmp, "http://127.0.0.1:9");+ let source = HostBearer {+ config: std::sync::Arc::new(config.clone()),+ };+ let error = openhuman_embed::__host::memory_engines::BearerSource::bearer(&source)+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ openhuman_embed::memory::api::Error::Unauthorized(_)+ ));++ store_key(&config, "jwt.bearer.test");+ assert_eq!(+ openhuman_embed::__host::memory_engines::BearerSource::bearer(&source)+ .await+ .unwrap(),+ "jwt.bearer.test"+ );+}++#[tokio::test]+async fn host_bearer_rejects_a_local_session_token() {+ let tmp = tempfile::tempdir().unwrap();+ let config = test_support::config(&tmp, "http://127.0.0.1:9");+ AuthService::from_config(&config)+ .store_provider_token(+ APP_SESSION_PROVIDER,+ DEFAULT_AUTH_PROFILE_NAME,+ "desktop.test.local",+ std::collections::HashMap::new(),+ true,+ )+ .ok();+ store_key(&config, "desktop.test.local");+ let source = HostBearer {+ config: std::sync::Arc::new(config),+ };+ let error = openhuman_embed::__host::memory_engines::BearerSource::bearer(&source)+ .await+ .unwrap_err();+ assert!(matches!(+ error,+ openhuman_embed::memory::api::Error::Unauthorized(_)+ ));+}++#[test]+fn registering_twice_leaves_one_engine() {+ register(&InstallOptions::default());+ register(&InstallOptions::default());+ assert!(openhuman_embed::__host::memory_engines::unregister_memory_engine(TINYHUMANS_ENGINE));+}++// ── billing ─────────────────────────────────────────────────────────────────++#[test]+fn parse_active_reads_the_flag_and_refuses_anything_else() {+ assert_eq!(+ parse_active(&json!({"active": true, "until": "x"})),+ Ok(true)+ );+ assert_eq!(+ parse_active(&json!({"active": false, "until": null})),+ Ok(false)+ );+ assert!(parse_active(&json!({"active": "yes"})).is_err());+ assert!(parse_active(&json!({})).is_err());+ assert_eq!(+ parse_active(&json!({"success": true, "data": {"active": true}})),+ Ok(true),+ "an answer still in its envelope reads the same"+ );+ assert!(parse_active(&json!({"success": true, "data": {}})).is_err());+}++#[tokio::test]+async fn an_answer_is_reused_within_the_ttl_and_asked_again_after() {+ let cache = Answer::new();+ let base = Instant::now();+ let calls = AtomicUsize::new(0);+ let ask = |active: bool| {+ calls.fetch_add(1, Ordering::SeqCst);+ async move { Ok(active) }+ };+ assert!(active_with_cache(&cache, KEY, CACHE_TTL, || base, || ask(true)).await);+ assert!(+ active_with_cache(+ &cache,+ KEY,+ CACHE_TTL,+ || base + Duration::from_secs(30),+ || ask(false)+ )+ .await,+ "still the cached answer"+ );+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert!(+ !active_with_cache(+ &cache,+ KEY,+ CACHE_TTL,+ || base + Duration::from_secs(61),+ || ask(false)+ )+ .await,+ "asked again once stale"+ );+ assert_eq!(calls.load(Ordering::SeqCst), 2);+}++#[tokio::test]+async fn an_error_is_not_free_and_is_not_asked_again_at_once() {+ let cache = Answer::new();+ let base = Instant::now();+ let calls = AtomicUsize::new(0);+ let failing = || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Err::<bool, _>("GET /memory/free-period failed (404 Not Found)".to_string()) }+ };+ assert!(!active_with_cache(&cache, KEY, CACHE_TTL, || base, failing).await);+ assert!(!active_with_cache(&cache, KEY, CACHE_TTL, || base, failing).await);+ assert_eq!(calls.load(Ordering::SeqCst), 1, "a failure is cached too");+}++#[tokio::test]+async fn each_backend_keeps_its_own_answer() {+ let cache = Answer::new();+ let base = Instant::now();+ let calls = AtomicUsize::new(0);+ let ask = |active: bool| {+ calls.fetch_add(1, Ordering::SeqCst);+ async move { Ok(active) }+ };+ assert!(active_with_cache(&cache, "https://a.test", CACHE_TTL, || base, || ask(true)).await);+ assert!(!active_with_cache(&cache, "https://b.test", CACHE_TTL, || base, || ask(false)).await);+ assert!(active_with_cache(&cache, "https://a.test", CACHE_TTL, || base, || ask(false)).await);+ assert_eq!(calls.load(Ordering::SeqCst), 2, "a's answer survived b's");+}++#[tokio::test]+async fn concurrent_callers_share_one_request() {+ let cache = Answer::new();+ let base = Instant::now();+ let calls = AtomicUsize::new(0);+ let ask = || {+ calls.fetch_add(1, Ordering::SeqCst);+ async {+ tokio::time::sleep(Duration::from_millis(20)).await;+ Ok(true)+ }+ };+ let (a, b) = tokio::join!(+ active_with_cache(&cache, KEY, CACHE_TTL, || base, ask),+ active_with_cache(&cache, KEY, CACHE_TTL, || base, ask),+ );+ assert!(a && b);+ assert_eq!(calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn an_answer_is_timed_from_when_it_arrives() {+ let cache = Answer::new();+ let base = Instant::now();+ let calls = AtomicUsize::new(0);+ let ticks = AtomicUsize::new(0);+ // The fetch takes longer than the TTL: asked at `base`, answered at+ // `base + 90s`.+ let clock = || {+ if ticks.fetch_add(1, Ordering::SeqCst) == 0 {+ base+ } else {+ base + Duration::from_secs(90)+ }+ };+ let ask = || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Ok(true) }+ };+ assert!(active_with_cache(&cache, KEY, CACHE_TTL, clock, ask).await);+ let later = || base + Duration::from_secs(120);+ assert!(active_with_cache(&cache, KEY, CACHE_TTL, later, ask).await);+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 1,+ "still fresh 30s after it arrived"+ );+}++#[test]+fn the_cache_key_digest_is_the_full_sha256() {+ let key = digest("th_account_a");+ assert_eq!(key.len(), 64, "{key}");+ assert_ne!(key, digest("th_account_b"));+}++async fn backend_answering(status: u16, body: serde_json::Value) -> wiremock::MockServer {+ use wiremock::matchers::{method, path};+ let server = wiremock::MockServer::start().await;+ wiremock::Mock::given(method("GET"))+ .and(path("/memory/free-period"))+ .respond_with(wiremock::ResponseTemplate::new(status).set_body_json(body))+ .mount(&server)+ .await;+ server+}++#[tokio::test]+async fn the_backend_says_the_period_is_on_or_off() {+ let on = backend_answering(+ 200,+ json!({"success": true, "data": {"active": true, "until": "2026-11-06T00:00:00.000Z"}}),+ )+ .await;+ let off = backend_answering(+ 200,+ json!({"success": true, "data": {"active": false, "until": null}}),+ )+ .await;+ let credential = BackendCredential::Session("jwt.free.test".to_string());+ assert_eq!(fetch(&credential, &on.uri()).await, Ok(true));+ assert_eq!(fetch(&credential, &off.uri()).await, Ok(false));+}++#[tokio::test]+async fn a_backend_without_the_route_is_an_error_read_as_not_free() {+ let server = backend_answering(404, json!({"success": false, "error": "Not Found"})).await;+ let credential = BackendCredential::Session("jwt.free.test".to_string());+ assert!(fetch(&credential, &server.uri()).await.is_err());+ let cache = Answer::new();+ let uri = server.uri();+ assert!(+ !active_with_cache(&cache, &uri, CACHE_TTL, Instant::now, || fetch(+ &credential,+ &uri+ ))+ .await+ );+}++/// The hosted engine bound for `config` (which must hold a credential).+fn bound_for(+ config: &openhuman_embed::__host::config::Config,+) -> openhuman_embed::__host::memory_engines::BoundEngine {+ match engine::bind(&request(config, None)) {+ Binding::On(bound) => bound,+ Binding::Off { reason, .. } => panic!("expected bound: {reason}"),+ }+}++async fn registered_free_period(config: openhuman_embed::__host::config::Config) -> bool {+ let bound = bound_for(&config);+ billing::free_period_active(config, bound).await+}++#[tokio::test]+async fn the_engines_own_endpoint_is_asked_not_the_apps() {+ let tmp = tempfile::tempdir().unwrap();+ let server = backend_answering(+ 200,+ json!({"success": true, "data": {"active": true, "until": null}}),+ )+ .await;+ let config = config_with_endpoint(&tmp, &server.uri());+ store_key(&config, "jwt.endpoint.test");+ assert!(registered_free_period(config).await);+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}++#[tokio::test]+async fn each_account_keeps_its_own_answer_on_the_hosted_engine() {+ let server = backend_answering(+ 200,+ json!({"success": true, "data": {"active": true, "until": null}}),+ )+ .await;+ for key in ["jwt.account.a", "jwt.account.b"] {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_with_endpoint(&tmp, &server.uri());+ store_key(&config, key);+ assert!(registered_free_period(config).await);+ }+ assert_eq!(+ server.received_requests().await.unwrap().len(),+ 2,+ "the second account asked for its own answer"+ );+}++#[tokio::test]+async fn a_signed_out_account_is_not_free() {+ let tmp = tempfile::tempdir().unwrap();+ let signed_in = config_with_endpoint(&tmp, "http://127.0.0.1:9");+ store_key(&signed_in, "jwt.signed.out");+ let bound = bound_for(&signed_in);+ let other = tempfile::tempdir().unwrap();+ let signed_out = config_with_endpoint(&other, "http://127.0.0.1:9");+ assert!(!billing::free_period_active(signed_out, bound).await);+}