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
test(e2e): cover 42 untested RPC controllers across voice, inference, sandbox, worktree, http_host, workspace, modules
M3gA-Mindc19763fd6040
diff --git a/tests/raw_coverage/inference_provider_auth_e2e.rs b/tests/raw_coverage/inference_provider_auth_e2e.rsnew file mode 100644index 0000000000..c8983d929b--- /dev/null+++ b/tests/raw_coverage/inference_provider_auth_e2e.rs@@ -0,0 +1,1178 @@+//! JSON-RPC E2E coverage for the seven `inference` controllers that no+//! `tests/**/*_e2e.rs` target reached: the four Claude-Code-CLI provider+//! surfaces, the Codex-CLI OAuth import, the BYO-provider auth-error registry,+//! and model-hint resolution.+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target;+//! `build.rs` globs `tests/raw_coverage/` and generates the `mod` list.+//!+//! Run with:+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)"`+//!+//! # How each case stays deterministic without a network or a real CLI+//!+//! - `claude_code_status` shells out to a `claude` binary. Every case here+//! points `OPENHUMAN_CLAUDE_CLI` at a **stub script** whose version string+//! the case chooses, so `ok` / `outdated` / `unusable` / `not_installed` are+//! all reachable and none of them depend on what is installed on the host.+//! - `claude_code_auth_status` resolves `ANTHROPIC_API_KEY` *before* it spawns+//! anything, so the `api_key_env` branch is assertable with no subprocess at+//! all. The un-keyed branch is driven through the same stub.+//! - `openai_oauth_import_codex_cli` reads `$CODEX_HOME/auth.json`, so a+//! fixture file drives both the import and the failure.+//! - `provider_auth_errors` reads a process-lived registry that+//! `auth_error_registry::record` writes; the case records and clears its own+//! entries so it leaves no state behind for another suite.+//!+//! Env is process-global and every aggregated suite shares one process, so+//! each case takes the **crate-wide** [`env_lock`] for its whole body.++use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;+use openhuman_core::openhuman::inference::auth_error_registry;++const TEST_RPC_TOKEN: &str = "inference-provider-auth-e2e-token";++static AUTH_INIT: OnceLock<()> = OnceLock::new();++/// Crate-wide, not file-local: all aggregated suites share one process, so a+/// private mutex would not mutually exclude with anyone else's env mutation.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++struct EnvVarGuard {+ key: &'static str,+ old: Option<std::ffi::OsString>,+}++impl EnvVarGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let old = std::env::var_os(key);+ std::env::set_var(key, path.as_os_str());+ Self { key, old }+ }++ fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var_os(key);+ std::env::set_var(key, value);+ Self { key, old }+ }++ fn unset(key: &'static str) -> Self {+ let old = std::env::var_os(key);+ std::env::remove_var(key);+ Self { key, old }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+}++/// See the note in `sandbox_runtime_platform_e2e.rs`: `core::auth::RPC_TOKEN`+/// is a process-global `OnceLock` and `init_rpc_token` is idempotent, so inside+/// the aggregated binary the first suite to initialise pins the bearer. Use the+/// token this process actually validates rather than assuming ours won.+fn ensure_rpc_auth() -> String {+ AUTH_INIT.get_or_init(|| {+ if std::env::var(CORE_TOKEN_ENV_VAR)+ .ok()+ .filter(|v| !v.trim().is_empty())+ .is_none()+ {+ std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);+ }+ let token_dir = std::env::temp_dir().join("openhuman-inference-provider-auth-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+ get_rpc_token()+ .expect("core RPC token must be initialised before serving")+ .to_string()+}++fn write_config(openhuman_dir: &Path, extra: &str) {+ std::fs::create_dir_all(openhuman_dir).expect("create .openhuman");+ let cfg = format!(+ r#"api_url = "http://127.0.0.1:9"+default_model = "e2e-model"+default_temperature = 0.2+{extra}+[secrets]+encrypt = false++[local_ai]+enabled = false++[modules]+enabled = false+allow_download = false++[memory]+provider = "none"+embedding_provider = "none"+embedding_model = "none"+embedding_dimensions = 0++[memory_tree]+embedding_strict = false+"#+ );+ std::fs::write(openhuman_dir.join("config.toml"), &cfg).expect("write config.toml");+ let _: openhuman_core::openhuman::config::Config =+ toml::from_str(&cfg).expect("test config must match schema");+}++struct TestHarness {+ tmp: TempDir,+ _guards: Vec<EnvVarGuard>,+ rpc_base: String,+ token: String,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++impl TestHarness {+ fn home(&self) -> &Path {+ self.tmp.path()+ }++ fn workspace(&self) -> std::path::PathBuf {+ self.tmp.path().join("workspace")+ }++ async fn rpc(&self, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("client");+ let url = format!("{}/rpc", self.rpc_base.trim_end_matches('/'));+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", self.token))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": method,+ "params": params,+ }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+ }+}++async fn serve_rpc() -> (+ SocketAddr,+ String,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ let token = ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let router = build_core_http_router(false);+ let join = tokio::spawn(async move { axum::serve(listener, router).await });+ (addr, token, join)+}++/// `extra` is appended to the generated `config.toml`, which is how a case+/// pins a per-workload provider route for `inference_resolve_model`.+async fn setup(extra: &str) -> TestHarness {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ write_config(&home.join(".openhuman"), extra);+ let workspace = home.join("workspace");+ std::fs::create_dir_all(&workspace).expect("create workspace");++ let guards = vec![+ EnvVarGuard::set_to_path("HOME", home),+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ // The host developer's real credentials must never decide what these+ // cases observe.+ EnvVarGuard::unset("ANTHROPIC_API_KEY"),+ EnvVarGuard::unset("OPENHUMAN_CLAUDE_CLI"),+ EnvVarGuard::unset("CODEX_HOME"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let (addr, token, join) = serve_rpc().await;+ TestHarness {+ tmp,+ _guards: guards,+ rpc_base: format!("http://{addr}"),+ token,+ join,+ }+}++fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {+ if let Some(error) = value.get("error") {+ panic!("{context}: unexpected JSON-RPC error: {error}");+ }+ value+ .get("result")+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"))+}++fn err_message(value: &Value, context: &str) -> String {+ let error = value+ .get("error")+ .unwrap_or_else(|| panic!("{context}: expected JSON-RPC error, got: {value}"));+ error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{context}: error without message: {error}"))+ .to_string()+}++fn payload<'a>(value: &'a Value, context: &str) -> &'a Value {+ let result = ok(value, context);+ result.get("result").unwrap_or(result)+}++/// Write an executable stub `claude` and return its path. `body` is a POSIX+/// shell script; the caller decides what `--version` prints and what the exit+/// status is.+#[cfg(unix)]+fn write_claude_stub(dir: &Path, name: &str, body: &str) -> std::path::PathBuf {+ use std::os::unix::fs::PermissionsExt;+ std::fs::create_dir_all(dir).expect("create stub dir");+ let path = dir.join(name);+ std::fs::write(&path, body).expect("write claude stub");+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod stub");+ path+}++/// A JWT-shaped token with an unsigned, base64url payload — what the Codex CLI+/// writes and what the importer decodes for the account id and expiry.+fn unsigned_jwt(claims: Value) -> String {+ use base64::Engine as _;+ let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;+ let header = engine.encode(br#"{"alg":"none","typ":"JWT"}"#);+ let payload = engine.encode(claims.to_string().as_bytes());+ format!("{header}.{payload}.")+}++// ── inference.resolve_model ────────────────────────────────────────────────++#[tokio::test]+async fn inference_resolve_model_maps_hints_and_tiers_to_the_routed_model() {+ let _lock = env_lock();+ let harness = setup("").await;++ // ---- Phase A: nothing routed. Every hint resolves to its managed tier. --++ // A managed tier with no BYOK route resolves to the tier name itself —+ // the managed backend is what expands it.+ let reasoning = harness+ .rpc(+ 71_001,+ "openhuman.inference_resolve_model",+ json!({ "hint": "hint:reasoning" }),+ )+ .await;+ let reasoning = payload(&reasoning, "resolve_model hint:reasoning");+ assert_eq!(+ reasoning.get("model"),+ Some(&json!("reasoning-v1")),+ "an unrouted reasoning hint resolves to the managed tier: {reasoning}"+ );+ assert_eq!(+ reasoning.get("vision"),+ Some(&json!(true)),+ "the reasoning tier is one of the two vision-capable managed tiers \+ (`oh_tier_supports_vision`); the RPC schema comment claiming the \+ per-tier map is `currently all false` is stale — see \+ ~/tinyhuman/bugs/e2e-wave-inference-stale-vision-and-workspace-docs.md: \+ {reasoning}"+ );++ // The bare tier name is accepted alongside the `hint:` alias and must+ // resolve identically.+ let bare_tier = harness+ .rpc(+ 71_002,+ "openhuman.inference_resolve_model",+ json!({ "hint": "reasoning-v1" }),+ )+ .await;+ assert_eq!(+ payload(&bare_tier, "resolve_model reasoning-v1").get("model"),+ Some(&json!("reasoning-v1"))+ );++ // A tier that is genuinely text-only answers `vision: false`, so the flag+ // carries real information rather than being pinned one way.+ let chat = harness+ .rpc(+ 71_003,+ "openhuman.inference_resolve_model",+ json!({ "hint": "hint:chat" }),+ )+ .await;+ let chat = payload(&chat, "resolve_model hint:chat");+ assert_eq!(chat.get("model"), Some(&json!("chat-v1")));+ assert_eq!(+ chat.get("vision"),+ Some(&json!(false)),+ "the chat tier is text-only: {chat}"+ );++ for (id, hint, tier) in [+ (71_004, "hint:coding", "coding-v1"),+ (71_005, "hint:agentic", "agentic-v1"),+ (71_006, "hint:burst", "burst-v1"),+ ] {+ let resolved = harness+ .rpc(+ id,+ "openhuman.inference_resolve_model",+ json!({ "hint": hint }),+ )+ .await;+ assert_eq!(+ payload(&resolved, hint).get("model"),+ Some(&json!(tier)),+ "{hint} must resolve to {tier} while nothing is routed"+ );+ }++ // An unknown hint is passed through rather than silently remapped.+ let unknown = harness+ .rpc(+ 71_007,+ "openhuman.inference_resolve_model",+ json!({ "hint": "hint:not-a-workload" }),+ )+ .await;+ assert_eq!(+ payload(&unknown, "resolve_model unknown hint").get("model"),+ Some(&json!("hint:not-a-workload")),+ "an unrecognised hint must round-trip, not resolve to a wrong model"+ );++ // ---- Phase B: pin ONE BYOK route and watch who inherits it. -------------+ //+ // Set through the RPC the settings panel uses, not by hand-writing a key+ // into `config.toml`, so this is a two-controller round trip: what the+ // settings call persisted vs what the router then resolves.+ let routed = harness+ .rpc(+ 71_010,+ "openhuman.inference_update_model_settings",+ json!({ "coding_provider": "openrouter:zai/glm-4.7" }),+ )+ .await;+ assert!(+ routed.get("error").is_none(),+ "pinning the coding route must succeed: {routed}"+ );++ // The routed role resolves to the model half only — the provider slug is+ // routing, not a model id.+ for (id, hint) in [(71_011, "hint:coding"), (71_012, "coding-v1")] {+ let coding = harness+ .rpc(+ id,+ "openhuman.inference_resolve_model",+ json!({ "hint": hint }),+ )+ .await;+ assert_eq!(+ payload(&coding, hint).get("model"),+ Some(&json!("zai/glm-4.7")),+ "{hint}: a `slug:model` route must resolve to the model half only"+ );+ }++ // The part that is easy to get wrong, and the reason this is two phases:+ // `provider_for_role` lets the **three chat-tier roles** (chat, reasoning,+ // coding) inherit any configured BYOK route via+ // `resolve_byok_fallback_provider_string`. So pinning *only* `coding` also+ // moves chat and reasoning off the managed backend. Asserting it here means+ // a change to that scoping is a test failure rather than a silent re-route+ // of the user's conversations.+ for (id, hint) in [(71_013, "hint:reasoning"), (71_014, "hint:chat")] {+ let inherited = harness+ .rpc(+ id,+ "openhuman.inference_resolve_model",+ json!({ "hint": hint }),+ )+ .await;+ assert_eq!(+ payload(&inherited, hint).get("model"),+ Some(&json!("zai/glm-4.7")),+ "{hint} inherits the BYOK route configured for a sibling chat-tier \+ role — setting one of chat/reasoning/coding moves all three"+ );+ }++ // …and the inheritance stops there. Agentic, burst, vision and the+ // background workloads stay on the managed backend, because they run+ // tier-specific models a BYOK provider does not serve.+ for (id, hint, tier) in [+ (71_015, "hint:agentic", "agentic-v1"),+ (71_016, "hint:burst", "burst-v1"),+ (71_017, "hint:vision", "vision-v1"),+ (71_018, "hint:summarization", "summarization-v1"),+ ] {+ let managed = harness+ .rpc(+ id,+ "openhuman.inference_resolve_model",+ json!({ "hint": hint }),+ )+ .await;+ assert_eq!(+ payload(&managed, hint).get("model"),+ Some(&json!(tier)),+ "{hint} must NOT inherit a chat-tier BYOK route — it stays managed"+ );+ }++ // ---- Failure paths -----------------------------------------------------+ //+ // Omitted: refused at the dispatch boundary from the schema's `required`+ // flag. Present-but-wrong-type: refused by the handler's deserialize. Two+ // different gates, so assert the two different messages.+ let missing = harness+ .rpc(71_020, "openhuman.inference_resolve_model", json!({}))+ .await;+ assert!(+ err_message(&missing, "resolve_model missing hint")+ .contains("missing required param 'hint'"),+ "an omitted `hint` must be refused by the schema gate"+ );++ // Present but the wrong JSON type. This is a THIRD gate, distinct from the+ // two above: `core::all::validate_params` type-checks every present param+ // against its declared `TypeSchema` before dispatch, so the handler's own+ // `serde_json::from_value` is never reached. Pinning the exact wording+ // because it is the message a client developer sees.+ let wrong_type = harness+ .rpc(+ 71_021,+ "openhuman.inference_resolve_model",+ json!({ "hint": 42 }),+ )+ .await;+ assert_eq!(+ err_message(&wrong_type, "resolve_model numeric hint"),+ "invalid type for param 'hint' in inference.resolve_model: \+ expected string, got number",+ "a non-string `hint` must be refused by the boundary type-check"+ );++ harness.join.abort();+}++// ── inference.provider_auth_errors ─────────────────────────────────────────++#[tokio::test]+async fn inference_provider_auth_errors_surfaces_recorded_byo_key_rejections() {+ let _lock = env_lock();+ let harness = setup("").await;++ // Start from a known state — another suite in this binary may have+ // recorded entries, and this case owns only its own slugs.+ let _ = auth_error_registry::clear("e2e-openrouter");+ let _ = auth_error_registry::clear("e2e-deepseek");++ let empty = harness+ .rpc(+ 72_001,+ "openhuman.inference_provider_auth_errors",+ json!({}),+ )+ .await;+ let before = payload(&empty, "provider_auth_errors empty")+ .get("errors")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("errors must be an array: {empty}"))+ .clone();+ assert!(+ !before+ .iter()+ .any(|e| e.get("provider") == Some(&json!("e2e-openrouter"))),+ "this case's slug must not be present before it records: {before:?}"+ );++ // Record two failures the way the demote site does, then read them back+ // over the RPC. This is the whole contract of the namespace: what the+ // provider layer records is what the settings panel shows.+ assert!(+ auth_error_registry::record("e2e-openrouter", 401),+ "the first failure for a provider opens a new episode"+ );+ assert!(+ !auth_error_registry::record("e2e-openrouter", 401),+ "a repeat failure must refresh, not re-open — that latch is what keeps \+ a retry loop from re-flooding the notification centre"+ );+ auth_error_registry::record("e2e-deepseek", 403);++ let listed = harness+ .rpc(+ 72_002,+ "openhuman.inference_provider_auth_errors",+ json!({}),+ )+ .await;+ let errors = payload(&listed, "provider_auth_errors recorded")+ .get("errors")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("errors must be an array: {listed}"))+ .clone();++ let openrouter = errors+ .iter()+ .find(|e| e.get("provider") == Some(&json!("e2e-openrouter")))+ .unwrap_or_else(|| panic!("the recorded 401 must be surfaced: {errors:?}"));+ assert_eq!(openrouter.get("status"), Some(&json!(401)));+ let message = openrouter+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ message.contains("e2e-openrouter") && message.contains("401"),+ "the surfaced message must name the provider and the status: {message}"+ );+ assert!(+ message.contains("Update your"),+ "the message must be actionable — it is rendered verbatim in the UI: {message}"+ );+ assert!(+ openrouter+ .get("timestamp_ms")+ .and_then(Value::as_u64)+ .is_some_and(|t| t > 0),+ "each entry must carry a wall-clock timestamp: {openrouter}"+ );++ let deepseek = errors+ .iter()+ .find(|e| e.get("provider") == Some(&json!("e2e-deepseek")))+ .unwrap_or_else(|| panic!("the recorded 403 must be surfaced: {errors:?}"));+ assert_eq!(deepseek.get("status"), Some(&json!(403)));++ // Clearing a provider's key removes it from the notice — assert the read+ // side sees that, since a stale "your key is bad" banner after the user+ // fixed their key is the failure this registry exists to avoid.+ assert!(auth_error_registry::clear("e2e-openrouter"));+ let after = harness+ .rpc(+ 72_003,+ "openhuman.inference_provider_auth_errors",+ json!({}),+ )+ .await;+ let after_errors = payload(&after, "provider_auth_errors cleared")+ .get("errors")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("errors must be an array: {after}"))+ .clone();+ assert!(+ !after_errors+ .iter()+ .any(|e| e.get("provider") == Some(&json!("e2e-openrouter"))),+ "a cleared provider must disappear from the notice: {after_errors:?}"+ );+ assert!(+ after_errors+ .iter()+ .any(|e| e.get("provider") == Some(&json!("e2e-deepseek"))),+ "clearing one provider must not clear the others: {after_errors:?}"+ );++ // Leave no state behind for another suite in this binary.+ let _ = auth_error_registry::clear("e2e-deepseek");++ harness.join.abort();+}++// ── inference.claude_code_status ───────────────────────────────────────────++#[cfg(unix)]+#[tokio::test]+async fn inference_claude_code_status_classifies_ok_outdated_unusable_and_missing() {+ let _lock = env_lock();+ let harness = setup("").await;+ let stub_dir = harness.home().join("stub-cli");++ // `ok` — a version at or above MIN_CLI_VERSION (2.0.0).+ let good = write_claude_stub(+ &stub_dir,+ "claude-good",+ "#!/bin/sh\necho '9.9.9 (Claude Code)'\n",+ );+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &good);+ let status = harness+ .rpc(73_001, "openhuman.inference_claude_code_status", json!({}))+ .await;+ let status = payload(&status, "claude_code_status ok");+ assert_eq!(+ status.get("status"),+ Some(&json!("ok")),+ "a modern CLI must classify as ok: {status}"+ );+ assert_eq!(status.get("version"), Some(&json!("9.9.9")));+ assert_eq!(+ status.get("path").and_then(Value::as_str),+ Some(good.display().to_string().as_str()),+ "the resolved binary path must be reported: {status}"+ );+ }++ // `outdated` — below the minimum. The reply must carry the minimum so the+ // UI can tell the user what to upgrade to.+ let old = write_claude_stub(+ &stub_dir,+ "claude-old",+ "#!/bin/sh\necho '1.0.1 (Claude Code)'\n",+ );+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &old);+ let status = harness+ .rpc(73_002, "openhuman.inference_claude_code_status", json!({}))+ .await;+ let status = payload(&status, "claude_code_status outdated");+ assert_eq!(status.get("status"), Some(&json!("outdated")));+ assert_eq!(status.get("version"), Some(&json!("1.0.1")));+ assert_eq!(+ status.get("min_required"),+ Some(&json!("2.0.0")),+ "an outdated verdict must name the required version: {status}"+ );+ }++ // `unusable` — the binary exists but fails. A non-zero exit must not be+ // reported as "not installed": telling a user to install what they already+ // have is the wrong instruction.+ let broken = write_claude_stub(+ &stub_dir,+ "claude-broken",+ "#!/bin/sh\necho 'boom' >&2\nexit 3\n",+ );+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &broken);+ let status = harness+ .rpc(73_003, "openhuman.inference_claude_code_status", json!({}))+ .await;+ let status = payload(&status, "claude_code_status unusable");+ assert_eq!(status.get("status"), Some(&json!("unusable")));+ let reason = status+ .get("reason")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ reason.contains("non-zero exit"),+ "an unusable verdict must explain itself: {status}"+ );+ assert!(+ reason.contains("boom"),+ "the CLI's own stderr must reach the reason: {status}"+ );+ }++ // `not_installed` — nothing on PATH and no override.+ let empty_path = harness.home().join("empty-path");+ std::fs::create_dir_all(&empty_path).expect("create empty path dir");+ {+ let _cli = EnvVarGuard::unset("OPENHUMAN_CLAUDE_CLI");+ let _path = EnvVarGuard::set_to_path("PATH", &empty_path);+ let status = harness+ .rpc(73_004, "openhuman.inference_claude_code_status", json!({}))+ .await;+ assert_eq!(+ payload(&status, "claude_code_status not installed").get("status"),+ Some(&json!("not_installed")),+ "no binary anywhere must classify as not_installed"+ );+ }++ // An override pointing at a path that does not exist falls back to the+ // PATH lookup rather than reporting `unusable` on a phantom binary.+ {+ let _cli = EnvVarGuard::set(+ "OPENHUMAN_CLAUDE_CLI",+ harness.home().join("nope/claude").to_str().unwrap(),+ );+ let _path = EnvVarGuard::set_to_path("PATH", &empty_path);+ let status = harness+ .rpc(73_005, "openhuman.inference_claude_code_status", json!({}))+ .await;+ assert_eq!(+ payload(&status, "claude_code_status bad override").get("status"),+ Some(&json!("not_installed")),+ "a non-existent override must not be treated as an installed binary"+ );+ }++ harness.join.abort();+}++// ── inference.claude_code_auth_status ──────────────────────────────────────++#[cfg(unix)]+#[tokio::test]+async fn inference_claude_code_auth_status_prefers_the_env_key_then_reads_the_cli() {+ let _lock = env_lock();+ let harness = setup("").await;+ let stub_dir = harness.home().join("stub-auth-cli");++ // `ANTHROPIC_API_KEY` wins outright — the spawned CLI would inherit it, so+ // it decides who authenticates regardless of any stored session. Assert it+ // short-circuits: the stub below would report a *subscription* if reached.+ let logged_in = write_claude_stub(+ &stub_dir,+ "claude-loggedin",+ "#!/bin/sh\necho '{\"loggedIn\":true,\"authMethod\":\"claude.ai\",\+ \"email\":\"[email protected]\",\"subscriptionType\":\"max\"}'\n",+ );+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &logged_in);+ let _key = EnvVarGuard::set("ANTHROPIC_API_KEY", "sk-ant-e2e");+ let auth = harness+ .rpc(+ 74_001,+ "openhuman.inference_claude_code_auth_status",+ json!({}),+ )+ .await;+ let auth = payload(&auth, "auth_status api key");+ assert_eq!(+ auth.get("source"),+ Some(&json!("api_key_env")),+ "an env API key must win over a logged-in CLI: {auth}"+ );+ assert!(+ auth.get("account_email").is_none(),+ "the api-key branch must not report a subscription account: {auth}"+ );+ assert!(+ auth.get("last_checked")+ .and_then(Value::as_u64)+ .is_some_and(|t| t > 0),+ "every probe must stamp when it ran: {auth}"+ );+ }++ // A blank key is not a key — the probe must fall through to the CLI.+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &logged_in);+ let _key = EnvVarGuard::set("ANTHROPIC_API_KEY", " ");+ let auth = harness+ .rpc(+ 74_002,+ "openhuman.inference_claude_code_auth_status",+ json!({}),+ )+ .await;+ let auth = payload(&auth, "auth_status blank key");+ assert_eq!(+ auth.get("source"),+ Some(&json!("subscription")),+ "a whitespace-only key must not be mistaken for a credential: {auth}"+ );+ assert_eq!(+ auth.get("account_email"),+ Some(&json!("[email protected]")),+ "the subscription branch must carry the account email: {auth}"+ );+ assert_eq!(auth.get("subscription_type"), Some(&json!("max")));+ }++ // Signed out — the CLI says so explicitly, and only then may we say so.+ let logged_out = write_claude_stub(+ &stub_dir,+ "claude-loggedout",+ "#!/bin/sh\necho '{\"loggedIn\":false}'\n",+ );+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &logged_out);+ let auth = harness+ .rpc(+ 74_003,+ "openhuman.inference_claude_code_auth_status",+ json!({}),+ )+ .await;+ assert_eq!(+ payload(&auth, "auth_status signed out").get("source"),+ Some(&json!("none")),+ "an explicit loggedIn:false is the only thing that may read as signed out"+ );+ }++ // A CLI too old for `auth status` exits non-zero. That must be `unknown`,+ // never `none` — telling a signed-in user they are signed out because their+ // binary predates a subcommand is the documented anti-goal.+ let ancient = write_claude_stub(+ &stub_dir,+ "claude-ancient",+ "#!/bin/sh\necho 'unknown command' >&2\nexit 1\n",+ );+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &ancient);+ let auth = harness+ .rpc(+ 74_004,+ "openhuman.inference_claude_code_auth_status",+ json!({}),+ )+ .await;+ assert_eq!(+ payload(&auth, "auth_status ancient cli").get("source"),+ Some(&json!("unknown")),+ "a CLI that cannot answer must read as unknown, never as signed out"+ );+ }++ // Unparseable output is the same story.+ let garbage = write_claude_stub(+ &stub_dir,+ "claude-garbage",+ "#!/bin/sh\necho 'not json at all'\n",+ );+ {+ let _cli = EnvVarGuard::set_to_path("OPENHUMAN_CLAUDE_CLI", &garbage);+ let auth = harness+ .rpc(+ 74_005,+ "openhuman.inference_claude_code_auth_status",+ json!({}),+ )+ .await;+ assert_eq!(+ payload(&auth, "auth_status garbage").get("source"),+ Some(&json!("unknown")),+ "unparseable CLI output must read as unknown, never as signed out"+ );+ }++ harness.join.abort();+}++// ── inference.claude_code_settings / set_full_access ───────────────────────++#[tokio::test]+async fn inference_claude_code_full_access_toggle_round_trips_through_the_workspace() {+ let _lock = env_lock();+ let harness = setup("").await;++ // The safe posture is the default, and it must be the default on a fresh+ // install with no settings file at all.+ let initial = harness+ .rpc(+ 75_001,+ "openhuman.inference_claude_code_settings",+ json!({}),+ )+ .await;+ assert_eq!(+ payload(&initial, "claude_code_settings default").get("full_access"),+ Some(&json!(false)),+ "full access must default OFF — this gates bypassPermissions + Bash"+ );++ // Enable it, and confirm the change is persisted rather than merely echoed.+ let enabled = harness+ .rpc(+ 75_002,+ "openhuman.inference_claude_code_set_full_access",+ json!({ "enabled": true }),+ )+ .await;+ assert_eq!(+ payload(&enabled, "set_full_access true").get("full_access"),+ Some(&json!(true))+ );+ // NOTE: despite the RPC description ("stored under the workspace") and the+ // helper's name (`workspace_dir_from_config`), the file lands in the+ // **config** directory — the function returns `config.config_path.parent()`,+ // i.e. `~/.openhuman`. Asserting the real location so this test documents+ // where the toggle actually is; the wording mismatch is filed in+ // ~/tinyhuman/bugs/e2e-wave-inference-stale-vision-and-workspace-docs.md.+ let settings_file = harness+ .home()+ .join(".openhuman")+ .join("claude_code_settings.json");+ assert!(+ settings_file.exists(),+ "the toggle must land on disk at {}",+ settings_file.display()+ );+ let on_disk: Value =+ serde_json::from_str(&std::fs::read_to_string(&settings_file).expect("read settings file"))+ .expect("settings file must be JSON");+ assert_eq!(+ on_disk.get("full_access"),+ Some(&json!(true)),+ "the persisted file must agree with the reply: {on_disk}"+ );++ let read_back = harness+ .rpc(+ 75_003,+ "openhuman.inference_claude_code_settings",+ json!({}),+ )+ .await;+ assert_eq!(+ payload(&read_back, "claude_code_settings after enable").get("full_access"),+ Some(&json!(true))+ );++ // …and back off again.+ let disabled = harness+ .rpc(+ 75_004,+ "openhuman.inference_claude_code_set_full_access",+ json!({ "enabled": false }),+ )+ .await;+ assert_eq!(+ payload(&disabled, "set_full_access false").get("full_access"),+ Some(&json!(false))+ );+ let read_back = harness+ .rpc(+ 75_005,+ "openhuman.inference_claude_code_settings",+ json!({}),+ )+ .await;+ assert_eq!(+ payload(&read_back, "claude_code_settings after disable").get("full_access"),+ Some(&json!(false))+ );++ // A corrupt settings file must fail *safe* — defaults, not full access.+ std::fs::write(&settings_file, "{ this is not json").expect("corrupt the settings file");+ let corrupt = harness+ .rpc(+ 75_006,+ "openhuman.inference_claude_code_settings",+ json!({}),+ )+ .await;+ assert_eq!(+ payload(&corrupt, "claude_code_settings corrupt").get("full_access"),+ Some(&json!(false)),+ "a corrupt settings file must never fail open into bypassPermissions"+ );++ // Failure path: `enabled` is required and must be a bool.+ let missing = harness+ .rpc(+ 75_007,+ "openhuman.inference_claude_code_set_full_access",+ json!({}),+ )+ .await;+ assert!(+ err_message(&missing, "set_full_access missing")+ .contains("missing required param 'enabled'"),+ "an omitted `enabled` must be refused by the schema gate"+ );++ let wrong_type = harness+ .rpc(+ 75_008,+ "openhuman.inference_claude_code_set_full_access",+ json!({ "enabled": "yes" }),+ )+ .await;+ // Same boundary type-check as `resolve_model` above — a string is not+ // coerced into a bool, which for *this* param would mean silently turning+ // on `bypassPermissions`.+ assert_eq!(+ err_message(&wrong_type, "set_full_access string"),+ "invalid type for param 'enabled' in inference.claude_code_set_full_access: \+ expected bool, got string",+ "a non-bool `enabled` must be rejected, not coerced to true"+ );++ harness.join.abort();+}++// ── inference.openai_oauth_import_codex_cli ────────────────────────────────++#[tokio::test]+async fn inference_openai_oauth_import_codex_cli_imports_a_real_auth_file() {+ let _lock = env_lock();+ let harness = setup("").await;++ let codex_home = harness.home().join("codex-home");+ std::fs::create_dir_all(&codex_home).expect("create codex home");+ let _codex = EnvVarGuard::set_to_path("CODEX_HOME", &codex_home);++ // No `auth.json` yet — the user never ran `codex login`. The error must be+ // the actionable one, because this is the common case the UI renders.+ let absent = harness+ .rpc(+ 76_001,+ "openhuman.inference_openai_oauth_import_codex_cli",+ json!({}),+ )+ .await;+ let message = err_message(&absent, "import_codex_cli absent");+ assert!(+ message.contains("Could not read Codex CLI auth"),+ "a missing auth.json must say what it could not read: {message}"+ );+ assert!(+ message.contains("codex login"),+ "the error must tell the user the one command that fixes it: {message}"+ );++ // A file that is not JSON.+ std::fs::write(codex_home.join("auth.json"), "not json").expect("write bad auth.json");+ let unparseable = harness+ .rpc(+ 76_002,+ "openhuman.inference_openai_oauth_import_codex_cli",+ json!({}),+ )+ .await;+ assert!(+ err_message(&unparseable, "import_codex_cli unparseable")+ .contains("Could not parse Codex CLI auth"),+ "a corrupt auth.json must be reported as a parse failure, not a missing file"+ );++ // Valid JSON with no tokens at all.+ std::fs::write(+ codex_home.join("auth.json"),+ json!({ "auth_mode": "chatgpt" }).to_string(),+ )+ .expect("write tokenless auth.json");+ let tokenless = harness+ .rpc(+ 76_003,+ "openhuman.inference_openai_oauth_import_codex_cli",+ json!({}),+ )+ .await;+ assert!(+ err_message(&tokenless, "import_codex_cli tokenless").contains("has no tokens"),+ "a logged-out codex install must be distinguished from a corrupt one"+ );++ // The happy path: a real-shaped auth.json. The import must both report the+ // connection and leave a stored OAuth profile that `openai_oauth_status`+ // can see — an import that "succeeds" without persisting is the failure+ // this pair of assertions exists to catch.+ let access_token = unsigned_jwt(json!({+ "https://api.openai.com/auth": { "chatgpt_account_id": "acct_e2e" },+ "sub": "acct_subject",+ "exp": (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp(),+ }));+ std::fs::write(+ codex_home.join("auth.json"),+ json!({+ "auth_mode": "chatgpt",+ "tokens": {+ "access_token": access_token,+ "refresh_token": "codex-refresh-e2e",+ "id_token": "codex-id-e2e",+ }+ })+ .to_string(),+ )+ .expect("write valid auth.json");++ let imported = harness+ .rpc(+ 76_004,+ "openhuman.inference_openai_oauth_import_codex_cli",+ json!({}),+ )+ .await;+ let imported = payload(&imported, "import_codex_cli ok");+ assert_eq!(imported.get("connected"), Some(&json!(true)));+ assert_eq!(+ imported.get("provider"),+ Some(&json!("provider:openai")),+ "the credential-store provider key is the namespaced `provider:openai`, \+ not the bare slug: {imported}"+ );+ assert_eq!(imported.get("authMethod"), Some(&json!("oauth")));+ assert_eq!(+ imported.get("source"),+ Some(&json!("codex_cli")),+ "the import must record where the credential came from: {imported}"+ );+ let profile_id = imported+ .get("profileId")+ .and_then(Value::as_str)+ .expect("an imported profile id")+ .to_string();+ assert!(!profile_id.is_empty());++ // The credential really landed: the status RPC now reports connected, with+ // the same profile.+ let status = harness+ .rpc(76_005, "openhuman.inference_openai_oauth_status", json!({}))+ .await;+ let status = payload(&status, "openai_oauth_status after import");+ assert_eq!(+ status.get("connected"),+ Some(&json!(true)),+ "an import that does not persist is not an import: {status}"+ );+ assert_eq!(status.get("profileId"), Some(&json!(profile_id)));+ assert_eq!(status.get("authMethod"), Some(&json!("oauth")));+ assert!(+ status.get("expiresAt").is_some(),+ "the JWT `exp` must be carried onto the stored token set: {status}"+ );++ // Clean up the stored credential so no later suite in this binary inherits+ // a connected OpenAI OAuth profile.+ let _ = harness+ .rpc(+ 76_006,+ "openhuman.inference_openai_oauth_disconnect",+ json!({}),+ )+ .await;++ harness.join.abort();+}diff --git a/tests/raw_coverage/sandbox_runtime_platform_e2e.rs b/tests/raw_coverage/sandbox_runtime_platform_e2e.rsnew file mode 100644index 0000000000..cf648c5c22--- /dev/null+++ b/tests/raw_coverage/sandbox_runtime_platform_e2e.rs@@ -0,0 +1,1573 @@+//! JSON-RPC E2E coverage for the platform-runtime namespaces that had **zero**+//! `tests/**/*_e2e.rs` reach before this file: `sandbox`, `worktree`,+//! `http_host`, `workspace`, and `modules`.+//!+//! Every case dispatches over the real `build_core_http_router` HTTP surface —+//! the same transport the desktop shell uses — and asserts on the *content* of+//! the reply, not merely that it is `Ok`. Each namespace gets at least one+//! failure path, because that is where the bugs in an untested controller live.+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target, not a+//! target of its own — `build.rs` globs `tests/raw_coverage/` and generates the+//! `mod` list, so adding the file is all the registration there is.+//!+//! Run with:+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)"`+//!+//! Isolation rules this file obeys:+//! - `HOME`, `OPENHUMAN_WORKSPACE`, `OPENHUMAN_ACTION_DIR` and `PATH` are+//! process-global, and every aggregated suite shares this one process, so+//! every case takes [`env_lock`] — which is a reference to the **crate-wide**+//! `SHARED_ENV_LOCK`, not a private mutex — and restores via [`EnvVarGuard`].+//! A file-local lock would compile, pass alone, and race another worker's+//! suite under load.+//! - `[modules] enabled = false` in the test config: `modules_load` with modules+//! enabled would try to *download* a pinned release artifact. The disabled+//! branch is the one an offline CI can assert on deterministically.+//! - `sandbox_cleanup_orphans` shells out to `docker kill`. Both cases below+//! point `PATH` at a temp dir so the real daemon is never reached — a test+//! that kills the developer's containers is not a test.++use std::net::SocketAddr;+use std::path::Path;+use std::process::Command;+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use axum::http::header::AUTHORIZATION;+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;++const TEST_RPC_TOKEN: &str = "sandbox-runtime-platform-e2e-token";++static AUTH_INIT: OnceLock<()> = OnceLock::new();++/// Every aggregated suite shares one process, so a private env lock would not+/// mutually exclude with anyone else's. Bind to the crate-wide mutex.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++struct EnvVarGuard {+ key: &'static str,+ old: Option<std::ffi::OsString>,+}++impl EnvVarGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let old = std::env::var_os(key);+ std::env::set_var(key, path.as_os_str());+ Self { key, old }+ }++ fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var_os(key);+ std::env::set_var(key, value);+ Self { key, old }+ }++ fn unset(key: &'static str) -> Self {+ let old = std::env::var_os(key);+ std::env::remove_var(key);+ Self { key, old }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+}++fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++/// Initialise the core RPC bearer and return **the token this process actually+/// validates against**.+///+/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token`+/// is deliberately idempotent, so inside the aggregated `raw_coverage_all`+/// binary the *first* suite to initialise pins the bearer for every later one.+/// Sending our own `TEST_RPC_TOKEN` unconditionally would therefore 401 for+/// whichever suites lose that race — an order-dependent failure. Ask for the+/// active token instead of assuming ours won.+/// See `~/tinyhuman/bugs/e2e-wave-raw-coverage-shared-rpc-token.md`.+fn ensure_rpc_auth() -> String {+ AUTH_INIT.get_or_init(|| {+ if std::env::var(CORE_TOKEN_ENV_VAR)+ .ok()+ .filter(|v| !v.trim().is_empty())+ .is_none()+ {+ std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);+ }+ let token_dir = std::env::temp_dir().join("openhuman-sandbox-runtime-platform-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+ get_rpc_token()+ .expect("core RPC token must be initialised before serving")+ .to_string()+}++async fn serve_rpc() -> (+ SocketAddr,+ String,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ let token = ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind rpc listener");+ let addr = listener.local_addr().expect("rpc listener addr");+ let router = build_core_http_router(false);+ let join = tokio::spawn(async move { axum::serve(listener, router).await });+ (addr, token, join)+}++/// `[modules] enabled = false` is load-bearing, not incidental — see the module+/// docs. `[local_ai] enabled = false` and `memory.provider = "none"` keep the+/// config load from reaching for a model or an embedding endpoint.+fn write_min_config(openhuman_dir: &Path) {+ std::fs::create_dir_all(openhuman_dir).expect("create .openhuman");+ let cfg = r#"api_url = "http://127.0.0.1:9"+default_model = "e2e-model"+default_temperature = 0.2++[secrets]+encrypt = false++[local_ai]+enabled = false++[modules]+enabled = false+allow_download = false++[memory]+provider = "none"+embedding_provider = "none"+embedding_model = "none"+embedding_dimensions = 0++[memory_tree]+embedding_strict = false+"#;+ std::fs::write(openhuman_dir.join("config.toml"), cfg).expect("write config.toml");+ let _: openhuman_core::openhuman::config::Config =+ toml::from_str(cfg).expect("test config must match schema");+}++struct TestHarness {+ tmp: TempDir,+ _guards: Vec<EnvVarGuard>,+ rpc_base: String,+ token: String,+ join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++impl TestHarness {+ fn home(&self) -> &Path {+ self.tmp.path()+ }++ fn workspace(&self) -> std::path::PathBuf {+ self.tmp.path().join("workspace")+ }++ /// Dispatch one JSON-RPC call over the harness's router with the bearer+ /// this process actually validates against.+ async fn rpc(&self, id: i64, method: &str, params: Value) -> Value {+ rpc_with_token(&self.rpc_base, &self.token, id, method, params).await+ }+}++/// Boot a router over a fresh temp `HOME`. `action_dir` pins+/// `OPENHUMAN_ACTION_DIR` (the repo root every `worktree` op anchors on);+/// `None` points it at an empty non-git directory, which is the "user has not+/// opened a repo" state `worktree_list` must degrade over.+async fn setup(action_dir: Option<&Path>) -> TestHarness {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");+ write_min_config(&openhuman_home);+ let workspace = home.join("workspace");+ std::fs::create_dir_all(&workspace).expect("create workspace");+ let empty_action_dir = home.join("no-repo");+ std::fs::create_dir_all(&empty_action_dir).expect("create action dir");++ let guards = vec![+ EnvVarGuard::set_to_path("HOME", home),+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),+ EnvVarGuard::set_to_path(+ "OPENHUMAN_ACTION_DIR",+ action_dir.unwrap_or(&empty_action_dir),+ ),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let (addr, token, join) = serve_rpc().await;+ TestHarness {+ tmp,+ _guards: guards,+ rpc_base: format!("http://{addr}"),+ token,+ join,+ }+}++async fn rpc_with_token(+ rpc_base: &str,+ token: &str,+ id: i64,+ method: &str,+ params: Value,+) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("client");+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {token}"))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": method,+ "params": params,+ }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+}++fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {+ if let Some(error) = value.get("error") {+ panic!("{context}: unexpected JSON-RPC error: {error}");+ }+ value+ .get("result")+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"))+}++/// The JSON-RPC error *message* for a call that must fail. Panics with the full+/// envelope when the call unexpectedly succeeded — a controller that silently+/// accepts bad input is exactly what these cases exist to catch.+fn err_message(value: &Value, context: &str) -> String {+ let error = value+ .get("error")+ .unwrap_or_else(|| panic!("{context}: expected JSON-RPC error, got: {value}"));+ error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{context}: error without message: {error}"))+ .to_string()+}++/// Controllers wrap their payload in `RpcOutcome::into_cli_compatible_json`,+/// which nests the value under `result` and carries `logs` alongside. Handlers+/// that return a bare `serde_json::json!` do not. Unwrap one level when it is+/// there so a case can assert on the payload either way.+fn payload<'a>(value: &'a Value, context: &str) -> &'a Value {+ let result = ok(value, context);+ result.get("result").unwrap_or(result)+}++/// A directory containing only the executables this test wants found. Used to+/// keep `docker` off `PATH` (or to substitute a stub for it).+fn stub_bin_dir(tmp: &Path, name: &str, script: Option<&str>) -> std::path::PathBuf {+ let dir = tmp.join(format!("stubbin-{name}"));+ std::fs::create_dir_all(&dir).expect("create stub bin dir");+ if let Some(body) = script {+ let path = dir.join(name);+ std::fs::write(&path, body).expect("write stub");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))+ .expect("chmod stub");+ }+ }+ dir+}++// ── sandbox ────────────────────────────────────────────────────────────────++#[tokio::test]+async fn sandbox_resolve_policy_maps_each_mode_and_remote_flag_to_a_backend() {+ let _lock = env_lock();+ let harness = setup(None).await;++ // `none` → no backend, network unrestricted.+ let none = harness+ .rpc(+ 60_001,+ "openhuman.sandbox_resolve_policy",+ json!({ "sandbox_mode": "none" }),+ )+ .await;+ let none = payload(&none, "resolve_policy none");+ assert_eq!(none.get("backend"), Some(&json!("none")));+ assert_eq!(none.get("allow_network"), Some(&json!(true)));+ assert_eq!(+ none.get("docker_overrides"),+ Some(&Value::Null),+ "a non-docker backend must not carry docker overrides: {none}"+ );++ // `read_only` collapses onto the same backend but is a distinct input.+ let read_only = harness+ .rpc(+ 60_002,+ "openhuman.sandbox_resolve_policy",+ json!({ "sandbox_mode": "read_only" }),+ )+ .await;+ assert_eq!(+ payload(&read_only, "resolve_policy read_only").get("backend"),+ Some(&json!("none"))+ );++ // `sandboxed` on a local session → the OS jail, network still allowed.+ let local = harness+ .rpc(+ 60_003,+ "openhuman.sandbox_resolve_policy",+ json!({ "sandbox_mode": "sandboxed", "is_remote": false }),+ )+ .await;+ let local = payload(&local, "resolve_policy sandboxed/local");+ assert_eq!(local.get("backend"), Some(&json!("local")));+ assert_eq!(local.get("allow_network"), Some(&json!(true)));++ // `sandboxed` + remote → Docker, and network is cut. This is the security+ // decision the whole namespace exists to make, so assert both halves.+ let remote = harness+ .rpc(+ 60_004,+ "openhuman.sandbox_resolve_policy",+ json!({ "sandbox_mode": "sandboxed", "is_remote": true }),+ )+ .await;+ let remote = payload(&remote, "resolve_policy sandboxed/remote");+ assert_eq!(remote.get("backend"), Some(&json!("docker")));+ assert_eq!(+ remote.get("allow_network"),+ Some(&json!(false)),+ "a remote sandboxed session must not get outbound network: {remote}"+ );+ let overrides = remote+ .get("docker_overrides")+ .unwrap_or_else(|| panic!("docker backend must carry overrides: {remote}"));+ assert!(+ overrides.get("image").and_then(Value::as_str).is_some(),+ "docker overrides must name an image: {overrides}"+ );+ assert_eq!(overrides.get("read_only_rootfs"), Some(&json!(true)));++ // An unknown mode string degrades to `none` rather than erroring — assert+ // the documented degradation so a future strict-parse change is visible.+ let unknown = harness+ .rpc(+ 60_005,+ "openhuman.sandbox_resolve_policy",+ json!({ "sandbox_mode": "not-a-mode" }),+ )+ .await;+ assert_eq!(+ payload(&unknown, "resolve_policy unknown").get("backend"),+ Some(&json!("none"))+ );++ // Failure path: the required param is enforced at the dispatch boundary+ // (`core::all::validate_params`), before the handler — which would+ // otherwise have defaulted it to `none` and answered a policy the caller+ // never asked for.+ let missing = harness+ .rpc(60_006, "openhuman.sandbox_resolve_policy", json!({}))+ .await;+ assert!(+ err_message(&missing, "resolve_policy missing mode")+ .contains("missing required param 'sandbox_mode'"),+ "an omitted `sandbox_mode` must be refused, not silently defaulted"+ );++ // …and the same gate rejects a param the schema does not declare, so a+ // stale frontend cannot smuggle an ignored field past it.+ let unknown_param = harness+ .rpc(+ 60_007,+ "openhuman.sandbox_resolve_policy",+ json!({ "sandbox_mode": "none", "not_a_field": true }),+ )+ .await;+ assert!(+ err_message(&unknown_param, "resolve_policy unknown param")+ .contains("unknown param 'not_a_field' for sandbox.resolve_policy"),+ "an undeclared param must be refused by name"+ );++ harness.join.abort();+}++#[tokio::test]+async fn sandbox_validate_policy_flags_host_network_and_dangerous_roots() {+ let _lock = env_lock();+ let harness = setup(None).await;++ // A clean policy validates.+ let safe = harness+ .rpc(+ 60_010,+ "openhuman.sandbox_validate_policy",+ json!({+ "policy": {+ "backend": "docker",+ "workspace_root": "/home/user/project",+ "read_only_mounts": ["/usr/lib"],+ "allow_network": false,+ "env_passthrough": [],+ "docker_overrides": { "network": "bridge", "extra_caps_drop": [] }+ }+ }),+ )+ .await;+ let safe = payload(&safe, "validate_policy safe");+ assert_eq!(safe.get("valid"), Some(&json!(true)));+ assert_eq!(safe.get("issues"), Some(&json!([])));++ // Host networking + a docker-socket mount + `/` as the workspace root:+ // three independent findings, all of which must be reported.+ let unsafe_policy = harness+ .rpc(+ 60_011,+ "openhuman.sandbox_validate_policy",+ json!({+ "policy": {+ "backend": "docker",+ "workspace_root": "/",+ "read_only_mounts": ["/var/run/docker.sock", "/etc"],+ "allow_network": true,+ "env_passthrough": [],+ "docker_overrides": { "network": "host", "extra_caps_drop": [] }+ }+ }),+ )+ .await;+ let unsafe_payload = payload(&unsafe_policy, "validate_policy unsafe");+ assert_eq!(unsafe_payload.get("valid"), Some(&json!(false)));+ let issues = unsafe_payload+ .get("issues")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("issues must be an array: {unsafe_payload}"));+ let joined = issues+ .iter()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>()+ .join(" | ");+ assert!(+ joined.contains("host network"),+ "host networking must be flagged: {joined}"+ );+ assert!(+ joined.contains("/var/run/docker.sock"),+ "the docker socket mount must be flagged: {joined}"+ );+ assert!(+ joined.contains("/etc"),+ "the /etc mount must be flagged: {joined}"+ );+ assert!(+ joined.contains("Workspace root is a dangerous path"),+ "`/` as the workspace root must be flagged: {joined}"+ );+ assert_eq!(+ issues.len(),+ 4,+ "expected exactly the four findings above: {joined}"+ );++ // Failure path: a policy that is not a SandboxPolicy at all.+ let bad = harness+ .rpc(+ 60_012,+ "openhuman.sandbox_validate_policy",+ json!({ "policy": { "backend": "not-a-backend" } }),+ )+ .await;+ let message = err_message(&bad, "validate_policy bad backend");+ assert!(+ message.contains("Invalid policy"),+ "unparseable policy must be rejected, got: {message}"+ );++ // Failure path: the required `policy` param omitted entirely.+ let missing = harness+ .rpc(60_013, "openhuman.sandbox_validate_policy", json!({}))+ .await;+ let message = err_message(&missing, "validate_policy missing");+ assert!(+ message.contains("missing required param 'policy'"),+ "a missing `policy` is caught by the dispatch-boundary gate, got: {message}"+ );++ harness.join.abort();+}++#[tokio::test]+async fn sandbox_status_reports_a_backend_handle_for_each_requested_kind() {+ let _lock = env_lock();+ let harness = setup(None).await;++ let none = harness+ .rpc(+ 60_020,+ "openhuman.sandbox_status",+ json!({ "backend": "none" }),+ )+ .await;+ let none = payload(&none, "sandbox_status none");+ assert_eq!(+ none.get("kind"),+ Some(&json!("none")),+ "backend=none must report the none handle: {none}"+ );+ assert!(+ none.get("status").is_some(),+ "a backend handle must carry a status: {none}"+ );++ // `local` resolves the OS jail. Availability is host-dependent (Landlock on+ // Linux, Seatbelt on macOS), so assert the handle's identity, not its+ // verdict.+ let local = harness+ .rpc(+ 60_021,+ "openhuman.sandbox_status",+ json!({ "backend": "local" }),+ )+ .await;+ let local = payload(&local, "sandbox_status local");+ assert_eq!(local.get("kind"), Some(&json!("local")));++ // An unrecognised backend string falls back to `none` rather than erroring.+ let bogus = harness+ .rpc(+ 60_022,+ "openhuman.sandbox_status",+ json!({ "backend": "kubernetes" }),+ )+ .await;+ assert_eq!(+ payload(&bogus, "sandbox_status bogus").get("kind"),+ Some(&json!("none")),+ "an unknown backend name must degrade to `none`, not error"+ );++ harness.join.abort();+}++/// What `sandbox_status` *should* answer for a local backend whose OS jail is+/// not available on this host.+///+/// Ignored because it fails today: `ops::create_sandbox_backend` returns+/// `SandboxStatus::Ready` from **both** arms of its availability check, so the+/// reply says the confinement is ready on a host where it degraded to a noop.+/// See `~/tinyhuman/bugs/e2e-wave-sandbox-local-jail-always-reports-ready.md`.+/// Un-ignore when that is fixed; the assertion below is the contract.+#[tokio::test]+#[ignore = "documents a bug: local jail unavailability is reported as `ready` \+ (bugs/e2e-wave-sandbox-local-jail-always-reports-ready.md)"]+async fn sandbox_status_local_backend_reports_an_unavailable_jail_as_not_ready() {+ let _lock = env_lock();+ let harness = setup(None).await;++ let local = harness+ .rpc(+ 60_025,+ "openhuman.sandbox_status",+ json!({ "backend": "local" }),+ )+ .await;+ let local = payload(&local, "sandbox_status local");+ assert_eq!(local.get("kind"), Some(&json!("local")));++ // `is_available` lives on the `JailBackend` trait, which must be in scope+ // for the method call on the returned `Arc<dyn JailBackend>`.+ use openhuman_core::openhuman::sandbox::cwd_jail::{default_backend, JailBackend as _};+ let jail_available = default_backend().is_available();+ if jail_available {+ assert_eq!(local.get("status"), Some(&json!("ready")));+ } else {+ assert_ne!(+ local.get("status"),+ Some(&json!("ready")),+ "an unavailable OS jail must not be reported as ready — the caller \+ would believe commands are confined when they run unconfined: {local}"+ );+ }++ harness.join.abort();+}++#[tokio::test]+async fn sandbox_cleanup_orphans_counts_zero_with_a_stub_docker_and_errors_without_one() {+ let _lock = env_lock();+ let harness = setup(None).await;++ // Happy path: a `docker` that lists nothing. The handler must report zero+ // cleaned — and must never reach `docker kill`, which is why the stub is a+ // stub. `docker ps -q` printing nothing is exactly the no-orphans case.+ let stub_dir = stub_bin_dir(harness.home(), "docker", Some("#!/bin/sh\nexit 0\n"));+ {+ let _path = EnvVarGuard::set_to_path("PATH", &stub_dir);+ let clean = harness+ .rpc(60_030, "openhuman.sandbox_cleanup_orphans", json!({}))+ .await;+ assert_eq!(+ payload(&clean, "cleanup_orphans stub").get("cleaned"),+ Some(&json!(0)),+ "a docker that lists no containers must report zero cleaned"+ );+ }++ // Failure path: no `docker` on PATH at all. The spawn error must surface as+ // an RPC error rather than a silent zero — "cleaned 0" and "could not look"+ // are different answers and the UI must be able to tell them apart.+ let empty_dir = stub_bin_dir(harness.home(), "nodocker", None);+ {+ let _path = EnvVarGuard::set_to_path("PATH", &empty_dir);+ let failed = harness+ .rpc(60_031, "openhuman.sandbox_cleanup_orphans", json!({}))+ .await;+ let message = err_message(&failed, "cleanup_orphans no docker");+ assert!(+ message.contains("Cleanup failed"),+ "a missing docker binary must surface as a cleanup failure, got: {message}"+ );+ }++ harness.join.abort();+}++// ── worktree ───────────────────────────────────────────────────────────────++/// Build a real git repo with one committed file and an isolated worker+/// worktree under the `.claude/worktrees` convention path the RPC manages.+/// Returns the repo root and the managed worktree path.+fn init_repo_with_managed_worktree(root: &Path) -> (std::path::PathBuf, std::path::PathBuf) {+ let run = |args: &[&str], cwd: &Path| {+ let out = Command::new("git")+ .args(args)+ .current_dir(cwd)+ // A developer's global hooks / gpg signing config would otherwise+ // decide whether this fixture builds.+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .env("GIT_AUTHOR_NAME", "e2e")+ .env("GIT_AUTHOR_EMAIL", "[email protected]")+ .env("GIT_COMMITTER_NAME", "e2e")+ .env("GIT_COMMITTER_EMAIL", "[email protected]")+ .output()+ .unwrap_or_else(|e| panic!("git {args:?}: {e}"));+ assert!(+ out.status.success(),+ "git {args:?} failed: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ };++ // Canonicalise before git ever sees the path: on macOS a tempdir lives+ // under `/var/folders/…`, `/var` is a symlink to `/private/var`, and+ // `git worktree list --porcelain` reports the *resolved* path. Comparing a+ // symlinked path against a resolved one is how this fixture would fail for+ // a reason that has nothing to do with the controller under test.+ let repo = root.join("repo");+ std::fs::create_dir_all(&repo).expect("create repo dir");+ let repo = std::fs::canonicalize(&repo).expect("canonicalise repo root");+ run(&["init", "-b", "main", "."], &repo);+ std::fs::write(repo.join("README.md"), "hello\n").expect("write README");+ run(&["add", "README.md"], &repo);+ run(&["commit", "--no-gpg-sign", "-m", "initial"], &repo);++ let worktree = repo.join(".claude").join("worktrees").join("worker-1");+ run(+ &[+ "worktree",+ "add",+ "-b",+ "worker/1",+ worktree.to_str().expect("worktree path utf-8"),+ ],+ &repo,+ );+ (repo, worktree)+}++#[tokio::test]+async fn worktree_list_status_diff_and_remove_round_trip_over_a_real_repo() {+ let outer = tempdir().expect("tempdir");+ let (repo, worktree) = init_repo_with_managed_worktree(outer.path());++ let _lock = env_lock();+ let harness = setup(Some(&repo)).await;++ // list — the managed worktree is discovered and reported with its branch.+ let listed = harness+ .rpc(61_001, "openhuman.worktree_list", json!({}))+ .await;+ let listed = payload(&listed, "worktree_list");+ let worktrees = listed+ .get("worktrees")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("worktrees must be an array: {listed}"));+ assert_eq!(+ worktrees.len(),+ 1,+ "only the managed worker worktree is listed, never the main checkout: {listed}"+ );+ assert_eq!(+ worktrees[0].get("branch"),+ Some(&json!("worker/1")),+ "the worktree's branch must be reported: {listed}"+ );+ assert_eq!(+ worktrees[0].get("isDirty"),+ Some(&json!(false)),+ "a freshly added worktree is clean: {listed}"+ );+ assert_eq!(+ listed.get("overlaps"),+ Some(&json!([])),+ "one worktree cannot overlap with itself: {listed}"+ );++ // status — clean tree, no changed files.+ let status = harness+ .rpc(+ 61_002,+ "openhuman.worktree_status",+ json!({ "path": worktree.to_str().unwrap() }),+ )+ .await;+ let status = payload(&status, "worktree_status clean");+ assert_eq!(status.get("branch"), Some(&json!("worker/1")));+ assert_eq!(status.get("isDirty"), Some(&json!(false)));+ assert_eq!(status.get("changedFiles"), Some(&json!([])));++ // diff — an empty summary for a clean tree.+ let diff = harness+ .rpc(+ 61_003,+ "openhuman.worktree_diff",+ json!({ "path": worktree.to_str().unwrap() }),+ )+ .await;+ assert_eq!(+ payload(&diff, "worktree_diff clean")+ .get("summary")+ .and_then(Value::as_str),+ Some(""),+ "a clean worktree diffs to nothing"+ );++ // Dirty it, then re-read: status and diff must both notice.+ std::fs::write(worktree.join("README.md"), "hello\nchanged\n").expect("dirty the worktree");+ std::fs::write(worktree.join("NEW.md"), "untracked\n").expect("add untracked");++ let dirty = harness+ .rpc(+ 61_004,+ "openhuman.worktree_status",+ json!({ "path": worktree.to_str().unwrap() }),+ )+ .await;+ let dirty = payload(&dirty, "worktree_status dirty");+ assert_eq!(dirty.get("isDirty"), Some(&json!(true)));+ let changed = dirty+ .get("changedFiles")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("changedFiles must be an array: {dirty}"))+ .iter()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>();+ assert!(+ changed.iter().any(|f| f.ends_with("README.md")),+ "the modified tracked file must be listed: {changed:?}"+ );++ let dirty_diff = harness+ .rpc(+ 61_005,+ "openhuman.worktree_diff",+ json!({ "path": worktree.to_str().unwrap() }),+ )+ .await;+ let summary = payload(&dirty_diff, "worktree_diff dirty")+ .get("summary")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ assert!(+ summary.contains("README.md"),+ "the diff summary must name the changed file: {summary}"+ );++ // remove without force must refuse a dirty worktree — the whole point of+ // the flag is that uncommitted work needs an explicit decision.+ let refused = harness+ .rpc(+ 61_006,+ "openhuman.worktree_remove",+ json!({ "path": worktree.to_str().unwrap() }),+ )+ .await;+ let message = err_message(&refused, "worktree_remove dirty without force");+ assert!(+ message.to_lowercase().contains("dirty") || message.to_lowercase().contains("uncommitted"),+ "removing a dirty worktree must say why it refused, got: {message}"+ );+ assert!(+ worktree.exists(),+ "a refused remove must leave the checkout on disk"+ );++ // remove with force succeeds and the checkout is gone.+ let removed = harness+ .rpc(+ 61_007,+ "openhuman.worktree_remove",+ json!({ "path": worktree.to_str().unwrap(), "force": true }),+ )+ .await;+ assert_eq!(+ payload(&removed, "worktree_remove forced").get("removed"),+ Some(&json!(true))+ );+ assert!(+ !worktree.exists(),+ "a forced remove must delete the checkout: {}",+ worktree.display()+ );++ let after = harness+ .rpc(61_008, "openhuman.worktree_list", json!({}))+ .await;+ assert_eq!(+ payload(&after, "worktree_list after remove")+ .get("worktrees")+ .and_then(Value::as_array)+ .map(Vec::len),+ Some(0),+ "the removed worktree must be gone from the listing"+ );++ harness.join.abort();+}++#[tokio::test]+async fn worktree_path_guard_rejects_relative_and_unmanaged_paths() {+ let outer = tempdir().expect("tempdir");+ let (repo, _worktree) = init_repo_with_managed_worktree(outer.path());++ let _lock = env_lock();+ let harness = setup(Some(&repo)).await;++ // The guard is the security boundary for this namespace: without it,+ // `worktree_remove` would happily delete the user's main checkout.+ for (id, method) in [+ (62_001, "openhuman.worktree_status"),+ (62_002, "openhuman.worktree_diff"),+ (62_003, "openhuman.worktree_remove"),+ ] {+ // Two distinct gates, two distinct messages. Omitting `path` never+ // reaches the handler — `core::all::validate_params` rejects it from+ // the schema. A *blank* path does reach the handler, and is refused+ // by `require_managed_worktree_path` further down.+ let missing = harness.rpc(id, method, json!({})).await;+ assert!(+ err_message(&missing, method).contains("missing required param 'path'"),+ "{method} must require `path` at the dispatch boundary"+ );++ let relative = harness+ .rpc(id + 10, method, json!({ "path": "relative/dir" }))+ .await;+ assert!(+ err_message(&relative, method).contains("absolute path required"),+ "{method} must reject a relative path"+ );++ // The repo root itself is absolute *and* real — and must still be+ // refused, because it is not under `.claude/worktrees`.+ let unmanaged = harness+ .rpc(id + 20, method, json!({ "path": repo.to_str().unwrap() }))+ .await;+ assert!(+ err_message(&unmanaged, method).contains("not a managed worker worktree"),+ "{method} must refuse the main checkout"+ );++ let blank = harness.rpc(id + 30, method, json!({ "path": " " })).await;+ assert!(+ err_message(&blank, method).contains("missing required param: path"),+ "{method} must treat a blank path as missing"+ );+ }++ harness.join.abort();+}++#[tokio::test]+async fn worktree_list_degrades_to_empty_outside_a_git_repo() {+ let _lock = env_lock();+ // `action_dir` = an empty non-git directory: the state of a user who has+ // not opened a project. The panel must render, not error.+ let harness = setup(None).await;++ let listed = harness+ .rpc(63_001, "openhuman.worktree_list", json!({}))+ .await;+ let listed = payload(&listed, "worktree_list non-git");+ assert_eq!(listed.get("worktrees"), Some(&json!([])));+ assert_eq!(listed.get("overlaps"), Some(&json!([])));++ harness.join.abort();+}++// ── http_host ──────────────────────────────────────────────────────────────++#[tokio::test]+async fn http_host_start_list_get_serves_the_directory_then_stop_retires_it() {+ let _lock = env_lock();+ let harness = setup(None).await;++ let served_dir = harness.home().join("served");+ std::fs::create_dir_all(&served_dir).expect("create served dir");+ std::fs::write(served_dir.join("hello.txt"), "hosted-body\n").expect("write served file");++ // start — port 0 lets the OS pick, so this never collides with a parallel+ // worker's test.+ let started = harness+ .rpc(+ 64_001,+ "openhuman.http_host_start",+ json!({+ "directory": served_dir.to_str().unwrap(),+ "port": 0,+ "server_name": "e2e-hosted",+ "disable_auth": true+ }),+ )+ .await;+ let server = payload(&started, "http_host_start")+ .get("server")+ .unwrap_or_else(|| panic!("start must return a server: {started}"))+ .clone();+ let server_id = server+ .get("server_id")+ .and_then(Value::as_str)+ .expect("server_id")+ .to_string();+ let port = server.get("port").and_then(Value::as_u64).expect("port");+ assert!(+ port > 0,+ "port 0 must be replaced by the bound port: {server}"+ );+ assert_eq!(server.get("bind_host"), Some(&json!("127.0.0.1")));+ assert_eq!(server.get("server_name"), Some(&json!("e2e-hosted")));+ assert_eq!(+ server.get("local_url").and_then(Value::as_str),+ Some(format!("http://127.0.0.1:{port}/").as_str())+ );+ assert_eq!(+ server.pointer("/auth/enabled"),+ Some(&json!(false)),+ "disable_auth=true must be honoured: {server}"+ );++ // The server is real: fetch the file it hosts over HTTP.+ let body = reqwest::Client::builder()+ .timeout(Duration::from_secs(10))+ .build()+ .expect("client")+ .get(format!("http://127.0.0.1:{port}/hello.txt"))+ .send()+ .await+ .expect("GET hosted file")+ .text()+ .await+ .expect("hosted body");+ assert_eq!(+ body, "hosted-body\n",+ "http_host_start must actually serve the directory"+ );++ // list — the running server is present.+ let listed = harness+ .rpc(64_002, "openhuman.http_host_list", json!({}))+ .await;+ let servers = payload(&listed, "http_host_list")+ .get("servers")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("servers must be an array: {listed}"))+ .clone();+ assert!(+ servers+ .iter()+ .any(|s| s.get("server_id").and_then(Value::as_str) == Some(server_id.as_str())),+ "the started server must appear in the listing: {listed}"+ );++ // get — the same record by id.+ let fetched = harness+ .rpc(+ 64_003,+ "openhuman.http_host_get",+ json!({ "server_id": server_id }),+ )+ .await;+ let fetched = payload(&fetched, "http_host_get")+ .get("server")+ .unwrap_or_else(|| panic!("get must return a server: {fetched}"))+ .clone();+ assert_eq!(fetched.get("port"), Some(&json!(port)));+ assert_eq!(+ fetched.get("directory"),+ server.get("directory"),+ "get must return the same canonicalised directory as start"+ );++ // stop — reports the final snapshot, and the id stops resolving.+ let stopped = harness+ .rpc(+ 64_004,+ "openhuman.http_host_stop",+ json!({ "server_id": server_id }),+ )+ .await;+ let stopped = payload(&stopped, "http_host_stop");+ assert_eq!(stopped.get("stopped"), Some(&json!(true)));+ assert_eq!(+ stopped.pointer("/server/server_id").and_then(Value::as_str),+ Some(server_id.as_str())+ );++ let gone = harness+ .rpc(+ 64_005,+ "openhuman.http_host_get",+ json!({ "server_id": server_id }),+ )+ .await;+ assert!(+ err_message(&gone, "http_host_get after stop").contains("not found"),+ "a stopped server must no longer resolve"+ );++ harness.join.abort();+}++#[tokio::test]+async fn http_host_rejects_a_missing_directory_and_an_unknown_server_id() {+ let _lock = env_lock();+ let harness = setup(None).await;++ let absent = harness.home().join("does-not-exist");+ let failed = harness+ .rpc(+ 65_001,+ "openhuman.http_host_start",+ json!({ "directory": absent.to_str().unwrap(), "port": 0, "disable_auth": true }),+ )+ .await;+ let message = err_message(&failed, "http_host_start missing dir");+ assert!(+ !message.is_empty(),+ "starting on a missing directory must fail with a reason"+ );++ // A file is not a directory — the canonicalisation guard must say so+ // rather than binding a server that serves nothing.+ let file = harness.home().join("a-file.txt");+ std::fs::write(&file, "x").expect("write file");+ let not_a_dir = harness+ .rpc(+ 65_002,+ "openhuman.http_host_start",+ json!({ "directory": file.to_str().unwrap(), "port": 0, "disable_auth": true }),+ )+ .await;+ assert!(+ !err_message(¬_a_dir, "http_host_start on a file").is_empty(),+ "hosting a regular file must be refused"+ );++ let unknown = harness+ .rpc(+ 65_003,+ "openhuman.http_host_get",+ json!({ "server_id": "00000000-0000-0000-0000-000000000000" }),+ )+ .await;+ assert!(+ err_message(&unknown, "http_host_get unknown").contains("not found"),+ "an unknown server id must report not-found"+ );++ let stop_unknown = harness+ .rpc(+ 65_004,+ "openhuman.http_host_stop",+ json!({ "server_id": "00000000-0000-0000-0000-000000000000" }),+ )+ .await;+ assert!(+ !err_message(&stop_unknown, "http_host_stop unknown").is_empty(),+ "stopping an unknown server must fail rather than report success"+ );++ // A malformed request (no `server_id`) must be a params error.+ let malformed = harness+ .rpc(65_005, "openhuman.http_host_get", json!({}))+ .await;+ assert!(+ err_message(&malformed, "http_host_get no id")+ .contains("missing required param 'server_id'"),+ "a missing server_id must be caught by the dispatch-boundary gate"+ );++ harness.join.abort();+}++#[tokio::test]+async fn http_host_start_mints_basic_auth_credentials_by_default() {+ let _lock = env_lock();+ let harness = setup(None).await;++ let served_dir = harness.home().join("guarded");+ std::fs::create_dir_all(&served_dir).expect("create dir");+ std::fs::write(served_dir.join("secret.txt"), "guarded-body\n").expect("write file");++ // No `disable_auth` — the documented default is auth ON with a generated+ // password. A regression that flipped this default would silently expose a+ // user's directory on their LAN.+ let started = harness+ .rpc(+ 66_001,+ "openhuman.http_host_start",+ json!({+ "directory": served_dir.to_str().unwrap(),+ "port": 0,+ "username": "e2e-user"+ }),+ )+ .await;+ let server = payload(&started, "http_host_start auth")+ .get("server")+ .expect("server")+ .clone();+ let server_id = server+ .get("server_id")+ .and_then(Value::as_str)+ .expect("server_id")+ .to_string();+ let port = server.get("port").and_then(Value::as_u64).expect("port");+ assert_eq!(server.pointer("/auth/enabled"), Some(&json!(true)));+ assert_eq!(server.pointer("/auth/username"), Some(&json!("e2e-user")));+ let password = server+ .pointer("/auth/password")+ .and_then(Value::as_str)+ .expect("a generated password")+ .to_string();+ assert!(+ !password.is_empty(),+ "auth-enabled hosting must mint a password"+ );++ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(10))+ .build()+ .expect("client");++ // Unauthenticated request is refused...+ let refused = client+ .get(format!("http://127.0.0.1:{port}/secret.txt"))+ .send()+ .await+ .expect("unauthenticated GET");+ assert_eq!(+ refused.status(),+ StatusCode::UNAUTHORIZED,+ "an auth-enabled hosted dir must reject an anonymous request"+ );++ // ...and the minted credentials work.+ let allowed = client+ .get(format!("http://127.0.0.1:{port}/secret.txt"))+ .basic_auth("e2e-user", Some(&password))+ .send()+ .await+ .expect("authenticated GET");+ assert_eq!(allowed.status(), StatusCode::OK);+ assert_eq!(allowed.text().await.expect("body"), "guarded-body\n");++ let _ = harness+ .rpc(+ 66_002,+ "openhuman.http_host_stop",+ json!({ "server_id": server_id }),+ )+ .await;++ harness.join.abort();+}++// ── workspace ──────────────────────────────────────────────────────────────++#[tokio::test]+async fn workspace_persona_files_round_trip_read_write_and_reset() {+ let _lock = env_lock();+ let harness = setup(None).await;++ // read on a fresh workspace falls back to the bundled default.+ let fresh = harness+ .rpc(+ 67_001,+ "openhuman.workspace_file_read",+ json!({ "filename": "SOUL.md" }),+ )+ .await;+ let fresh = payload(&fresh, "workspace_file_read fresh");+ assert_eq!(fresh.get("filename"), Some(&json!("SOUL.md")));+ assert_eq!(+ fresh.get("is_default"),+ Some(&json!(true)),+ "a missing workspace copy must be reported as the bundled default: {fresh}"+ );+ let bundled = fresh+ .get("contents")+ .and_then(Value::as_str)+ .expect("contents")+ .to_string();+ assert!(+ !bundled.is_empty(),+ "the bundled default must not be empty — the editor renders it"+ );++ // write persists and flips is_default off.+ let written = harness+ .rpc(+ 67_002,+ "openhuman.workspace_file_write",+ json!({ "filename": "SOUL.md", "contents": "# e2e soul\nBe brief.\n" }),+ )+ .await;+ let written = payload(&written, "workspace_file_write");+ assert_eq!(written.get("is_default"), Some(&json!(false)));+ assert_eq!(+ written.get("contents"),+ Some(&json!("# e2e soul\nBe brief.\n"))+ );+ assert_eq!(+ std::fs::read_to_string(harness.workspace().join("SOUL.md")).expect("SOUL.md on disk"),+ "# e2e soul\nBe brief.\n",+ "the write must land in the workspace, not just in the reply"+ );++ // read returns what was written.+ let read_back = harness+ .rpc(+ 67_003,+ "openhuman.workspace_file_read",+ json!({ "filename": "SOUL.md" }),+ )+ .await;+ let read_back = payload(&read_back, "workspace_file_read after write");+ assert_eq!(read_back.get("is_default"), Some(&json!(false)));+ assert_eq!(+ read_back.get("contents"),+ Some(&json!("# e2e soul\nBe brief.\n"))+ );++ // reset restores the bundled default, on disk as well as in the reply.+ let reset = harness+ .rpc(+ 67_004,+ "openhuman.workspace_file_reset",+ json!({ "filename": "SOUL.md" }),+ )+ .await;+ let reset = payload(&reset, "workspace_file_reset");+ assert_eq!(reset.get("is_default"), Some(&json!(true)));+ assert_eq!(reset.get("contents"), Some(&json!(bundled.clone())));+ assert_eq!(+ std::fs::read_to_string(harness.workspace().join("SOUL.md")).expect("SOUL.md on disk"),+ bundled,+ "reset must rewrite the file, not only report the default"+ );++ // IDENTITY.md is the second allowlisted file and must behave the same.+ let identity = harness+ .rpc(+ 67_005,+ "openhuman.workspace_file_read",+ json!({ "filename": "IDENTITY.md" }),+ )+ .await;+ assert_eq!(+ payload(&identity, "workspace_file_read IDENTITY").get("filename"),+ Some(&json!("IDENTITY.md"))+ );++ harness.join.abort();+}++#[tokio::test]+async fn workspace_allowlist_refuses_arbitrary_paths_and_oversize_writes() {+ let _lock = env_lock();+ let harness = setup(None).await;++ // The allowlist is the only thing standing between this RPC and arbitrary+ // read/write under the workspace, so exercise the shapes an attacker would+ // reach for.+ for (id, filename) in [+ (68_001, "config.toml"),+ (68_002, "../../etc/passwd"),+ (68_003, "soul.md"), // case matters — the allowlist is exact+ (68_004, ""),+ ] {+ let refused = harness+ .rpc(+ id,+ "openhuman.workspace_file_read",+ json!({ "filename": filename }),+ )+ .await;+ let message = err_message(&refused, &format!("workspace_file_read {filename}"));+ assert!(+ message.contains("is not an editable workspace file"),+ "reading '{filename}' must be refused by the allowlist, got: {message}"+ );++ let refused_write = harness+ .rpc(+ id + 100,+ "openhuman.workspace_file_write",+ json!({ "filename": filename, "contents": "x" }),+ )+ .await;+ assert!(+ err_message(&refused_write, "workspace_file_write")+ .contains("is not an editable workspace file"),+ "writing '{filename}' must be refused by the allowlist"+ );++ let refused_reset = harness+ .rpc(+ id + 200,+ "openhuman.workspace_file_reset",+ json!({ "filename": filename }),+ )+ .await;+ assert!(+ err_message(&refused_reset, "workspace_file_reset")+ .contains("is not an editable workspace file"),+ "resetting '{filename}' must be refused by the allowlist"+ );+ }++ // A missing required param is a distinct failure from a rejected one.+ let no_filename = harness+ .rpc(68_010, "openhuman.workspace_file_read", json!({}))+ .await;+ assert!(+ err_message(&no_filename, "workspace_file_read no filename")+ .contains("missing required param 'filename'"),+ "an omitted filename must be reported as missing, not as non-editable"+ );++ let no_contents = harness+ .rpc(+ 68_011,+ "openhuman.workspace_file_write",+ json!({ "filename": "SOUL.md" }),+ )+ .await;+ assert!(+ err_message(&no_contents, "workspace_file_write no contents")+ .contains("missing required param 'contents'"),+ "an omitted body must be reported as missing"+ );++ // The 256 KiB cap bounds a runaway paste from the UI.+ let oversize = "x".repeat(256 * 1024 + 1);+ let refused = harness+ .rpc(+ 68_012,+ "openhuman.workspace_file_write",+ json!({ "filename": "SOUL.md", "contents": oversize }),+ )+ .await;+ assert!(+ err_message(&refused, "workspace_file_write oversize").contains("exceed the"),+ "a write over the byte limit must be refused"+ );+ assert!(+ !harness.workspace().join("SOUL.md").exists(),+ "a refused oversize write must not have touched the file"+ );++ harness.join.abort();+}++// ── modules ────────────────────────────────────────────────────────────────++#[tokio::test]+async fn modules_list_and_status_report_every_known_module() {+ let _lock = env_lock();+ let harness = setup(None).await;++ let listed = harness+ .rpc(69_001, "openhuman.modules_list", json!({}))+ .await;+ let modules = payload(&listed, "modules_list")+ .get("modules")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("modules must be an array: {listed}"))+ .clone();+ assert!(+ !modules.is_empty(),+ "this build knows at least one loadable module: {listed}"+ );+ let ids: Vec<&str> = modules+ .iter()+ .filter_map(|m| m.get("id").and_then(Value::as_str))+ .collect();+ for expected in ["tinydocs", "tinymemory", "tinymcp"] {+ assert!(+ ids.contains(&expected),+ "the compiled-in registry must list '{expected}': {ids:?}"+ );+ }+ // Every entry carries the fields the settings screen renders.+ for module in &modules {+ for field in ["id", "description", "version", "bus_name", "state"] {+ assert!(+ module.get(field).is_some(),+ "module status is missing `{field}`: {module}"+ );+ }+ }+ // The test config disables modules, so every entry must say so — and say+ // *why*, since "unavailable" without a reason is the failure mode this+ // namespace exists to avoid.+ for module in &modules {+ assert_eq!(+ module.get("state"),+ Some(&json!("unsupported")),+ "with `[modules] enabled = false` every module is unsupported: {module}"+ );+ assert_eq!(+ module.get("detail"),+ Some(&json!("modules are disabled in configuration")),+ "the reason must be reported, not just the state: {module}"+ );+ }++ // status for one id returns exactly that module.+ let status = harness+ .rpc(+ 69_002,+ "openhuman.modules_status",+ json!({ "id": "tinydocs" }),+ )+ .await;+ let module = payload(&status, "modules_status")+ .get("module")+ .unwrap_or_else(|| panic!("status must return a module: {status}"));+ assert_eq!(module.get("id"), Some(&json!("tinydocs")));+ assert_eq!(module.get("state"), Some(&json!("unsupported")));++ harness.join.abort();+}++#[tokio::test]+async fn modules_status_and_load_reject_an_unknown_id_and_a_blank_one() {+ let _lock = env_lock();+ let harness = setup(None).await;++ for (id, method) in [+ (70_001, "openhuman.modules_status"),+ (70_002, "openhuman.modules_load"),+ ] {+ let unknown = harness.rpc(id, method, json!({ "id": "tinynope" })).await;+ assert!(+ err_message(&unknown, method).contains("unknown module 'tinynope'"),+ "{method} must name the unknown module in its error"+ );++ // Omitted entirely: caught at the dispatch boundary by the schema's+ // `required` flag, before the handler runs.+ let missing = harness.rpc(id + 10, method, json!({})).await;+ assert!(+ err_message(&missing, method).contains("missing required param 'id'"),+ "{method} must require an id"+ );++ let blank = harness.rpc(id + 20, method, json!({ "id": " " })).await;+ assert!(+ err_message(&blank, method).contains("`id` is required"),+ "{method} must treat a blank id as missing"+ );+ }++ // `modules_load` on a known module reports the *state after the attempt*+ // rather than failing the transport — with modules disabled the attempt+ // cannot succeed, and the answer is a state plus a reason. (Downloads stay+ // off: `[modules] enabled = false` short-circuits before any network I/O.)+ let attempted = harness+ .rpc(+ 70_003,+ "openhuman.modules_load",+ json!({ "id": "tinydocs" }),+ )+ .await;+ let module = payload(&attempted, "modules_load disabled")+ .get("module")+ .unwrap_or_else(|| panic!("load must return a module status: {attempted}"));+ assert_eq!(module.get("id"), Some(&json!("tinydocs")));+ assert_eq!(+ module.get("state"),+ Some(&json!("unsupported")),+ "a load that could not run must not report ready: {module}"+ );+ assert_eq!(+ module.get("detail"),+ Some(&json!("modules are disabled in configuration"))+ );++ harness.join.abort();+}diff --git a/tests/raw_coverage/voice_audio_e2e.rs b/tests/raw_coverage/voice_audio_e2e.rsnew file mode 100644index 0000000000..e3b27df54f--- /dev/null+++ b/tests/raw_coverage/voice_audio_e2e.rs@@ -0,0 +1,1657 @@+//! JSON-RPC E2E coverage for the 14 uncovered `voice` controllers and all three+//! `audio_toolkit` controllers (the latter namespace was at 0%).+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target;+//! `build.rs` globs `tests/raw_coverage/` and generates the `mod` list. That+//! target already declares `required-features = ["voice", "inference"]`, both of+//! which are in `scripts/ci/product-features.sh`, so no `Cargo.toml` edit is+//! needed for the gates these controllers sit behind.+//!+//! Run with:+//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)"`+//!+//! # How the cloud-backed voice paths stay hermetic+//!+//! `voice_tts_dispatch`, `voice_reply_synthesize`, `voice_stt_dispatch`,+//! `voice_transcribe_bytes` and `voice_agent_signed_url` all route through the+//! hosted backend behind a session token. Rather than skip them, this file+//! stands up a **mock backend** on loopback (`/auth/me`,+//! `/openai/v1/audio/speech`, `/openai/v1/audio/transcriptions`,+//! `/voice-agent/get-signed-url`), points `api_url` at it, and mints a session+//! through the real `openhuman.auth_store_session` RPC. `ensure_secure_backend_url`+//! permits a loopback `http://` origin, which is what makes that possible.+//!+//! `voice_tts` is the one path that does not go to the backend — it drives the+//! local Piper binary. A stub `piper` on `PIPER_BIN` plus a stub voice model+//! makes its happy path assertable without a 60 MB ONNX download.+//!+//! `voice_server_start` deliberately uses a **non-`fn` hotkey**: on macOS every+//! other key is refused before any OS event tap is created (#2677), so the case+//! can exercise the lifecycle without a test grabbing the developer's keyboard.+//!+//! Env is process-global and every aggregated suite shares one process, so each+//! case takes the **crate-wide** [`env_lock`] for its whole body.++#![cfg(feature = "voice")]++use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use axum::body::Bytes;+use axum::http::header::AUTHORIZATION;+use axum::http::HeaderMap;+use axum::routing::{get, post};+use axum::{Json, Router};+use reqwest::StatusCode;+use serde_json::{json, Value};+use tempfile::{tempdir, TempDir};++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::jsonrpc::build_core_http_router;++const TEST_RPC_TOKEN: &str = "voice-audio-e2e-token";+const SESSION_JWT: &str = "voice-audio-e2e-jwt";+/// One second of silence as an mp3-shaped payload. The content does not have to+/// decode — nothing in the path under test parses the audio — but it must be+/// non-empty, because `transcribe_cloud` rejects an empty decode.+const FAKE_MP3_BASE64: &str = "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4Ljc2LjEwMAAAAAAAAAAAAAAA";++static AUTH_INIT: OnceLock<()> = OnceLock::new();++/// Crate-wide, not file-local: all aggregated suites share one process, so a+/// private mutex would not mutually exclude with anyone else's env mutation.+static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++fn env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++struct EnvVarGuard {+ key: &'static str,+ old: Option<std::ffi::OsString>,+}++impl EnvVarGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let old = std::env::var_os(key);+ std::env::set_var(key, path.as_os_str());+ Self { key, old }+ }++ fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var_os(key);+ std::env::set_var(key, value);+ Self { key, old }+ }++ fn unset(key: &'static str) -> Self {+ let old = std::env::var_os(key);+ std::env::remove_var(key);+ Self { key, old }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+}++/// See `sandbox_runtime_platform_e2e.rs`: `core::auth::RPC_TOKEN` is a+/// process-global `OnceLock`, so inside the aggregated binary the first suite+/// to initialise pins the bearer for every later one. Use the token this+/// process actually validates rather than assuming ours won.+fn ensure_rpc_auth() -> String {+ AUTH_INIT.get_or_init(|| {+ if std::env::var(CORE_TOKEN_ENV_VAR)+ .ok()+ .filter(|v| !v.trim().is_empty())+ .is_none()+ {+ std::env::set_var(CORE_TOKEN_ENV_VAR, TEST_RPC_TOKEN);+ }+ let token_dir = std::env::temp_dir().join("openhuman-voice-audio-e2e-auth");+ init_rpc_token(&token_dir).expect("init rpc auth token");+ });+ get_rpc_token()+ .expect("core RPC token must be initialised before serving")+ .to_string()+}++// ── mock backend ───────────────────────────────────────────────────────────++fn unauthorized() -> (StatusCode, Json<Value>) {+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "missing or invalid bearer" })),+ )+}++fn require_session(headers: &HeaderMap) -> Result<(), (StatusCode, Json<Value>)> {+ let actual = headers+ .get(AUTHORIZATION)+ .and_then(|value| value.to_str().ok())+ .map(str::trim);+ match actual {+ Some(value) if value == format!("Bearer {SESSION_JWT}") => Ok(()),+ _ => Err(unauthorized()),+ }+}++async fn mock_current_user(headers: HeaderMap) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ Ok(Json(json!({+ "success": true,+ "data": { "_id": "voice-e2e-user", "username": "voice-e2e" }+ })))+}++/// The hosted TTS proxy. Echoes back the requested voice so a case can prove+/// the *routing* decision reached the backend, not just that a call happened.+async fn mock_audio_speech(+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ let text = body.get("text").and_then(Value::as_str).unwrap_or_default();+ if text.trim().is_empty() {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({ "success": false, "error": "text is required" })),+ ));+ }+ Ok(Json(json!({+ "audio_base64": FAKE_MP3_BASE64,+ "audio_mime": "audio/mpeg",+ "visemes": [+ { "viseme": "AA", "start_ms": 0, "end_ms": 120 },+ { "viseme": "MM", "start_ms": 120, "end_ms": 240 }+ ],+ // Echoed for assertion; the client ignores unknown fields.+ "echo_voice_id": body.get("voice_id").cloned().unwrap_or(Value::Null),+ "echo_text": text,+ })))+}++/// The hosted STT proxy. Multipart in, `{ "text": … }` out.+///+/// The body is scanned as raw bytes rather than parsed: this crate's `axum` is+/// built without the `multipart` feature (see `Cargo.toml`), and a mock only+/// needs to prove the client actually sent a file part and which model it+/// asked for.+async fn mock_audio_transcriptions(+ headers: HeaderMap,+ body: Bytes,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ let raw = String::from_utf8_lossy(&body);+ if !raw.contains("name=\"file\"") {+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({ "success": false, "error": "no audio part" })),+ ));+ }+ // The `model` part is `…name="model"\r\n\r\n<value>\r\n--boundary`.+ let model = raw+ .split("name=\"model\"")+ .nth(1)+ .and_then(|rest| rest.split("\r\n\r\n").nth(1))+ .and_then(|rest| rest.split("\r\n").next())+ .unwrap_or("")+ .trim()+ .to_string();+ Ok(Json(json!({ "text": format!("transcribed by {model}") })))+}++async fn mock_voice_agent_signed_url(+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ require_session(&headers)?;+ Ok(Json(json!({+ "success": true,+ "data": {+ "signedUrl": "wss://voice.e2e.test/convai?token=e2e-signed",+ "agentId": "agent_e2e_001"+ }+ })))+}++fn mock_backend_router() -> Router {+ Router::new()+ .route("/auth/me", get(mock_current_user))+ .route("/settings", get(mock_current_user))+ .route("/openai/v1/audio/speech", post(mock_audio_speech))+ .route(+ "/openai/v1/audio/transcriptions",+ post(mock_audio_transcriptions),+ )+ .route(+ "/voice-agent/get-signed-url",+ get(mock_voice_agent_signed_url),+ )+}++async fn serve(+ router: Router,+) -> (+ SocketAddr,+ tokio::task::JoinHandle<Result<(), std::io::Error>>,+) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind listener");+ let addr = listener.local_addr().expect("listener addr");+ let join = tokio::spawn(async move { axum::serve(listener, router).await });+ (addr, join)+}++// ── harness ────────────────────────────────────────────────────────────────++/// `extra` is spliced in **above the first table** so a caller may pass either a+/// bare top-level key or a whole `[table]`; appending it at the end would make a+/// top-level key land inside `[memory_tree]`.+///+/// `[local_ai]` is deliberately *not* in the fixed template: the local-Piper+/// case needs `runtime_enabled = true`, and declaring the table twice in one+/// document is a TOML duplicate-key error. `runtime_enabled` defaults to false,+/// which is what every other case wants anyway.+fn write_config(dir: &Path, api_url: &str, extra: &str) {+ std::fs::create_dir_all(dir).expect("create config dir");+ let cfg = format!(+ r#"api_url = "{api_url}"+default_model = "e2e-model"+default_temperature = 0.2+{extra}+[secrets]+encrypt = false++[modules]+enabled = false+allow_download = false++[memory]+provider = "none"+embedding_provider = "none"+embedding_model = "none"+embedding_dimensions = 0++[memory_tree]+embedding_strict = false+"#+ );+ std::fs::write(dir.join("config.toml"), &cfg).expect("write config.toml");+ let _: openhuman_core::openhuman::config::Config =+ toml::from_str(&cfg).expect("test config must match schema");+}++struct TestHarness {+ tmp: TempDir,+ _guards: Vec<EnvVarGuard>,+ rpc_base: String,+ token: String,+ rpc_join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+ mock_join: tokio::task::JoinHandle<Result<(), std::io::Error>>,+}++impl TestHarness {+ fn home(&self) -> &Path {+ self.tmp.path()+ }++ fn workspace(&self) -> std::path::PathBuf {+ self.tmp.path().join("workspace")+ }++ async fn rpc(&self, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("client");+ let url = format!("{}/rpc", self.rpc_base.trim_end_matches('/'));+ let response = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", self.token))+ .json(&json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": method,+ "params": params,+ }))+ .send()+ .await+ .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));+ assert_eq!(+ response.status(),+ StatusCode::OK,+ "HTTP transport should accept {method}"+ );+ response+ .json::<Value>()+ .await+ .unwrap_or_else(|err| panic!("json for {method}: {err}"))+ }++ /// Mint a backend session through the real auth RPC, which validates the+ /// JWT against the mock's `GET /auth/me`. Every backend-bound voice call+ /// below needs this to have happened.+ async fn store_session(&self, id: i64) {+ let stored = self+ .rpc(+ id,+ "openhuman.auth_store_session",+ json!({ "token": SESSION_JWT, "user_id": "voice-e2e-user" }),+ )+ .await;+ assert!(+ stored.get("error").is_none(),+ "storing the e2e session must succeed: {stored}"+ );+ }++ fn shutdown(self) {+ self.rpc_join.abort();+ self.mock_join.abort();+ }+}++async fn setup(extra: &str) -> TestHarness {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let workspace = home.join("workspace");+ std::fs::create_dir_all(&workspace).expect("create workspace");++ let (mock_addr, mock_join) = serve(mock_backend_router()).await;+ let mock_origin = format!("http://127.0.0.1:{}", mock_addr.port());++ write_config(&home.join(".openhuman"), &mock_origin, extra);+ // `auth_store_session` activates the user and reloads config from the+ // user-scoped directory; without a copy there it would fall back to+ // defaults and lose the mock `api_url`.+ write_config(+ &home.join(".openhuman").join("users").join("voice-e2e-user"),+ &mock_origin,+ extra,+ );++ let guards = vec![+ EnvVarGuard::set_to_path("HOME", home),+ EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),+ EnvVarGuard::unset("BACKEND_URL"),+ EnvVarGuard::unset("VITE_BACKEND_URL"),+ EnvVarGuard::unset("OPENHUMAN_API_URL"),+ EnvVarGuard::unset("PIPER_BIN"),+ EnvVarGuard::unset("OPENHUMAN_TEST_REPLY_SPEECH_SEAM"),+ EnvVarGuard::unset("OPENHUMAN_EMAIL_CAPTURE_DIR"),+ EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),+ EnvVarGuard::set("OPENHUMAN_MEMORY_EMBED_STRICT", "false"),+ ];++ let token = ensure_rpc_auth();+ let (rpc_addr, rpc_join) = serve(build_core_http_router(false)).await;++ TestHarness {+ tmp,+ _guards: guards,+ rpc_base: format!("http://{rpc_addr}"),+ token,+ rpc_join,+ mock_join,+ }+}++fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {+ if let Some(error) = value.get("error") {+ panic!("{context}: unexpected JSON-RPC error: {error}");+ }+ value+ .get("result")+ .unwrap_or_else(|| panic!("{context}: missing result: {value}"))+}++fn err_message(value: &Value, context: &str) -> String {+ let error = value+ .get("error")+ .unwrap_or_else(|| panic!("{context}: expected JSON-RPC error, got: {value}"));+ error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{context}: error without message: {error}"))+ .to_string()+}++fn payload<'a>(value: &'a Value, context: &str) -> &'a Value {+ let result = ok(value, context);+ result.get("result").unwrap_or(result)+}++/// A stub `piper` that writes a minimal RIFF/WAVE file to whatever+/// `--output_file` names, so the local TTS path can be driven end to end.+#[cfg(unix)]+fn write_piper_stub(dir: &Path) -> std::path::PathBuf {+ use std::os::unix::fs::PermissionsExt;+ std::fs::create_dir_all(dir).expect("create stub dir");+ let path = dir.join("piper");+ std::fs::write(+ &path,+ r#"#!/bin/sh+# Mirrors piper's CLI shape: read text on stdin, write a wav to --output_file.+out=""+while [ $# -gt 0 ]; do+ case "$1" in+ --output_file) out="$2"; shift 2 ;;+ *) shift ;;+ esac+done+cat > /dev/null+[ -n "$out" ] || exit 2+printf 'RIFF$\000\000\000WAVEfmt \020\000\000\000' > "$out"+printf '\001\000\001\000\200>\000\000\000}\000\000\002\000\020\000data\000\000\000\000' >> "$out"+"#,+ )+ .expect("write piper stub");+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod stub");+ path+}++// ── voice: provider settings ───────────────────────────────────────────────++#[tokio::test]+async fn voice_set_providers_persists_and_validates_the_selectors() {+ let _lock = env_lock();+ let harness = setup("").await;++ let set = harness+ .rpc(+ 80_001,+ "openhuman.voice_set_providers",+ json!({+ "stt_provider": "cloud",+ "tts_provider": "piper",+ "stt_model": "whisper-1",+ "tts_voice": "en_US-amy-medium"+ }),+ )+ .await;+ let set = payload(&set, "voice_set_providers");+ assert_eq!(set.get("stt_provider"), Some(&json!("cloud")));+ assert_eq!(set.get("tts_provider"), Some(&json!("piper")));+ assert_eq!(set.get("stt_model_id"), Some(&json!("whisper-1")));+ assert_eq!(set.get("tts_voice_id"), Some(&json!("en_US-amy-medium")));++ // Persisted, not merely echoed: read it back through a different RPC.+ let status = harness+ .rpc(80_002, "openhuman.voice_status", json!({}))+ .await;+ let status = payload(&status, "voice_status after set_providers");+ assert_eq!(+ status.get("tts_provider"),+ Some(&json!("piper")),+ "the selector must survive into the status surface: {status}"+ );++ // Omitted fields are left alone — a settings panel that only changes the+ // TTS dropdown must not blank the STT model.+ let partial = harness+ .rpc(+ 80_003,+ "openhuman.voice_set_providers",+ json!({ "tts_provider": "cloud" }),+ )+ .await;+ let partial = payload(&partial, "voice_set_providers partial");+ assert_eq!(partial.get("tts_provider"), Some(&json!("cloud")));+ assert_eq!(+ partial.get("stt_model_id"),+ Some(&json!("whisper-1")),+ "an omitted field must keep its current value: {partial}"+ );+ assert_eq!(partial.get("stt_provider"), Some(&json!("cloud")));++ // Failure path: the removed local whisper engine is rejected rather than+ // silently remapped — accepting it would undo the config migration.+ let removed = harness+ .rpc(+ 80_004,+ "openhuman.voice_set_providers",+ json!({ "stt_provider": "whisper" }),+ )+ .await;+ let message = err_message(&removed, "voice_set_providers whisper");+ assert!(+ message.contains("was removed with the bundled whisper.cpp engine"),+ "'whisper' must be refused with the migration explanation: {message}"+ );++ let removed_local = harness+ .rpc(+ 80_005,+ "openhuman.voice_set_providers",+ json!({ "stt_provider": "local" }),+ )+ .await;+ assert!(+ err_message(&removed_local, "voice_set_providers local")+ .contains("was removed with the bundled whisper.cpp engine"),+ "'local' is the same removed engine and must be refused too"+ );++ // …and the rejected write must not have landed.+ let after = harness+ .rpc(80_006, "openhuman.voice_status", json!({}))+ .await;+ assert_ne!(+ payload(&after, "voice_status after rejection").get("stt_engine"),+ Some(&json!("whisper")),+ "a refused provider must never reach the config"+ );++ harness.shutdown();+}++#[tokio::test]+async fn voice_update_provider_settings_registers_providers_and_rejects_bad_enums() {+ let _lock = env_lock();+ let harness = setup("").await;++ let updated = harness+ .rpc(+ 81_001,+ "openhuman.voice_update_provider_settings",+ json!({+ "voice_providers": [{+ "slug": "deepgram",+ "label": "Deepgram",+ "endpoint": "https://api.deepgram.com/v1",+ "auth_style": "bearer",+ "capability": "stt",+ "stt_api_style": "deepgram",+ "default_stt_model": "nova-2"+ }],+ "stt_provider": "deepgram:nova-2"+ }),+ )+ .await;+ let updated = payload(&updated, "voice_update_provider_settings");+ let providers = updated+ .get("voice_providers")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("voice_providers must be an array: {updated}"));+ assert_eq!(providers.len(), 1, "exactly the one entry sent: {updated}");+ let entry = &providers[0];+ assert_eq!(entry.get("slug"), Some(&json!("deepgram")));+ assert_eq!(entry.get("label"), Some(&json!("Deepgram")));+ assert_eq!(+ entry.get("endpoint"),+ Some(&json!("https://api.deepgram.com/v1"))+ );+ assert_eq!(entry.get("capability"), Some(&json!("stt")));+ assert_eq!(entry.get("default_stt_model"), Some(&json!("nova-2")));+ assert!(+ entry+ .get("id")+ .and_then(Value::as_str)+ .is_some_and(|id| !id.is_empty()),+ "an entry with no id must be assigned one: {entry}"+ );+ assert_eq!(updated.get("stt_provider"), Some(&json!("deepgram:nova-2")));++ let assigned_id = entry+ .get("id")+ .and_then(Value::as_str)+ .expect("id")+ .to_string();++ // list_models resolves by slug *or* id and returns the catalogue the+ // settings dropdown renders.+ for (id, key) in [(81_002, "deepgram"), (81_003, assigned_id.as_str())] {+ let models = harness+ .rpc(+ id,+ "openhuman.voice_list_models",+ json!({ "provider_id": key, "capability": "stt" }),+ )+ .await;+ let models = payload(&models, "voice_list_models deepgram")+ .get("models")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("models must be an array for {key}"))+ .clone();+ assert_eq!(+ models.len(),+ 6,+ "the deepgram STT catalogue is six entries: {models:?}"+ );+ assert_eq!(+ models[0].get("id"),+ Some(&json!("nova-2")),+ "the recommended model must lead the list: {models:?}"+ );+ assert!(+ models+ .iter()+ .all(|m| m.get("label").and_then(Value::as_str).is_some()),+ "every entry must carry a display label: {models:?}"+ );+ }++ // Deepgram has no TTS catalogue — asking for one must return empty, not+ // the STT list under a TTS heading.+ let tts_models = harness+ .rpc(+ 81_004,+ "openhuman.voice_list_models",+ json!({ "provider_id": "deepgram", "capability": "tts" }),+ )+ .await;+ assert_eq!(+ payload(&tts_models, "voice_list_models deepgram tts").get("models"),+ Some(&json!([])),+ "an STT-only provider must not advertise voices"+ );++ // An unregistered provider yields an empty catalogue rather than an error.+ let unknown = harness+ .rpc(+ 81_005,+ "openhuman.voice_list_models",+ json!({ "provider_id": "not-registered" }),+ )+ .await;+ assert_eq!(+ payload(&unknown, "voice_list_models unknown").get("models"),+ Some(&json!([]))+ );++ // Failure path: `provider_id` is required.+ let missing = harness+ .rpc(81_006, "openhuman.voice_list_models", json!({}))+ .await;+ assert!(+ err_message(&missing, "voice_list_models missing")+ .contains("missing required param 'provider_id'"),+ "an omitted provider_id must be refused at the dispatch boundary"+ );++ // Failure path: a reserved slug cannot be claimed by a user-defined+ // provider — that would let a BYO entry shadow the managed engine.+ let reserved = harness+ .rpc(+ 81_007,+ "openhuman.voice_update_provider_settings",+ json!({ "voice_providers": [{ "slug": "cloud" }] }),+ )+ .await;+ assert!(+ err_message(&reserved, "voice_update_provider_settings reserved")+ .contains("is reserved and cannot be used"),+ "the reserved-slug guard must hold"+ );++ // Failure path: each enum is validated with a message naming the valid set.+ for (id, field, value, expected) in [+ (81_010, "capability", "audio", "invalid capability 'audio'"),+ (81_011, "auth_style", "basic", "invalid auth_style 'basic'"),+ (+ 81_012,+ "stt_api_style",+ "whisper",+ "invalid stt_api_style 'whisper'",+ ),+ (+ 81_013,+ "tts_api_style",+ "azure",+ "invalid tts_api_style 'azure'",+ ),+ ] {+ // Built as a Map rather than inline in `json!` because the key is a+ // loop variable, not a literal.+ let mut provider = serde_json::Map::new();+ provider.insert("slug".to_string(), json!("acme"));+ provider.insert(field.to_string(), json!(value));+ let bad = harness+ .rpc(+ id,+ "openhuman.voice_update_provider_settings",+ json!({ "voice_providers": [Value::Object(provider)] }),+ )+ .await;+ let message = err_message(&bad, &format!("voice_update_provider_settings {field}"));+ assert!(+ message.contains(expected),+ "{field}={value} must be refused by name, got: {message}"+ );+ }++ // …and none of those refusals may have clobbered the registered provider.+ let survived = harness+ .rpc(+ 81_020,+ "openhuman.voice_update_provider_settings",+ json!({}),+ )+ .await;+ let survived = payload(&survived, "voice_update_provider_settings no-op")+ .get("voice_providers")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("voice_providers must be an array"))+ .clone();+ assert_eq!(+ survived.len(),+ 1,+ "a rejected update must be atomic — deepgram must still be registered: {survived:?}"+ );+ assert_eq!(survived[0].get("slug"), Some(&json!("deepgram")));++ harness.shutdown();+}++// ── voice: server lifecycle ────────────────────────────────────────────────++#[tokio::test]+async fn voice_server_status_start_and_stop_report_a_consistent_state_machine() {+ let _lock = env_lock();+ let harness = setup("").await;++ // Before anything is started the status surface must still answer — a+ // settings panel that cannot render until a server exists is broken.+ let idle = harness+ .rpc(82_001, "openhuman.voice_server_status", json!({}))+ .await;+ let idle = payload(&idle, "voice_server_status cold");+ assert!(+ idle.get("state").and_then(Value::as_str).is_some(),+ "status must always carry a state: {idle}"+ );+ for field in ["state", "hotkey", "activation_mode", "transcription_count"] {+ assert!(+ idle.get(field).is_some(),+ "voice server status is missing `{field}`: {idle}"+ );+ }++ // Stopping a server that was never started reports stopped rather than+ // erroring — the UI's stop button must be idempotent.+ let stopped = harness+ .rpc(82_002, "openhuman.voice_server_stop", json!({}))+ .await;+ let stopped = payload(&stopped, "voice_server_stop cold");+ assert_eq!(+ stopped.get("state"),+ Some(&json!("stopped")),+ "stopping an unstarted server must report stopped: {stopped}"+ );+ assert_eq!(stopped.get("transcription_count"), Some(&json!(0)));++ // Start with an explicit, deliberately non-`fn` hotkey. On macOS every+ // non-`fn` key is refused before any event tap is created (#2677), so this+ // exercises the lifecycle without a test capturing global input.+ let started = harness+ .rpc(+ 82_003,+ "openhuman.voice_server_start",+ json!({ "hotkey": "ctrl+alt+shift+f9", "activation_mode": "tap", "skip_cleanup": true }),+ )+ .await;+ let started = payload(&started, "voice_server_start");+ assert_eq!(+ started.get("hotkey"),+ Some(&json!("ctrl+alt+shift+f9")),+ "the requested hotkey must be reflected in the status: {started}"+ );+ assert_eq!(+ started.get("activation_mode"),+ Some(&json!("tap")),+ "the requested activation mode must be reflected: {started}"+ );+ let state = started+ .get("state")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ assert!(+ matches!(+ state.as_str(),+ "stopped" | "idle" | "recording" | "processing"+ ),+ "state must be one of the declared variants, got: {state}"+ );++ // Whatever the host allowed, the singleton is now initialised and both+ // read RPCs must agree with each other.+ let after = harness+ .rpc(82_004, "openhuman.voice_server_status", json!({}))+ .await;+ let after = payload(&after, "voice_server_status after start");+ assert_eq!(+ after.get("hotkey"),+ started.get("hotkey"),+ "status and start must describe the same server: {after}"+ );++ // A start with a *different* config while running must be refused rather+ // than silently rebinding the user's hotkey under them. Only assert that+ // when the server actually came up — on a host that refused the listener+ // there is nothing running to conflict with.+ if state != "stopped" {+ let conflicting = harness+ .rpc(+ 82_005,+ "openhuman.voice_server_start",+ json!({ "hotkey": "ctrl+alt+shift+f10", "activation_mode": "push" }),+ )+ .await;+ assert!(+ err_message(&conflicting, "voice_server_start conflicting").contains("stop it first"),+ "a conflicting start must refuse and say how to resolve it"+ );+ }++ // Always leave the singleton stopped — another suite shares this process.+ let final_stop = harness+ .rpc(82_006, "openhuman.voice_server_stop", json!({}))+ .await;+ assert_eq!(+ payload(&final_stop, "voice_server_stop final").get("state"),+ Some(&json!("stopped")),+ "stop must land the server in the stopped state"+ );++ harness.shutdown();+}++// ── voice: overlay STT notify ──────────────────────────────────────────────++#[tokio::test]+async fn voice_overlay_stt_notify_accepts_each_state_and_requires_text_for_completion() {+ let _lock = env_lock();+ let harness = setup("").await;++ for (id, state) in [+ (83_001, "recording_started"),+ (83_002, "cancelled"),+ (83_003, "error"),+ ] {+ let notified = harness+ .rpc(+ id,+ "openhuman.voice_overlay_stt_notify",+ json!({ "state": state }),+ )+ .await;+ assert_eq!(+ payload(¬ified, &format!("overlay_stt_notify {state}")).get("ok"),+ Some(&json!(true)),+ "state '{state}' must be accepted without text"+ );+ }++ let done = harness+ .rpc(+ 83_004,+ "openhuman.voice_overlay_stt_notify",+ json!({ "state": "transcription_done", "text": "hello from the overlay" }),+ )+ .await;+ assert_eq!(+ payload(&done, "overlay_stt_notify done").get("ok"),+ Some(&json!(true))+ );++ // Failure path: a completion with no transcript is meaningless and must be+ // refused rather than publishing an empty transcription into the composer.+ let no_text = harness+ .rpc(+ 83_005,+ "openhuman.voice_overlay_stt_notify",+ json!({ "state": "transcription_done" }),+ )+ .await;+ assert!(+ err_message(&no_text, "overlay_stt_notify no text")+ .contains("`text` is required for transcription_done"),+ "a completion without a transcript must be refused"+ );++ // Failure path: an unknown state.+ let bad_state = harness+ .rpc(+ 83_006,+ "openhuman.voice_overlay_stt_notify",+ json!({ "state": "listening" }),+ )+ .await;+ assert!(+ err_message(&bad_state, "overlay_stt_notify bad state").contains("invalid params"),+ "an unrecognised state must be a params error"+ );++ // Failure path: `state` is required.+ let missing = harness+ .rpc(83_007, "openhuman.voice_overlay_stt_notify", json!({}))+ .await;+ assert!(+ err_message(&missing, "overlay_stt_notify missing")+ .contains("missing required param 'state'"),+ "an omitted state must be refused at the dispatch boundary"+ );++ harness.shutdown();+}++// ── voice: backend-bound synthesis and transcription ───────────────────────++#[tokio::test]+async fn voice_tts_dispatch_and_reply_synthesize_route_through_the_configured_provider() {+ let _lock = env_lock();+ let harness = setup("").await;++ // Every path here needs a session, and the "no session" branch is worth+ // asserting first — it is the state a signed-out user is in.+ let unauthenticated = harness+ .rpc(+ 84_001,+ "openhuman.voice_tts_dispatch",+ json!({ "text": "hello", "provider": "cloud" }),+ )+ .await;+ assert!(+ err_message(&unauthenticated, "voice_tts_dispatch no session")+ .contains("no backend session token"),+ "a signed-out user must be told to sign in, not given an opaque failure"+ );++ harness.store_session(84_002).await;++ // tts_dispatch with an explicit provider + voice.+ let dispatched = harness+ .rpc(+ 84_003,+ "openhuman.voice_tts_dispatch",+ json!({ "text": "hello from e2e", "provider": "cloud", "voice": "voice_abc" }),+ )+ .await;+ let dispatched = payload(&dispatched, "voice_tts_dispatch");+ assert_eq!(+ dispatched.get("audio_mime"),+ Some(&json!("audio/mpeg")),+ "the backend's mime must be carried through verbatim: {dispatched}"+ );+ assert_eq!(+ dispatched.get("audio_base64"),+ Some(&json!(FAKE_MP3_BASE64)),+ "the audio payload must reach the caller unmodified: {dispatched}"+ );+ let visemes = dispatched+ .get("visemes")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("visemes must be an array: {dispatched}"));+ assert_eq!(+ visemes.len(),+ 2,+ "both viseme frames must be normalised, not dropped: {dispatched}"+ );+ assert_eq!(visemes[0].get("viseme"), Some(&json!("AA")));+ assert_eq!(visemes[1].get("end_ms"), Some(&json!(240)));++ // reply_synthesize honours the *configured* provider rather than always+ // hitting the cloud proxy. Pin it to cloud, then prove the voice id the+ // caller passed reached the backend.+ let _ = harness+ .rpc(+ 84_004,+ "openhuman.voice_set_providers",+ json!({ "tts_provider": "cloud" }),+ )+ .await;+ let synthesized = harness+ .rpc(+ 84_005,+ "openhuman.voice_reply_synthesize",+ json!({ "text": "spoken reply", "voice_id": "voice_reply_42" }),+ )+ .await;+ let synthesized = payload(&synthesized, "voice_reply_synthesize");+ assert_eq!(synthesized.get("audio_mime"), Some(&json!("audio/mpeg")));+ assert_eq!(+ synthesized.get("audio_base64"),+ Some(&json!(FAKE_MP3_BASE64))+ );++ // Failure path: the backend rejects empty text, and that rejection must+ // surface rather than being swallowed into a silent empty clip.+ let empty = harness+ .rpc(+ 84_006,+ "openhuman.voice_reply_synthesize",+ json!({ "text": " " }),+ )+ .await;+ assert!(+ err_message(&empty, "voice_reply_synthesize empty").contains("text is required"),+ "empty text must be refused"+ );++ // Failure path: `text` is required by the param schema.+ let missing = harness+ .rpc(84_007, "openhuman.voice_tts_dispatch", json!({}))+ .await;+ assert!(+ err_message(&missing, "voice_tts_dispatch missing text")+ .contains("missing required param 'text'"),+ "an omitted `text` must be refused at the dispatch boundary"+ );++ // Failure path: an unregistered provider slug cannot be dispatched to.+ let unregistered = harness+ .rpc(+ 84_008,+ "openhuman.voice_tts_dispatch",+ json!({ "text": "hi", "provider": "not-a-provider" }),+ )+ .await;+ assert!(+ err_message(&unregistered, "voice_tts_dispatch unregistered")+ .contains("no voice provider with slug 'not-a-provider'"),+ "dispatching to an unknown slug must name the slug"+ );++ harness.shutdown();+}++#[tokio::test]+async fn voice_stt_dispatch_and_transcribe_bytes_reach_the_backend_transcription_proxy() {+ let _lock = env_lock();+ let harness = setup("").await;++ // Signed-out first.+ let unauthenticated = harness+ .rpc(+ 85_001,+ "openhuman.voice_stt_dispatch",+ json!({ "audio_base64": FAKE_MP3_BASE64, "provider": "cloud" }),+ )+ .await;+ assert!(+ err_message(&unauthenticated, "voice_stt_dispatch no session")+ .contains("no backend session token"),+ "a signed-out transcription must say to sign in"+ );++ harness.store_session(85_002).await;++ let dispatched = harness+ .rpc(+ 85_003,+ "openhuman.voice_stt_dispatch",+ json!({+ "audio_base64": FAKE_MP3_BASE64,+ "provider": "cloud",+ "mime_type": "audio/mpeg",+ "file_name": "clip.mp3",+ "language": "en"+ }),+ )+ .await;+ let dispatched = payload(&dispatched, "voice_stt_dispatch");+ assert_eq!(+ dispatched.get("provider"),+ Some(&json!("cloud")),+ "the dispatch reply must name the provider that served it: {dispatched}"+ );+ let text = dispatched+ .get("text")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ text.starts_with("transcribed by "),+ "the backend's transcript must reach the caller: {dispatched}"+ );++ // Failure paths on the decode guard — these run before any network call,+ // so a malformed clip never costs the user an upload.+ let not_base64 = harness+ .rpc(+ 85_004,+ "openhuman.voice_stt_dispatch",+ json!({ "audio_base64": "!!!not base64!!!", "provider": "cloud" }),+ )+ .await;+ assert!(+ err_message(¬_base64, "voice_stt_dispatch bad base64").contains("invalid base64 audio"),+ "an undecodable payload must be rejected before upload"+ );++ let empty = harness+ .rpc(+ 85_005,+ "openhuman.voice_stt_dispatch",+ json!({ "audio_base64": "", "provider": "cloud" }),+ )+ .await;+ assert!(+ err_message(&empty, "voice_stt_dispatch empty").contains("audio_base64 is required"),+ "an empty payload must be refused"+ );++ // transcribe_bytes takes raw bytes and an extension. Its extension guard+ // is the thing worth pinning: it becomes a temp file name.+ let bad_ext = harness+ .rpc(+ 85_006,+ "openhuman.voice_transcribe_bytes",+ json!({ "audio_bytes": [1, 2, 3], "extension": "wav/../../etc" }),+ )+ .await;+ assert!(+ err_message(&bad_ext, "voice_transcribe_bytes bad ext").contains("must be alphanumeric"),+ "a non-alphanumeric extension must be refused — it names a temp file"+ );++ let blank_ext = harness+ .rpc(+ 85_007,+ "openhuman.voice_transcribe_bytes",+ json!({ "audio_bytes": [1, 2, 3], "extension": "." }),+ )+ .await;+ assert!(+ err_message(&blank_ext, "voice_transcribe_bytes blank ext").contains("must not be empty"),+ "an extension that trims to nothing must be refused"+ );++ let missing_bytes = harness+ .rpc(85_008, "openhuman.voice_transcribe_bytes", json!({}))+ .await;+ assert!(+ err_message(&missing_bytes, "voice_transcribe_bytes missing")+ .contains("missing required param 'audio_bytes'"),+ "an omitted `audio_bytes` must be refused at the dispatch boundary"+ );++ // voice_transcribe reads a file path; a path that does not exist must fail+ // with a reason rather than returning an empty transcript, which the UI+ // would render as "no speech detected".+ let missing_file = harness+ .rpc(+ 85_009,+ "openhuman.voice_transcribe",+ json!({ "audio_path": harness.home().join("nope.wav").to_str().unwrap(), "skip_cleanup": true }),+ )+ .await;+ assert!(+ !err_message(&missing_file, "voice_transcribe missing file").is_empty(),+ "transcribing a nonexistent file must fail with a reason"+ );++ let no_path = harness+ .rpc(85_010, "openhuman.voice_transcribe", json!({}))+ .await;+ assert!(+ err_message(&no_path, "voice_transcribe no path")+ .contains("missing required param 'audio_path'"),+ "an omitted `audio_path` must be refused at the dispatch boundary"+ );++ harness.shutdown();+}++// ── voice: realtime agent signed URL ───────────────────────────────────────++#[tokio::test]+async fn voice_agent_signed_url_mints_from_the_backend_and_refuses_without_a_session() {+ let _lock = env_lock();+ let harness = setup("").await;++ let signed_out = harness+ .rpc(86_001, "openhuman.voice_agent_signed_url", json!({}))+ .await;+ assert!(+ err_message(&signed_out, "voice_agent_signed_url signed out")+ .contains("no backend session token; sign in first"),+ "minting without a session must say to sign in"+ );++ harness.store_session(86_002).await;++ let minted = harness+ .rpc(86_003, "openhuman.voice_agent_signed_url", json!({}))+ .await;+ let minted = payload(&minted, "voice_agent_signed_url");+ assert_eq!(+ minted.get("agent_id").or_else(|| minted.get("agentId")),+ Some(&json!("agent_e2e_001")),+ "the backend's agent id must be unwrapped from its envelope: {minted}"+ );+ let url = minted+ .get("signed_url")+ .or_else(|| minted.get("signedUrl"))+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert_eq!(+ url, "wss://voice.e2e.test/convai?token=e2e-signed",+ "the signed URL must round-trip verbatim: {minted}"+ );++ harness.shutdown();+}++// ── voice: local Piper TTS ─────────────────────────────────────────────────++#[cfg(unix)]+#[tokio::test]+async fn voice_tts_writes_a_local_wav_through_piper_and_reports_the_disabled_runtime() {+ let _lock = env_lock();++ // `runtime_enabled = false` is the first gate `local_ai::tts` checks, and+ // it is what a user with local AI switched off will hit.+ let disabled = setup("").await;+ let refused = disabled+ .rpc(87_001, "openhuman.voice_tts", json!({ "text": "hello" }))+ .await;+ assert!(+ err_message(&refused, "voice_tts disabled").contains("local ai is disabled"),+ "local TTS with the runtime off must say so"+ );+ let no_text = disabled.rpc(87_002, "openhuman.voice_tts", json!({})).await;+ assert!(+ err_message(&no_text, "voice_tts no text").contains("missing required param 'text'"),+ "an omitted `text` must be refused at the dispatch boundary"+ );+ disabled.shutdown();++ // Now the happy path, with the runtime on and a stub piper + stub voice.+ let harness = setup("[local_ai]\nruntime_enabled = true\n").await;+ let voice_model = harness.home().join("stub-voice.onnx");+ std::fs::write(&voice_model, b"not a real onnx, only a path").expect("write stub voice");+ let piper = write_piper_stub(&harness.home().join("stub-bin"));++ // `tts_voice_id` is read as a path first, so pointing it at a real file is+ // what lets `resolve_tts_voice_path` succeed without a model download.+ let _ = harness+ .rpc(+ 87_003,+ "openhuman.voice_set_providers",+ json!({ "tts_voice": voice_model.to_str().unwrap() }),+ )+ .await;+ let _piper_guard = EnvVarGuard::set_to_path("PIPER_BIN", &piper);++ let out_path = harness.workspace().join("tts-e2e.wav");+ let synthesized = harness+ .rpc(+ 87_004,+ "openhuman.voice_tts",+ json!({ "text": "hello local", "output_path": out_path.to_str().unwrap() }),+ )+ .await;+ let synthesized = payload(&synthesized, "voice_tts piper");+ assert_eq!(+ synthesized.get("output_path").and_then(Value::as_str),+ Some(out_path.display().to_string().as_str()),+ "the requested output path must be honoured and reported: {synthesized}"+ );+ let written = std::fs::read(&out_path).expect("piper must have written the wav");+ assert!(+ written.starts_with(b"RIFF"),+ "the reported file must actually be the synthesized audio, not an empty stub"+ );++ harness.shutdown();+}++// ── audio_toolkit ──────────────────────────────────────────────────────────++#[tokio::test]+async fn audio_toolkit_generates_emails_and_combines_the_podcast_flow() {+ let _lock = env_lock();+ let harness = setup("").await;+ harness.store_session(88_001).await;++ // Capture mode writes the composed MIME message to the workspace instead of+ // opening an SMTP connection, which is what makes the email half of this+ // namespace testable at all.+ let capture_dir = harness.workspace().join("email-capture");+ let _capture = EnvVarGuard::set_to_path("OPENHUMAN_EMAIL_CAPTURE_DIR", &capture_dir);++ // generate_podcast — cloud TTS via the mock backend, written under the+ // workspace.+ let generated = harness+ .rpc(+ 88_002,+ "openhuman.audio_toolkit_generate_podcast",+ json!({+ "text": "Chapter one. The lazy senior developer.",+ "title": "Ponytail Weekly",+ "provider": "cloud",+ "format": "mp3"+ }),+ )+ .await;+ let generated = payload(&generated, "audio_toolkit_generate_podcast");+ assert_eq!(generated.get("provider"), Some(&json!("cloud")));+ assert_eq!(generated.get("format"), Some(&json!("mp3")));+ assert_eq!(generated.get("audio_mime"), Some(&json!("audio/mpeg")));+ assert_eq!(+ generated.get("chars_synthesized"),+ Some(&json!(39)),+ "the synthesized character count must reflect the trimmed input: {generated}"+ );+ let rel_path = generated+ .get("output_path")+ .and_then(Value::as_str)+ .expect("output_path")+ .to_string();+ assert!(+ rel_path.starts_with("artifacts/audio/"),+ "the default output path must land in the audio artifacts dir: {rel_path}"+ );+ assert!(+ rel_path.ends_with("-ponytail-weekly.mp3"),+ "the title must be slugified into the file name: {rel_path}"+ );+ let on_disk = harness.workspace().join(&rel_path);+ assert!(+ on_disk.is_file(),+ "the audio must actually be written to {}",+ on_disk.display()+ );+ assert_eq!(+ generated.get("bytes_written").and_then(Value::as_u64),+ Some(std::fs::metadata(&on_disk).expect("stat audio").len()),+ "the reported byte count must match the file on disk: {generated}"+ );++ // email_podcast — attach the file just generated.+ let emailed = harness+ .rpc(+ 88_003,+ "openhuman.audio_toolkit_email_podcast",+ json!({+ "to": "[email protected]",+ "subject": "Your podcast",+ "body": "Attached.",+ "audio_path": rel_path,+ "attachment_name": "weekly.mp3"+ }),+ )+ .await;+ let emailed = payload(&emailed, "audio_toolkit_email_podcast");+ assert_eq!(emailed.get("to"), Some(&json!("[email protected]")));+ assert_eq!(emailed.get("subject"), Some(&json!("Your podcast")));+ assert_eq!(emailed.get("attachment_name"), Some(&json!("weekly.mp3")));+ assert_eq!(+ emailed.get("mode"),+ Some(&json!("capture")),+ "with a capture dir set the message must be captured, never sent: {emailed}"+ );+ let capture_rel = emailed+ .get("capture_path")+ .and_then(Value::as_str)+ .expect("capture_path")+ .to_string();+ let eml = std::fs::read_to_string(harness.workspace().join(&capture_rel))+ .expect("the captured .eml must exist");+ assert!(+ eml.contains("To: [email protected]"),+ "the captured message must address the recipient: {eml:.400}"+ );+ assert!(+ eml.contains("Subject: Your podcast"),+ "the captured message must carry the subject: {eml:.400}"+ );+ assert!(+ eml.contains("weekly.mp3"),+ "the attachment name must appear in the MIME part: {eml:.400}"+ );+ assert!(+ eml.contains("audio/mpeg"),+ "the attachment content type must be derived from the file name: {eml:.400}"+ );++ // generate_and_email_podcast — the combined flow must thread the generated+ // path into the email, which is the one thing the two-call version cannot+ // get wrong and the combined one can.+ let combined = harness+ .rpc(+ 88_004,+ "openhuman.audio_toolkit_generate_and_email_podcast",+ json!({+ "text": "Combined flow.",+ "to": "[email protected]",+ "subject": "Combined",+ "body": "Generated and sent.",+ "title": "Combined Episode",+ "provider": "cloud",+ "format": "mp3"+ }),+ )+ .await;+ let combined = payload(&combined, "audio_toolkit_generate_and_email_podcast");+ let audio_path = combined+ .pointer("/audio/output_path")+ .and_then(Value::as_str)+ .expect("combined audio output_path")+ .to_string();+ assert!(+ audio_path.ends_with("-combined-episode.mp3"),+ "the combined flow must slugify its own title: {audio_path}"+ );+ assert!(+ harness.workspace().join(&audio_path).is_file(),+ "the combined flow must write the audio it claims to have emailed"+ );+ assert_eq!(+ combined.pointer("/email/mode"),+ Some(&json!("capture")),+ "the combined flow must go through the same delivery path: {combined}"+ );+ let combined_attachment = combined+ .pointer("/email/attachment_name")+ .and_then(Value::as_str)+ .expect("combined attachment_name");+ assert!(+ audio_path.ends_with(combined_attachment),+ "with no explicit attachment name the generated file's name must be used \+ — this is the seam where an empty audio_path used to slip through: \+ audio={audio_path} attachment={combined_attachment}"+ );++ harness.shutdown();+}++#[tokio::test]+async fn audio_toolkit_refuses_bad_paths_formats_and_missing_fields() {+ let _lock = env_lock();+ let harness = setup("").await;+ let capture_dir = harness.workspace().join("email-capture");+ let _capture = EnvVarGuard::set_to_path("OPENHUMAN_EMAIL_CAPTURE_DIR", &capture_dir);++ // Provider/format incompatibilities are refused before any synthesis is+ // attempted — the user gets told which combination to pick.+ let cloud_wav = harness+ .rpc(+ 89_001,+ "openhuman.audio_toolkit_generate_podcast",+ json!({ "text": "x", "provider": "cloud", "format": "wav" }),+ )+ .await;+ assert!(+ err_message(&cloud_wav, "generate_podcast cloud+wav")+ .contains("provider `cloud` currently returns mp3 output only"),+ "cloud+wav must be refused with the fix named"+ );++ let piper_mp3 = harness+ .rpc(+ 89_002,+ "openhuman.audio_toolkit_generate_podcast",+ json!({ "text": "x", "provider": "piper", "format": "mp3" }),+ )+ .await;+ assert!(+ err_message(&piper_mp3, "generate_podcast piper+mp3")+ .contains("provider `piper` only supports wav output"),+ "piper+mp3 must be refused with the fix named"+ );++ // Empty text short-circuits before the provider is even constructed.+ let empty = harness+ .rpc(+ 89_003,+ "openhuman.audio_toolkit_generate_podcast",+ json!({ "text": " " }),+ )+ .await;+ assert!(+ err_message(&empty, "generate_podcast empty").contains("text is required"),+ "empty text must be refused"+ );++ // The workspace confinement on the output path is the security boundary of+ // this namespace: without it a caller could write anywhere on the host.+ let absolute = harness+ .rpc(+ 89_004,+ "openhuman.audio_toolkit_generate_podcast",+ json!({ "text": "x", "provider": "cloud", "output_path": "/tmp/escape.mp3" }),+ )+ .await;+ assert!(+ err_message(&absolute, "generate_podcast absolute path")+ .contains("output_path must be workspace-relative"),+ "an absolute output path must be refused"+ );++ let traversal = harness+ .rpc(+ 89_005,+ "openhuman.audio_toolkit_generate_podcast",+ json!({ "text": "x", "provider": "cloud", "output_path": "../../escape.mp3" }),+ )+ .await;+ assert!(+ err_message(&traversal, "generate_podcast traversal")+ .contains("must not contain parent-directory traversal"),+ "a traversing output path must be refused"+ );++ // The same confinement on the *read* side of email_podcast.+ for (id, path, expected) in [+ (+ 89_010,+ "/etc/passwd",+ "audio_path must be workspace-relative",+ ),+ (+ 89_011,+ "../../../etc/passwd",+ "must not contain parent-directory traversal",+ ),+ ] {+ let refused = harness+ .rpc(+ id,+ "openhuman.audio_toolkit_email_podcast",+ json!({+ "to": "[email protected]",+ "subject": "s",+ "body": "b",+ "audio_path": path+ }),+ )+ .await;+ assert!(+ err_message(&refused, "email_podcast confinement").contains(expected),+ "email_podcast must refuse '{path}'"+ );+ }++ // Each required email field is validated by name.+ for (id, field, params) in [+ (+ 89_020,+ "to",+ json!({ "to": " ", "subject": "s", "body": "b", "audio_path": "a.mp3" }),+ ),+ (+ 89_021,+ "subject",+ json!({ "to": "[email protected]", "subject": " ", "body": "b", "audio_path": "a.mp3" }),+ ),+ (+ 89_022,+ "body",+ json!({ "to": "[email protected]", "subject": "s", "body": " ", "audio_path": "a.mp3" }),+ ),+ (+ 89_023,+ "audio_path",+ json!({ "to": "[email protected]", "subject": "s", "body": "b", "audio_path": " " }),+ ),+ ] {+ let refused = harness+ .rpc(id, "openhuman.audio_toolkit_email_podcast", params)+ .await;+ let message = err_message(&refused, &format!("email_podcast blank {field}"));+ assert!(+ message.contains(&format!("{field} is required")),+ "a blank `{field}` must be named in the error, got: {message}"+ );+ }++ // A workspace-relative path that simply is not there.+ let absent = harness+ .rpc(+ 89_030,+ "openhuman.audio_toolkit_email_podcast",+ json!({+ "to": "[email protected]",+ "subject": "s",+ "body": "b",+ "audio_path": "artifacts/audio/nope.mp3"+ }),+ )+ .await;+ assert!(+ err_message(&absent, "email_podcast absent file").contains("failed to read"),+ "emailing a missing attachment must fail with a read error"+ );++ // The combined flow inherits every one of those guards.+ let combined_bad = harness+ .rpc(+ 89_040,+ "openhuman.audio_toolkit_generate_and_email_podcast",+ json!({+ "text": "x",+ "to": "[email protected]",+ "subject": "s",+ "body": "b",+ "provider": "cloud",+ "format": "wav"+ }),+ )+ .await;+ assert!(+ err_message(&combined_bad, "generate_and_email cloud+wav")+ .contains("provider `cloud` currently returns mp3 output only"),+ "the combined flow must validate before it generates"+ );++ // …and must not have written anything on the way to that refusal.+ assert!(+ !harness.workspace().join("artifacts").exists(),+ "a refused generate must leave no artifacts directory behind"+ );++ harness.shutdown();+}