The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rs,tes
Steven Enamakel32e4891fde38
diff --git a/tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rs b/tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rsdeleted file mode 100644index 21976e5820..0000000000--- a/tests/raw_coverage/channels_lark_email_dispatch_round21_raw_coverage_e2e.rs+++ /dev/null@@ -1,43 +0,0 @@-//! Round21 raw integration coverage for channels provider seams.-//!-//! Parser fixtures only: no real IMAP or SMTP traffic is performed.--use tinychannels::providers::email_channel::{- test_support as email_support, EmailChannel, EmailConfig,-};--#[test]-fn email_parser_support_covers_text_html_attachment_and_message_building() {- let text_raw = b"From: Alice <[email protected]>\r\nSubject: Plain\r\nMessage-ID: <[email protected]>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nHello from plain text.\r\n";- let parsed = email_support::parse_email_fixture(text_raw).expect("plain parse");- assert_eq!(parsed.sender, "[email protected]");- assert_eq!(parsed.subject.as_deref(), Some("Plain"));- assert!(parsed.text.contains("Hello from plain text."));-- let html_raw = b"From: Bob <[email protected]>\r\nSubject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<div>Hello <strong>HTML</strong> body</div>\r\n";- let parsed_html = email_support::parse_email_fixture(html_raw).expect("html parse");- assert_eq!(parsed_html.sender, "[email protected]");- assert_eq!(parsed_html.text, "Hello HTML body");-- let attachment_raw = b"From: Ops <[email protected]>\r\nSubject: Attachment\r\nContent-Type: multipart/mixed; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Disposition: attachment; filename=\"note.txt\"\r\n\r\nattachment text body\r\n--b--\r\n";- let parsed_attachment =- email_support::parse_email_fixture(attachment_raw).expect("attachment parse");- assert!(parsed_attachment.text.contains("[Attachment: note.txt]"));- assert!(parsed_attachment.text.contains("attachment text body"));-- let channel = EmailChannel::new(EmailConfig {- from_address: "[email protected]".into(),- allowed_senders: vec!["@example.com".into(), "trusted.test".into()],- ..Default::default()- });- assert!(channel.is_sender_allowed("[email protected]"));- assert!(channel.is_sender_allowed("[email protected]"));- assert!(!channel.is_sender_allowed("[email protected]"));-- let message = channel- .build_plain_message("[email protected]", "Round21", "coverage body")- .expect("build message");- let wire = String::from_utf8_lossy(&message.formatted()).to_string();- assert!(wire.contains("Subject: Round21"));- assert!(wire.contains("coverage body"));-}diff --git a/tests/raw_coverage/channels_round24_raw_coverage_e2e.rs b/tests/raw_coverage/channels_round24_raw_coverage_e2e.rsdeleted file mode 100644index f2b70c0737..0000000000--- a/tests/raw_coverage/channels_round24_raw_coverage_e2e.rs+++ /dev/null@@ -1,126 +0,0 @@-//! Round24 raw integration coverage for broad cold channel helpers.-//!-//! Parser/state seams only: no real network traffic.--use openhuman_core::channels::test_support as runtime_support;-use serde_json::json;-use tinychannels::delivery::progressive::{- extract_message_id, latest_thinking_snippet, StreamingState,-};-use tinychannels::providers::email_channel::test_support as email_support;-use tinychannels::ChannelMessage;--fn channel_message(channel: &str, reply_target: &str, content: &str) -> ChannelMessage {- ChannelMessage {- id: "msg-1".to_string(),- sender: "sender-1".to_string(),- reply_target: reply_target.to_string(),- content: content.to_string(),- channel: channel.to_string(),- timestamp: 1,- thread_ts: None,- sender_name: None,- }-}--#[test]-fn bus_state_helpers_cover_message_ids_drafts_snippets_and_thread_keys() {- assert_eq!(- extract_message_id(&json!({"id": "abc"})).as_deref(),- Some("abc")- );- assert_eq!(- extract_message_id(&json!({"messageId": 42})).as_deref(),- Some("42")- );- assert_eq!(- extract_message_id(&json!({"data": {"messageId": 99_u64}})).as_deref(),- Some("99")- );- assert!(extract_message_id(&json!({"ok": true})).is_none());-- assert_eq!(StreamingState::default().compose_draft(), "_working…_");- assert_eq!(- StreamingState {- content: "answer with trailing space ".into(),- ..Default::default()- }- .compose_draft(),- "answer with trailing space"- );-- assert!(latest_thinking_snippet(&StreamingState {- thinking_accumulator: " ".into(),- ..Default::default()- })- .is_none());- let long_thinking = format!("prefix {}", "alpha ".repeat(80));- let snippet = latest_thinking_snippet(&StreamingState {- thinking_accumulator: long_thinking,- ..Default::default()- })- .expect("snippet");- assert!(snippet.len() <= 200);- assert!(snippet.starts_with("alpha"));-- assert_eq!(- tinychannels::channel::derive_inbound_thread_id(- "slack:T1",- Some(" U1 "),- Some(" C1 "),- Some(" 1700.1 "),- ),- "channel:slack:T1/U1/C1#thread:1700.1"- );- assert_eq!(- tinychannels::channel::derive_inbound_thread_id(- "telegram:123",- Some("U1"),- Some("123"),- Some("message-specific"),- ),- "channel:telegram:123/U1/123"- );-}--#[test]-fn dispatch_helpers_cover_channel_context_and_ack_categories() {- let web = channel_message("web", "thread-1", "hello");- assert!(runtime_support::build_channel_context_block_for_test(&web).is_empty());-- let telegram = channel_message("telegram", "chat-42", "remind me tomorrow");- let context = runtime_support::build_channel_context_block_for_test(&telegram);- assert!(context.contains("telegram"));- // The job records its origin, so the model is told reminders return to- // this chat on their own and is not handed a target to copy.- assert!(context.contains("delivered back to this chat automatically"));- assert!(!context.contains("chat-42"));- assert!(!context.contains("cron_add"));-- let no_target = channel_message("slack", "", "hello");- assert!(runtime_support::build_channel_context_block_for_test(&no_target).is_empty());-- let gratitude = tinychannels::runtime::select_acknowledgment_reaction("thank you");- assert!(["❤️", "🙏"].contains(&gratitude));- let finance = tinychannels::runtime::select_acknowledgment_reaction("btc market?");- assert!(["💯", "⚡"].contains(&finance));- let code = tinychannels::runtime::select_acknowledgment_reaction("debug this rust api");- assert!(["👨💻", "🤓"].contains(&code));- let greeting = tinychannels::runtime::select_acknowledgment_reaction("hello there");- assert!(["🤗", "😁"].contains(&greeting));- let question = tinychannels::runtime::select_acknowledgment_reaction("what happened?");- assert!(["🤔", "✍️"].contains(&question));-}--#[test]-fn email_parser_edges_are_exercised_without_sockets() {- let no_sender = b"Subject: Anonymous\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nbody";- let parsed_mail = email_support::parse_email_fixture(no_sender).expect("mail parse");- assert_eq!(parsed_mail.sender, "unknown");- assert_eq!(parsed_mail.text, "body");-- let html_only =- b"From: Html <[email protected]>\r\nContent-Type: text/html\r\n\r\n<p>A</p><p>B</p>";- let parsed_html = email_support::parse_email_fixture(html_only).expect("html parse");- assert_eq!(parsed_html.text, "A\nB\n");-}diff --git a/tests/raw_coverage/channels_round26_raw_coverage_e2e.rs b/tests/raw_coverage/channels_telegram_loopback_e2e.rssimilarity index 100%rename from tests/raw_coverage/channels_round26_raw_coverage_e2e.rsrename to tests/raw_coverage/channels_telegram_loopback_e2e.rsdiff --git a/tests/raw_coverage/composio_raw_coverage_e2e.rs b/tests/raw_coverage/composio_raw_coverage_e2e.rsdeleted file mode 100644index 5fe7f326f2..0000000000--- a/tests/raw_coverage/composio_raw_coverage_e2e.rs+++ /dev/null@@ -1,475 +0,0 @@-//! Raw-line oriented coverage for deterministic Composio helpers.-//!-//! These tests avoid live Composio/backend calls and exercise public helper-//! surfaces that feed the JSON-RPC and agent-tool paths.--use openhuman_core::core::runtime::DispatchCtx;-use std::sync::{Arc, OnceLock};--use serde_json::{json, Value};-use tempfile::tempdir;--use openhuman_core::agent::prompts::ConnectedIntegration;-use openhuman_core::config::Config;-use openhuman_core::core::all::RegisteredController;-use openhuman_core::integrations::composio::client::{resolve_composio_route, ComposioRoute};-use openhuman_core::integrations::composio::{- all_composio_controller_schemas, all_composio_registered_controllers,- cached_active_integrations, connected_set_hash, connection_identity,- fetch_connected_integrations, fetch_connected_integrations_status,- invalidate_connected_integrations_cache, ComposioActionTool, FetchConnectedIntegrationsStatus,-};--use tinytools::Tool;--static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;--#[tokio::test]-async fn composio_connected_integrations_public_helpers_handle_empty_auth_and_identity_edges() {- crate::tinyhumans_boot::boot();- let dir = tempdir().expect("tempdir");- let config = Config {- workspace_dir: dir.path().to_path_buf(),- config_path: dir.path().join("config.toml"),- ..Config::default()- };-- invalidate_connected_integrations_cache();- assert!(cached_active_integrations(&config).is_none());-- let first = ConnectedIntegration {- toolkit: "gmail".into(),- description: "Gmail".into(),- tools: Vec::new(),- gated_tools: Vec::new(),- connected: true,- connections: Vec::new(),- non_active_status: None,- };- let second = ConnectedIntegration {- toolkit: "slack".into(),- description: "Slack".into(),- tools: Vec::new(),- gated_tools: Vec::new(),- connected: true,- connections: Vec::new(),- non_active_status: None,- };- let disconnected = ConnectedIntegration {- toolkit: "notion".into(),- description: "Notion".into(),- tools: Vec::new(),- gated_tools: Vec::new(),- connected: false,- connections: Vec::new(),- non_active_status: Some("EXPIRED".into()),- };- assert_eq!(- connected_set_hash(&[first.clone(), second.clone(), disconnected.clone()]),- connected_set_hash(&[disconnected, second, first])- );- assert_ne!(- connected_set_hash(&[]),- connected_set_hash(&[ConnectedIntegration {- toolkit: "gmail".into(),- description: String::new(),- tools: Vec::new(),- gated_tools: Vec::new(),- connected: true,- connections: Vec::new(),- non_active_status: None,- }])- );-- let status = fetch_connected_integrations_status(&config).await;- assert!(matches!(- status,- FetchConnectedIntegrationsStatus::Unavailable- ));- assert!(fetch_connected_integrations(&config).await.is_empty());- assert!(cached_active_integrations(&config).is_none());-- assert_eq!(connection_identity(&config, " ").await, None);- assert_eq!(connection_identity(&config, "unknown-toolkit").await, None);-}--#[tokio::test]-async fn composio_ops_mode_is_local_and_trigger_history_reads_the_module_archive() {- let _module = crate::CONNECTOR_MODULE_LOCK.lock().await;- // The connector module keeps the trigger archive in host storage.- let env_lock = ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock()- .await;- let _storage = crate::HostStorage::install(&env_lock);- crate::tinyhumans_boot::boot();- let dir = tempdir().expect("tempdir");- let mut config = Config {- workspace_dir: dir.path().to_path_buf(),- config_path: dir.path().join("config.toml"),- ..Config::default()- };- config.composio.mode = "direct".into();- openhuman_core::integrations::composio::init_composio_trigger_history(- config.workspace_dir.clone(),- )- .expect("initialize the runtime-owned trigger archive lease");-- let mode = openhuman_core::integrations::composio::ops::composio_get_mode(&config)- .await- .expect("get mode should not call backend")- .into_cli_compatible_json()- .expect("mode outcome serializes");- assert_eq!(mode.pointer("/result/mode"), Some(&json!("direct")));- assert!(mode.pointer("/result/api_key_set").is_some());-- let history = openhuman_core::integrations::composio::ops::composio_list_trigger_history(- &openhuman_core::core::runtime::DispatchCtx::host_default(),- &config,- Some(0),- )- .await- .expect("the runtime-owned archive lease is available");- let history = history- .into_cli_compatible_json()- .expect("history outcome serializes");- assert!(history- .pointer("/result/archive_dir")- .and_then(Value::as_str)- .unwrap_or_default()- .contains("triggers"));-}--#[tokio::test]-async fn composio_action_tool_execute_reports_missing_route_without_network() {- let _module = crate::CONNECTOR_MODULE_LOCK.lock().await;- crate::tinyhumans_boot::boot();- let tmp = tempfile::tempdir().expect("temp config directory");- let config = Config {- config_path: tmp.path().join("config.toml"),- ..Default::default()- };- let tool = ComposioActionTool::new(- Arc::new(config),- "GMAIL_SEND_EMAIL".into(),- "Send an email".into(),- None,- );-- let result = tool- .execute(json!({ "to": "[email protected]", "subject": "no route" }))- .await- .expect("local validation returns a tool result");- assert!(result.is_error);- let rendered = serde_json::to_string(&result).unwrap();- assert!(rendered.contains("without a connector route"), "{rendered}");- assert!(rendered.contains("proxy"), "{rendered}");-}--#[test]-fn composio_client_factory_modes_are_deterministic_without_network() {- crate::tinyhumans_boot::boot();- let dir = tempdir().expect("tempdir");- let mut config = Config {- workspace_dir: dir.path().to_path_buf(),- config_path: dir.path().join("config.toml"),- ..Config::default()- };-- config.composio.mode = String::new();- let backend_err = match resolve_composio_route(&config) {- Ok(_) => panic!("backend without a session should fail"),- Err(error) => error,- };- assert!(backend_err.to_string().contains("no backend session token"));-- config.composio.mode = "direct".into();- let direct_err = match resolve_composio_route(&config) {- Ok(_) => panic!("direct mode without an api key should fail"),- Err(error) => error,- };- assert!(direct_err.to_string().contains("no api key is configured"));-- config.composio.api_key = Some(" cmp_test_key ".into());- let direct = resolve_composio_route(&config).expect("inline direct key builds a client");- assert_eq!(direct.mode(), "direct");- assert!(matches!(direct, ComposioRoute::Direct(_)));-- config.composio.mode = "typo".into();- let unknown = match resolve_composio_route(&config) {- Ok(_) => panic!("unknown composio mode should fail"),- Err(error) => error,- };- assert!(unknown.to_string().contains("unknown composio mode"));-}--#[tokio::test]-async fn composio_controller_registry_and_scope_handlers_cover_validation_edges() {- let env_lock = ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock()- .await;- // Scope preferences live in the connector module's host storage.- let _storage = crate::HostStorage::install(&env_lock);- crate::tinyhumans_boot::boot();- // The controller loads config through the process workspace resolver. Pin- // the test to an isolated workspace so the scope store does not depend on- // a developer's local config.- let workspace = tempdir().expect("isolated workspace");- let workspace_dir = workspace.path().join("workspace");- std::fs::create_dir_all(&workspace_dir).expect("create isolated workspace");- let _workspace = WorkspaceEnvGuard::set(&workspace_dir);- let schemas = all_composio_controller_schemas();- let registered = all_composio_registered_controllers();- assert_eq!(schemas.len(), registered.len());- assert!(schemas.iter().any(|schema| schema.function == "execute"));- assert!(schemas- .iter()- .any(|schema| schema.function == "set_api_key"));- assert!(registered.iter().all(|controller| {- controller- .rpc_method_name()- .starts_with("openhuman.composio_")- }));-- let unknown = openhuman_core::integrations::composio::schemas::schemas("not_real");- assert_eq!(unknown.function, "unknown");- assert_eq!(unknown.inputs[0].name, "function");-- let get_scopes = composio_controller(®istered, "get_user_scopes");- let scopes = composio_call(get_scopes, json!({ "toolkit": " Gmail " }))- .await- .expect("default user scopes");- assert_eq!(scopes.pointer("/read"), Some(&json!(true)));- assert_eq!(scopes.pointer("/write"), Some(&json!(true)));- assert_eq!(scopes.pointer("/admin"), Some(&json!(false)));-- let missing_toolkit = composio_call(get_scopes, json!({}))- .await- .expect_err("toolkit is required");- assert!(missing_toolkit.contains("missing required param 'toolkit'"));-- let set_scopes = composio_controller(®istered, "set_user_scopes");- let invalid_write = composio_call(- set_scopes,- json!({ "toolkit": "gmail", "read": true, "write": "yes", "admin": false }),- )- .await- .expect_err("write must be bool");- assert!(invalid_write.contains("invalid 'write'"));- // The pref persists in the connector module's host storage (b80c12358a)- // and reads back through `get_user_scopes`.- let saved = composio_call(- set_scopes,- json!({ "toolkit": " GitHub ", "read": true, "write": false, "admin": true }),- )- .await- .expect("set_user_scopes persists to host storage");- assert_eq!(saved.pointer("/admin"), Some(&json!(true)));- assert_eq!(saved.pointer("/write"), Some(&json!(false)));- let reread = composio_call(get_scopes, json!({ "toolkit": "github" }))- .await- .expect("get_user_scopes reads the stored pref");- assert_eq!(reread.pointer("/admin"), Some(&json!(true)));- assert_eq!(reread.pointer("/write"), Some(&json!(false)));- assert!(- !workspace_dir- .join("integrations")- .join("composio_user_scopes.json")- .exists(),- "the legacy workspace file is no longer written"- );-}--struct WorkspaceEnvGuard(Option<std::ffi::OsString>);--impl WorkspaceEnvGuard {- fn set(path: &std::path::Path) -> Self {- let previous = std::env::var_os("OPENHUMAN_WORKSPACE");- unsafe { std::env::set_var("OPENHUMAN_WORKSPACE", path) };- Self(previous)- }-}--impl Drop for WorkspaceEnvGuard {- fn drop(&mut self) {- match self.0.take() {- Some(previous) => unsafe { std::env::set_var("OPENHUMAN_WORKSPACE", previous) },- None => unsafe { std::env::remove_var("OPENHUMAN_WORKSPACE") },- }- }-}--#[test]-fn composio_controller_schema_catalog_covers_all_declared_functions() {- crate::tinyhumans_boot::boot();- // (function, required input names, first output name). Assert the required- // inputs are *present* rather than pinning `inputs.len() == N` — the exact- // count broke whenever an additive optional param was declared (plan.md §3).- let expected: [(&str, &[&str], &str); 22] = [- ("list_toolkits", &[], "toolkits"),- ("list_capabilities", &[], "capabilities"),- ("list_agent_ready_toolkits", &[], "toolkits"),- ("list_connections", &[], "connections"),- ("authorize", &["toolkit"], "connectUrl"),- ("delete_connection", &["connection_id"], "deleted"),- ("list_tools", &["toolkits"], "tools"),- ("execute", &["tool", "connection_id"], "result"),- ("list_github_repos", &["connection_id"], "result"),- ("create_trigger", &["slug", "connection_id"], "result"),- ("get_user_profile", &["connection_id"], "profile"),- ("refresh_all_identities", &[], "report"),- ("list_trigger_history", &["limit"], "result"),- ("get_user_scopes", &["toolkit"], "pref"),- ("set_user_scopes", &["toolkit", "read", "write"], "pref"),- ("list_available_triggers", &["toolkit"], "triggers"),- ("list_triggers", &["toolkit"], "triggers"),- ("enable_trigger", &["connection_id", "slug"], "result"),- ("disable_trigger", &["trigger_id"], "deleted"),- ("get_mode", &[], "mode"),- ("set_api_key", &["api_key"], "result"),- ("clear_api_key", &[], "result"),- ];-- for (function, required_inputs, first_output) in expected {- let schema = openhuman_core::integrations::composio::schemas::schemas(function);- assert_eq!(schema.namespace, "composio");- assert_eq!(schema.function, function);- let input_names: Vec<&str> = schema.inputs.iter().map(|f| f.name).collect();- for required in required_inputs {- assert!(- input_names.contains(required),- "{function} must declare input `{required}` (got {input_names:?})"- );- }- assert_eq!(schema.outputs[0].name, first_output, "{function}");- assert!(!schema.description.is_empty());- }-}--#[tokio::test]-async fn composio_controller_handlers_reject_bad_params_before_network() {- crate::tinyhumans_boot::boot();- let registered = all_composio_registered_controllers();-- let missing_authorize = composio_call(composio_controller(®istered, "authorize"), json!({}))- .await- .expect_err("authorize requires toolkit");- assert!(missing_authorize.contains("missing required param 'toolkit'"));-- let blank_delete = composio_call(- composio_controller(®istered, "delete_connection"),- json!({ "connection_id": " " }),- )- .await- .expect_err("delete requires non-empty connection");- assert!(blank_delete.contains("'connection_id' must not be empty"));-- let invalid_list_tools = composio_call(- composio_controller(®istered, "list_tools"),- json!({ "toolkits": "gmail" }),- )- .await- .expect_err("toolkits must be an array");- assert!(invalid_list_tools.contains("invalid 'toolkits'"));-- let missing_execute = composio_call(composio_controller(®istered, "execute"), json!({}))- .await- .expect_err("execute requires tool");- assert!(missing_execute.contains("missing required param 'tool'"));-- let blank_create = composio_call(- composio_controller(®istered, "create_trigger"),- json!({ "slug": " " }),- )- .await- .expect_err("create trigger rejects blank slug");- assert!(blank_create.contains("'slug' must not be empty"));-- let missing_profile = composio_call(- composio_controller(®istered, "get_user_profile"),- json!({}),- )- .await- .expect_err("profile requires connection id");- assert!(missing_profile.contains("missing required param 'connection_id'"));-- let blank_available = composio_call(- composio_controller(®istered, "list_available_triggers"),- json!({ "toolkit": " " }),- )- .await- .expect_err("available triggers rejects blank toolkit");- assert!(blank_available.contains("'toolkit' must not be empty"));-- let missing_enable_connection = composio_call(- composio_controller(®istered, "enable_trigger"),- json!({ "connection_id": " ", "slug": "GMAIL_NEW_GMAIL_MESSAGE" }),- )- .await- .expect_err("enable trigger rejects blank connection");- assert!(missing_enable_connection.contains("'connection_id' must not be empty"));-- let missing_disable = composio_call(- composio_controller(®istered, "disable_trigger"),- json!({}),- )- .await- .expect_err("disable trigger requires id");- assert!(missing_disable.contains("missing required param 'trigger_id'"));-- let bad_set_key = composio_call(- composio_controller(®istered, "set_api_key"),- json!({ "api_key": "" }),- )- .await- .expect_err("set api key requires non-empty key");- assert!(bad_set_key.contains("'api_key' must not be empty"));-- let bad_github_repos = composio_call(- composio_controller(®istered, "list_github_repos"),- json!({ "connection_id": 42 }),- )- .await- .expect_err("github repos connection id must be string");- assert!(bad_github_repos.contains("invalid params"));-- let bad_history_limit = composio_call(- composio_controller(®istered, "list_trigger_history"),- json!({ "limit": "many" }),- )- .await- .expect_err("history limit must be numeric");- assert!(bad_history_limit.contains("invalid params"));-- let bad_list_triggers = composio_call(- composio_controller(®istered, "list_triggers"),- json!({ "toolkit": 12 }),- )- .await- .expect_err("list triggers toolkit must be string");- assert!(bad_list_triggers.contains("invalid params"));-- let missing_enable_slug = composio_call(- composio_controller(®istered, "enable_trigger"),- json!({ "connection_id": "conn-1", "slug": " " }),- )- .await- .expect_err("enable trigger rejects blank slug");- assert!(missing_enable_slug.contains("'slug' must not be empty"));-}--fn composio_controller<'a>(- controllers: &'a [RegisteredController],- function: &str,-) -> &'a RegisteredController {- controllers- .iter()- .find(|controller| controller.schema.function == function)- .unwrap_or_else(|| panic!("controller {function} registered"))-}--async fn composio_call(controller: &RegisteredController, params: Value) -> Result<Value, String> {- let params = params.as_object().cloned().unwrap_or_default();- (controller.handler)(DispatchCtx::process_default(), params).await-}diff --git a/tests/raw_coverage/composio_tools_direct_raw_coverage_e2e.rs b/tests/raw_coverage/composio_tools_direct_raw_coverage_e2e.rsdeleted file mode 100644index 375a3f9dd3..0000000000--- a/tests/raw_coverage/composio_tools_direct_raw_coverage_e2e.rs+++ /dev/null@@ -1,251 +0,0 @@-//! Raw integration coverage for direct Composio tools.-//!-//! This binary stays on loopback mocks and temp stores. It exercises the-//! direct BYO-key tool surface without contacting Composio.--use std::sync::{Arc, Mutex};--use axum::body::to_bytes;-use axum::extract::{Request, State};-use axum::http::{Method, StatusCode};-use axum::response::{IntoResponse, Response};-use axum::routing::any;-use axum::{Json, Router};-use serde_json::{json, Value};--use openhuman_core::config::Config;-use openhuman_core::integrations::composio::client::{direct_list_connections, DirectCredential};--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<RecordedRequest>>>,-}--#[derive(Clone, Debug)]-struct RecordedRequest {- method: String,- path: String,- query: String,- body: Value,- api_key: Option<String>,-}--#[tokio::test]-async fn direct_composio_client_uses_loopback_for_connected_accounts() {- // The read runs in the connector module, which is process-global.- let _module = crate::CONNECTOR_MODULE_LOCK.lock().await;- let dir = tempfile::tempdir().expect("tempdir");- let config = Config {- workspace_dir: dir.path().to_path_buf(),- config_path: dir.path().join("config.toml"),- ..Config::default()- };- let state = MockState::default();- let app = Router::new()- .fallback(any(composio_direct_handler))- .with_state(state.clone());- let base = start_loopback(app).await;- let tool = Arc::new(- DirectCredential::new_with_base_urls_for_loopback(- " ck_round16 ",- format!("{base}/api/v2"),- format!("{base}/api/v3"),- )- .expect("loopback direct client"),- );-- let mapped = direct_list_connections(&config, &tool)- .await- .expect("mapped connected accounts");- assert_eq!(mapped.connections.len(), 4);- assert!(mapped- .connections- .iter()- .any(|conn| conn.id == "acct-github" && conn.toolkit == "github"));- // Slug extraction: padded string, nested object, `appName` fallback, and a- // row with no recognizable slug is kept with an empty toolkit.- let toolkits: Vec<&str> = mapped- .connections- .iter()- .map(|c| c.toolkit.as_str())- .collect();- assert_eq!(toolkits[..2], ["gmail", "github"]);- assert_eq!(toolkits[2], "slack");- assert_eq!(toolkits[3], "");-- let requests = state.requests.lock().expect("requests").clone();- assert!(requests.iter().all(|request| {- request.api_key.as_deref() == Some("ck_round16") || request.path == "/health"- }));- assert!(requests.iter().any(|request| {- request.method == "GET"- && request.path == "/api/v3/connected_accounts"- && request.query.contains("limit=200")- }));-}--async fn composio_direct_handler(State(state): State<MockState>, request: Request) -> Response {- let method = request.method().clone();- let uri = request.uri().clone();- let path = uri.path().to_string();- let query = uri.query().unwrap_or_default().to_string();- let api_key = request- .headers()- .get("x-api-key")- .and_then(|value| value.to_str().ok())- .map(ToString::to_string);- let body_bytes = to_bytes(request.into_body(), usize::MAX)- .await- .expect("mock request body");- let body: Value = if body_bytes.is_empty() {- json!({})- } else {- serde_json::from_slice(&body_bytes).expect("json body")- };- state- .requests- .lock()- .expect("requests")- .push(RecordedRequest {- method: method.as_str().to_string(),- path: path.clone(),- query,- body: body.clone(),- api_key,- });-- match (method, path.as_str()) {- (Method::GET, "/api/v3/tools") => Json(json!({- "items": [- {- "slug": "gmail-fetch-emails",- "name": "Gmail fetch fallback",- "description": "Fetch Gmail",- "toolkit": { "slug": "gmail" },- "input_parameters": {- "type": "object",- "properties": { "query": { "type": "string" } }- }- },- {- "name": "gmail-send-email",- "description": "Send Gmail",- "appName": "gmail",- "parameters": { "type": "object" }- },- {- "description": "dropped because it has no slug or name",- "toolkit": { "slug": "gmail" }- }- ]- }))- .into_response(),- (Method::POST, "/api/v3/tools/execute/GMAIL_FETCH_EMAILS") => Json(json!({- "successful": true,- "data": {- "messages": [{ "id": "msg-direct", "subject": "hello" }]- }- }))- .into_response(),- (Method::POST, "/api/v3/tools/execute/FALLBACK_ACTION") => (- StatusCode::BAD_GATEWAY,- Json(json!({- "error": { "message": "temporary v3 outage" }- })),- )- .into_response(),- (Method::POST, "/api/v2/actions/FALLBACK_ACTION/execute") => Json(json!({- "legacy": true,- "input": body.get("input").cloned().unwrap_or_else(|| json!({}))- }))- .into_response(),- (Method::POST, "/api/v3/tools/execute/BROKEN_ACTION") => (- StatusCode::BAD_REQUEST,- Json(json!({- "error": {- "message": "bad connected_account_id acct-secret for entity_id entity-secret"- }- })),- )- .into_response(),- (Method::POST, "/api/v2/actions/BROKEN_ACTION/execute") => (- StatusCode::BAD_REQUEST,- Json(json!({- "message": "legacy connectedAccountId acct-secret and entityId entity-secret failed"- })),- )- .into_response(),- (Method::GET, "/api/v3/auth_configs") => Json(json!({- "items": [- { "id": "auth-disabled", "enabled": false, "status": "disabled" },- { "id": "auth-enabled", "status": "ENABLED" }- ]- }))- .into_response(),- (Method::POST, "/api/v3/connected_accounts/link") => {- let auth_config = body- .get("auth_config_id")- .and_then(Value::as_str)- .unwrap_or_default();- if auth_config == "auth-explicit" {- Json(json!({ "redirectUrl": "https://connect.example/from-redirect-url" }))- .into_response()- } else {- Json(json!({- "data": {- "redirect_url": "https://connect.example/from-data"- }- }))- .into_response()- }- }- (Method::GET, "/api/v3/connected_accounts") => Json(json!({- "items": [- {- "id": "acct-gmail",- "status": "ACTIVE",- "created_at": "2026-05-29T12:00:00Z",- "toolkit": " gmail "- },- {- "id": "acct-github",- "status": "INITIATED",- "createdAt": "2026-05-29T12:01:00Z",- "toolkit": { "slug": "github" }- },- {- "id": "acct-slack",- "status": "FAILED",- "app_name": "slack"- },- {- "id": "acct-empty-toolkit",- "status": "ACTIVE",- "toolkit": null- },- {- "id": " ",- "status": "ACTIVE",- "toolkit": "not-returned"- }- ]- }))- .into_response(),- _ => (- StatusCode::NOT_FOUND,- Json(json!({ "error": { "message": format!("unhandled {path}") } })),- )- .into_response(),- }-}--async fn start_loopback(app: Router) -> String {- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind mock composio direct server");- let addr = listener.local_addr().expect("mock addr");- tokio::spawn(async move {- let _ = axum::serve(listener, app).await;- });- format!("http://127.0.0.1:{}", addr.port())-}diff --git a/tests/raw_coverage/inference_local_admin_raw_coverage_e2e.rs b/tests/raw_coverage/inference_local_admin_raw_coverage_e2e.rsdeleted file mode 100644index 6fb8289449..0000000000--- a/tests/raw_coverage/inference_local_admin_raw_coverage_e2e.rs+++ /dev/null@@ -1,508 +0,0 @@-//! Round 16 raw/E2E coverage for inference local-admin branches.-//!-//! This suite uses temp workspaces, temp PATH scripts, and loopback HTTP mocks-//! only. It must not call host Ollama, Piper, Whisper, Python, or MLX binaries,-//! and asserts that OpenHuman itself never launches one either.--use crate::env_guard::EnvVarGuard;-use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex, OnceLock};--use axum::body::Body;-use axum::extract::State;-use axum::http::{header, HeaderMap, Response, StatusCode};-use axum::response::IntoResponse;-use axum::routing::{get, post};-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};--use openhuman_core::config::schema::cloud_providers::{- AuthStyle as CloudAuthStyle, CloudProviderCreds,-};-use openhuman_core::config::Config;-use tinyinference_local::service::LocalAiService;-use openhuman_core::inference::provider::factory::auth_key_for_slug;-use openhuman_core::inference::provider::list_configured_models;-use openhuman_core::security::credentials::{AuthService, DEFAULT_AUTH_PROFILE_NAME};--/// One captured mock request: method/path, optional auth header, JSON body.-type RecordedRequest = (String, Option<String>, Value);--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<RecordedRequest>>>,- ollama_models: Arc<Mutex<Vec<String>>>,-}--/// Process-wide lock serializing tests that mutate global environment-/// variables through [`EnvVarGuard`]. `cargo llvm-cov` runs integration tests-/// multi-threaded (it does not pass `--test-threads=1`), so without this guard-/// concurrent tests clobber each other's env — e.g. one test points-/// `OPENHUMAN_OLLAMA_BASE_URL` at an unreachable port and asserts Ollama is-/// unavailable while another points it at a mock and asserts it is available.-/// Each env-mutating test holds this guard for its whole body; declaring it-/// before any `EnvVarGuard` makes it drop last, after the env is restored.-fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {- static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .blocking_lock()-}--async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {- static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock().await-}--#[tokio::test]-async fn local_admin_covers_diagnostics_and_endpoint_probe_without_spawning() {- let _env_guard = env_lock_async().await;- let (base, state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = true;- config.local_ai.opt_in_confirmed = true;- config.local_ai.base_url = Some(base.clone());- config.local_ai.chat_model_id = "gemma3n:e4b-it-q8_0".to_string();- config.local_ai.embedding_model_id = "bge-m3".to_string();- config.local_ai.vision_model_id = "missing-vision".to_string();- config.local_ai.tts_voice_id = "round16-voice".to_string();-- // Every runtime binary on PATH is a stub that leaves a marker if run.- // OpenHuman never launches a local runtime, so none may appear.- let scripts = tempdir().expect("scripts");- let spawn_marker = scripts.path().join("spawned.marker");- let marker_script = format!("#!/bin/sh\ntouch '{}'\nexit 42\n", spawn_marker.display());- write_stub_script(scripts.path(), "ollama", &marker_script);- write_stub_script(scripts.path(), "python", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "python3", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "mlx_lm.generate", "#!/bin/sh\nexit 42\n");- write_stub_script(scripts.path(), "piper", "#!/bin/sh\nexit 42\n");- let _path = EnvVarGuard::set("PATH", scripts.path());- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);- let _ollama_bin = EnvVarGuard::unset("OLLAMA_BIN");- let _piper_bin = EnvVarGuard::unset("PIPER_BIN");- let _whisper_bin = EnvVarGuard::unset("WHISPER_BIN");-- let runtime = openhuman_core::inference::local_runtime_config(&config);- let service = LocalAiService::new(&runtime);-- let diagnostics = service.diagnostics(&runtime).await.expect("diagnostics");- assert_eq!(diagnostics["ollama_running"], true);- assert_eq!(diagnostics["expected"]["chat_found"], false);- assert_eq!(diagnostics["expected"]["embedding_found"], true);- assert_eq!(diagnostics["expected"]["vision_found"], false);- assert_eq!(diagnostics["ok"], false);- assert!(diagnostics["issues"]- .as_array()- .unwrap()- .iter()- .any(|issue| issue.as_str().unwrap().contains("gemma3n:e4b-it-q8_0")));-- // Bootstrap is now a read-only endpoint probe: the mock answers- // `/api/tags`, so the runtime is `ready` even though the chat model is- // missing (the user pulls it themselves).- service.bootstrap(&runtime).await;- let status = service.status();- assert_eq!(status.state, "ready");- assert_eq!(status.chat_model_id, "gemma3n:e4b-it-q8_0");- assert!(- !state- .requests- .lock()- .expect("requests")- .iter()- .any(|(path, _, _)| path.contains("pull")),- "bootstrap must never pull a model"- );- assert!(- !spawn_marker.exists(),- "bootstrap must never launch a runtime binary"- );-}--#[tokio::test]-async fn provider_model_listing_covers_local_synthesis_and_openrouter_failures() {- let _env_guard = env_lock_async().await;- let (base, _state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.base_url = Some(base.clone());- config.cloud_providers = vec![- CloudProviderCreds {- id: "openrouter-id".to_string(),- slug: "openrouter".to_string(),- label: "OpenRouter".to_string(),- endpoint: format!("{base}/openrouter-error"),- auth_style: CloudAuthStyle::Bearer,- default_model: None,- },- CloudProviderCreds {- id: "array-id".to_string(),- slug: "array-body".to_string(),- label: "Array Body".to_string(),- endpoint: format!("{base}/array-body"),- auth_style: CloudAuthStyle::None,- default_model: None,- },- CloudProviderCreds {- id: "status-id".to_string(),- slug: "status-body".to_string(),- label: "Status Body".to_string(),- endpoint: format!("{base}/status-body"),- auth_style: CloudAuthStyle::None,- default_model: None,- },- ];- config.save().await.expect("save config");- AuthService::from_config(&config)- .store_provider_token(- &auth_key_for_slug("openrouter"),- DEFAULT_AUTH_PROFILE_NAME,- "sk-openrouter-secret",- HashMap::new(),- true,- )- .expect("store token");-- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);-- let local = list_configured_models("ollama")- .await- .expect("synthetic ollama")- .value;- assert_eq!(local["models"][0]["id"], "bge-m3");-- let array_err = list_configured_models("array-body")- .await- .expect_err("top-level array");- assert!(array_err.contains("not a JSON object"));-- let status_err = list_configured_models("status-body")- .await- .expect_err("non-success");- assert!(status_err.contains("provider returned 500"));- assert!(!status_err.contains("sk-status-secret"));-- let openrouter_err = list_configured_models("openrouter")- .await- .expect_err("openrouter key validation error payload");- assert!(openrouter_err.contains("OpenRouter key validation returned error payload"));- assert!(!openrouter_err.contains("sk-openrouter-secret"));-}--#[tokio::test]-async fn local_admin_reports_unhealthy_runtime_and_lm_studio_issue_shapes() {- let _env_guard = env_lock_async().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = true;- config.local_ai.opt_in_confirmed = true;- config.local_ai.base_url = Some("http://127.0.0.1:9".to_string());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", "http://127.0.0.1:9");- let runtime = openhuman_core::inference::local_runtime_config(&config);- let service = LocalAiService::new(&runtime);-- let unhealthy = service.diagnostics(&runtime).await.expect("unhealthy diag");- assert_eq!(unhealthy["ollama_running"], false);- assert!(unhealthy["issues"][0]- .as_str()- .unwrap()- .contains("not running or not reachable"));- service.bootstrap(&runtime).await;- assert_eq!(service.status().state, "unreachable");-- let (base, _state) = serve_mock().await;- let mut lm_config = config.clone();- lm_config.local_ai.provider = "lm-studio".to_string();- lm_config.local_ai.base_url = Some(format!("{base}/lm-empty/v1"));- lm_config.local_ai.chat_model_id = "loaded-chat".to_string();- let mut lm_runtime = openhuman_core::inference::local_runtime_config(&lm_config);- let lm_empty = service- .diagnostics(&lm_runtime)- .await- .expect("lm studio empty");- assert_eq!(lm_empty["provider"], "lm_studio");- assert_eq!(lm_empty["lm_studio_running"], true);- assert!(lm_empty["issues"][0]- .as_str()- .unwrap()- .contains("no models are loaded"));-- lm_config.local_ai.base_url = Some(format!("{base}/lm-wrong/v1"));- lm_runtime = openhuman_core::inference::local_runtime_config(&lm_config);- let lm_wrong = service- .diagnostics(&lm_runtime)- .await- .expect("lm studio wrong model");- assert!(lm_wrong["issues"][0]- .as_str()- .unwrap()- .contains("not loaded"));-- lm_config.local_ai.base_url = Some(format!("{base}/lm-error/v1"));- lm_runtime = openhuman_core::inference::local_runtime_config(&lm_config);- let lm_error = service- .diagnostics(&lm_runtime)- .await- .expect("lm studio error payload");- assert!(lm_error["issues"][0]- .as_str()- .unwrap()- .contains("no models are loaded"));-}--async fn serve_mock() -> (String, MockState) {- let state = MockState::default();- *state.ollama_models.lock().expect("models") =- vec!["bge-m3".to_string(), "loaded-chat".to_string()];- let app = Router::new()- .route("/v1/chat/completions", post(chat_completions))- .route("/v1/responses", post(responses))- .route("/v1/models", get(models))- .route("/array-body/models", get(array_body_models))- .route("/status-body/models", get(status_body_models))- .route("/openrouter-error/key", get(openrouter_error_key))- .route("/openrouter-error/models", get(models))- .route("/lm-empty/v1/models", get(empty_lm_models))- .route("/lm-wrong/v1/models", get(wrong_lm_models))- .route("/lm-error/v1/models", get(error_payload_models))- .route("/api/tags", get(ollama_tags))- .route("/api/show", post(ollama_show))- .route("/api/pull", post(ollama_pull_recorded))- .route("/api/generate", post(ollama_generate))- .route("/api/chat", post(ollama_chat))- .with_state(state.clone());- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind mock");- let addr = listener.local_addr().expect("addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve mock");- });- (format!("http://{addr}"), state)-}--async fn chat_completions(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/v1/chat/completions", &headers, body.clone());- let model = body["model"].as_str().unwrap_or_default();- match model {- "merge-model" => Json(json!({- "choices": [{ "message": { "content": "merged response" } }]- }))- .into_response(),- "stream-tools-unsupported" if body.get("tools").is_some() => (- StatusCode::BAD_REQUEST,- Json(json!({"error": {"message": "model does not support tools"}})),- )- .into_response(),- "stream-tools-unsupported" => Response::builder()- .status(StatusCode::OK)- .header(header::CONTENT_TYPE, "application/json")- .body(Body::from(- json!({- "choices": [{ "message": { "content": "json stream fallback" } }]- })- .to_string(),- ))- .expect("json response")- .into_response(),- "not-found-model" | "responses-empty-input" => (- StatusCode::NOT_FOUND,- Json(json!({"error": {"message": "not found sk-should-redact"}})),- )- .into_response(),- "empty-choices" => Json(json!({ "choices": [] })).into_response(),- "auth-model" => Json(json!({- "choices": [{ "message": { "content": "auth response" } }]- }))- .into_response(),- _ => Json(json!({- "choices": [{ "message": { "content": "default response" } }]- }))- .into_response(),- }-}--async fn responses(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/v1/responses", &headers, body.clone());- if body["input"]- .as_str()- .map(str::trim)- .unwrap_or_default()- .is_empty()- {- return Json(json!({ "output": [] })).into_response();- }- Json(json!({- "output": [{- "content": [{ "type": "output_text", "text": "responses fallback" }]- }]- }))- .into_response()-}--async fn models(State(state): State<MockState>) -> impl IntoResponse {- let models = state- .ollama_models- .lock()- .expect("models")- .iter()- .map(|id| json!({ "id": id, "owned_by": "round16", "context_window": 8192 }))- .collect::<Vec<_>>();- Json(json!({ "object": "list", "data": models }))-}--async fn array_body_models() -> impl IntoResponse {- Json(json!([{ "id": "bad" }]))-}--async fn status_body_models() -> impl IntoResponse {- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(json!({"error": "status failed sk-status-secret"})),- )-}--async fn openrouter_error_key() -> impl IntoResponse {- Json(json!({"error": {"message": "bad key sk-openrouter-secret"}}))-}--async fn empty_lm_models() -> impl IntoResponse {- Json(json!({ "object": "list", "data": [] }))-}--async fn wrong_lm_models() -> impl IntoResponse {- Json(json!({- "object": "list",- "data": [{ "id": "some-other-chat", "owned_by": "round16" }]- }))-}--async fn error_payload_models() -> impl IntoResponse {- Json(json!({ "error": { "message": "LM Studio endpoint error" } }))-}--async fn ollama_tags(State(state): State<MockState>) -> impl IntoResponse {- let models = state- .ollama_models- .lock()- .expect("models")- .iter()- .map(|name| json!({ "name": name, "model": name }))- .collect::<Vec<_>>();- Json(json!({ "models": models }))-}--async fn ollama_show(Json(body): Json<Value>) -> impl IntoResponse {- let model = body- .get("model")- .or_else(|| body.get("name"))- .and_then(Value::as_str)- .unwrap_or_default();- if model == "___nonexistent_probe___" {- return (- StatusCode::NOT_FOUND,- Json(json!({"error": "model not found"})),- )- .into_response();- }- let context = match model {- "gemma3n:e4b-it-q8_0" => 1024,- "bge-m3" => 8192,- _ => 4096,- };- Json(json!({- "model_info": {- "general.context_length": context,- "llama.context_length": context- }- }))- .into_response()-}--/// Records any pull attempt so tests can assert none happens: OpenHuman no-/// longer pulls models, the user does.-async fn ollama_pull_recorded(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/api/pull", &headers, body);- StatusCode::GONE-}--async fn ollama_generate() -> impl IntoResponse {- Json(json!({- "response": "generated",- "done": true,- "prompt_eval_count": 1,- "prompt_eval_duration": 1000000,- "eval_count": 1,- "eval_duration": 1000000- }))-}--async fn ollama_chat() -> impl IntoResponse {- Json(json!({- "message": { "role": "assistant", "content": "chat generated" },- "done": true- }))-}--fn remember(state: &MockState, path: &str, headers: &HeaderMap, body: Value) {- state- .requests- .lock()- .expect("requests")- .push((path.to_string(), auth_header(headers), body));-}--fn auth_header(headers: &HeaderMap) -> Option<String> {- headers- .get("authorization")- .or_else(|| headers.get("x-api-key"))- .or_else(|| headers.get("x-custom-auth"))- .and_then(|value| value.to_str().ok())- .map(ToOwned::to_owned)-}--fn temp_config(tmp: &TempDir) -> Config {- let root = tmp.path().join(".openhuman");- std::fs::create_dir_all(root.join("workspace")).expect("workspace dir");- let mut config = Config {- config_path: root.join("config.toml"),- workspace_dir: root.join("workspace"),- ..Default::default()- };- config.secrets.encrypt = false;- config.api_url = Some("http://127.0.0.1:9".to_string());- config-}--fn write_stub_script(dir: &Path, name: &str, body: &str) -> PathBuf {- let path = dir.join(name);- std::fs::write(&path, body).expect("write stub");- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut perms = std::fs::metadata(&path).expect("metadata").permissions();- perms.set_mode(0o755);- std::fs::set_permissions(&path, perms).expect("chmod");- }- path-}diff --git a/tests/raw_coverage/inference_local_controllers_rpc_raw_coverage_e2e.rs b/tests/raw_coverage/inference_local_controllers_rpc_e2e.rssimilarity index 100%rename from tests/raw_coverage/inference_local_controllers_rpc_raw_coverage_e2e.rsrename to tests/raw_coverage/inference_local_controllers_rpc_e2e.rsdiff --git a/tests/raw_coverage/inference_provider_admin_round22_raw_coverage_e2e.rs b/tests/raw_coverage/inference_provider_admin_round22_raw_coverage_e2e.rsdeleted file mode 100644index e152fce455..0000000000--- a/tests/raw_coverage/inference_provider_admin_round22_raw_coverage_e2e.rs+++ /dev/null@@ -1,512 +0,0 @@-//! Round 22 raw/E2E-style coverage for inference provider/admin branches.-//!-//! All external inference/admin surfaces are mocked with loopback HTTP servers-//! and temp PATH binaries. This suite must not invoke real Ollama, MLX, Python,-//! whisper, piper, local AI binaries, models, or downloads.--use crate::env_guard::EnvVarGuard;-use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex, OnceLock};--use axum::extract::State;-use axum::http::{header, HeaderMap, StatusCode};-use axum::response::IntoResponse;-use axum::routing::{get, post};-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};-use tinyinference_llm::message::Message;-use tinyinference_llm::model::ModelRequest;--use openhuman_core::config::schema::cloud_providers::{- AuthStyle as CloudAuthStyle, CloudProviderCreds,-};-use openhuman_core::config::Config;-use tinyinference_local::service::LocalAiService;-use openhuman_core::inference::provider::factory::{- auth_key_for_slug, create_chat_model_from_string_with_model_id,-};-use openhuman_core::inference::provider::list_configured_models;-use openhuman_core::security::credentials::{- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,-};--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<SeenRequest>>>,-}--#[derive(Debug, Clone)]-struct SeenRequest {- path: String,- auth: Option<String>,- user_agent: Option<String>,- body: Value,-}--/// Serializes the whole suite's process-global env access.-///-/// Several tests mutate `OPENHUMAN_WORKSPACE` / `OPENHUMAN_OLLAMA_BASE_URL` /-/// `PATH` via [`EnvVarGuard`]. `cargo test` (and `cargo llvm-cov`) run a-/// binary's tests on multiple threads by default, so without this lock those-/// mutations race and a test reads another test's workspace/config — observed-/// as a flaky failure under `cargo llvm-cov` (the coverage job does not pass-/// `--test-threads=1`). Every test takes this guard up front so the suite is-/// effectively serialized regardless of the runner's thread count.-static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;--fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .blocking_lock()-}--async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock().await-}--#[tokio::test]-async fn provider_admin_model_listing_covers_openrouter_validation_and_local_synthesis() {- let _env = env_lock_async().await;- let (base, state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.base_url = Some(base.clone());- config.cloud_providers = vec![- provider_entry(- "openrouter-id",- "openrouter",- &format!("{base}/openrouter/api/v1"),- CloudAuthStyle::Bearer,- None,- ),- provider_entry(- "object-error-id",- "object-error",- &format!("{base}/object-error"),- CloudAuthStyle::None,- None,- ),- ];- config.save().await.expect("save config");- let auth = AuthService::from_config(&config);- auth.store_provider_token(- &auth_key_for_slug("openrouter"),- DEFAULT_AUTH_PROFILE_NAME,- "sk-openrouter",- HashMap::new(),- true,- )- .expect("store openrouter key");- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);-- let openrouter = list_configured_models("openrouter")- .await- .expect("openrouter models")- .value;- assert_eq!(openrouter["models"][0]["id"], "or-model");-- let object_error = list_configured_models("object-error")- .await- .expect_err("object error payload");- assert!(object_error.contains("nested provider failure"));-- let synthetic_ollama = list_configured_models("ollama")- .await- .expect("synthetic ollama /v1 models")- .value;- assert_eq!(synthetic_ollama["models"][0]["id"], "ollama-synth");-- config.cloud_providers = vec![provider_entry(- "openrouter-id",- "openrouter",- &format!("{base}/openrouter-bad/api/v1"),- CloudAuthStyle::Bearer,- None,- )];- config.save().await.expect("save bad openrouter config");- auth.store_provider_token(- &auth_key_for_slug("openrouter"),- DEFAULT_AUTH_PROFILE_NAME,- "sk-openrouter-bad",- HashMap::new(),- true,- )- .expect("store bad openrouter key");- let bad_key = list_configured_models("openrouter")- .await- .expect_err("openrouter key validation body");- assert!(bad_key.contains("OpenRouter key validation returned error payload"));- assert!(!bad_key.contains("sk-openrouter-bad"));-- let seen = state.requests.lock().expect("requests");- assert!(seen.iter().any(|req| req.path == "/openrouter/api/v1/key"- && req.auth.as_deref() == Some("Bearer sk-openrouter")));- assert!(seen- .iter()- .any(|req| req.path == "/v1/models" && req.auth.is_none()));-}--#[tokio::test]-async fn factory_covers_legacy_api_key_scoping_and_abstract_model_errors() {- let _env = env_lock_async().await;- let (base, state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.api_key = Some("sk-legacy-direct".to_string());- config.inference_url = Some(format!("{base}/legacy/v1"));- config.cloud_providers = vec![- provider_entry(- "legacy-id",- "legacy",- &format!("{base}/legacy/v1/"),- CloudAuthStyle::Bearer,- Some("legacy-default"),- ),- provider_entry(- "other-id",- "other",- &format!("{base}/other/v1"),- CloudAuthStyle::Bearer,- Some("other-default"),- ),- provider_entry(- "abstract-id",- "abstract",- &format!("{base}/abstract/v1"),- CloudAuthStyle::Bearer,- None,- ),- ];- let auth = AuthService::from_config(&config);- auth.store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "session-token",- HashMap::new(),- true,- )- .expect("store app session");- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());-- let (legacy, legacy_model) =- create_chat_model_from_string_with_model_id("chat", "legacy:requested-model", &config, 0.4)- .expect("legacy direct model");- assert_eq!(legacy_model, "requested-model");- let legacy_response = legacy- .invoke(- &(),- ModelRequest::new(vec![Message::user("hello")]).with_model(&legacy_model),- )- .await- .expect("legacy chat");- assert_eq!(legacy_response.text(), "legacy direct ok");-- let (other, other_model) =- create_chat_model_from_string_with_model_id("chat", "other:other-model", &config, 0.4)- .expect("other model");- let other_text = other- .invoke(- &(),- ModelRequest::new(vec![Message::user("hello")]).with_model(&other_model),- )- .await- .expect("other model dispatches without inheriting the legacy key");- assert_eq!(other_text.text(), "other no key ok");-- let abstract_err = match create_chat_model_from_string_with_model_id(- "reasoning",- "abstract:reasoning-v1",- &config,- 0.4,- ) {- Ok(_) => panic!("expected abstract tier error"),- Err(err) => err,- };- assert!(abstract_err- .to_string()- .contains("has no concrete default_model configured"));-- let seen = state.requests.lock().expect("requests");- assert!(seen- .iter()- .any(|req| req.path == "/legacy/v1/chat/completions"- && req.auth.as_deref() == Some("Bearer sk-legacy-direct")));- assert!(seen- .iter()- .any(|req| req.path == "/other/v1/chat/completions"- && !req- .auth- .as_deref()- .is_some_and(|auth| auth.contains("sk-legacy-direct"))));-}--#[tokio::test]-async fn local_admin_covers_diagnostics_errors_and_probe_with_fake_bins() {- let _env = env_lock_async().await;- let (base, _state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = true;- config.local_ai.opt_in_confirmed = true;- config.local_ai.base_url = Some(base.clone());- config.local_ai.chat_model_id = "gemma3n:e4b-it-q8_0".to_string();- config.local_ai.embedding_model_id = "all-minilm:latest".to_string();- config.local_ai.stt_model_id = "round22-stt".to_string();- config.local_ai.tts_voice_id = "round22-voice".to_string();-- let scripts = tempdir().expect("scripts");- let ollama = write_stub_script(&scripts, "ollama", "#!/bin/sh\nprintf 'fake ollama\\n'\n");- write_stub_script(&scripts, "python", "#!/bin/sh\nexit 42\n");- write_stub_script(&scripts, "python3", "#!/bin/sh\nexit 42\n");- write_stub_script(&scripts, "mlx_lm.generate", "#!/bin/sh\nexit 42\n");- write_stub_script(&scripts, "piper", "#!/bin/sh\nexit 42\n");-- let _path = EnvVarGuard::set("PATH", scripts.path());- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);- let _ollama_bin = EnvVarGuard::set("OLLAMA_BIN", &ollama);- let _piper_bin = EnvVarGuard::unset("PIPER_BIN");- let _whisper_bin = EnvVarGuard::unset("WHISPER_BIN");-- let runtime = openhuman_core::inference::local_runtime_config(&config);- let service = LocalAiService::new(&runtime);- let diag = service.diagnostics(&runtime).await.expect("diagnostics");- assert_eq!(diag["ollama_running"], true);- let issues = diag["issues"].as_array().expect("issues");- assert!(issues.iter().any(|issue| issue- .as_str()- .unwrap()- .contains("Chat model `gemma3n:e4b-it-q8_0`")));- assert!(issues.iter().any(|issue| issue- .as_str()- .unwrap()- .contains("Embedding model `all-minilm:latest`")));-- let mut tags_500 = config.clone();- tags_500.local_ai.base_url = Some(format!("{base}/tags-500"));- let tags_500_runtime = openhuman_core::inference::local_runtime_config(&tags_500);- let diag_500 = service- .diagnostics(&tags_500_runtime)- .await- .expect("500 diagnostics");- assert_eq!(diag_500["ollama_running"], false);- assert!(diag_500["issues"][0]- .as_str()- .unwrap()- .contains("not running or not reachable"));-- // Missing models are reported, never pulled: bootstrap stays a read-only- // probe of the reachable endpoint.- service.bootstrap(&runtime).await;- assert_eq!(service.status().state, "ready");- service.bootstrap(&tags_500_runtime).await;- assert_eq!(- service.status().state,- "ready",- "a ready status is kept until reset_to_idle"- );-}--async fn serve_mock() -> (String, MockState) {- let state = MockState::default();- let app = Router::new()- .route("/fallback/v1/chat/completions", post(always_404))- .route("/fallback/v1/responses", post(responses_fallback))- .route("/merge/v1/chat/completions", post(merge_chat))- .route("/custom-auth/v1/chat/completions", post(custom_auth_chat))- .route("/openrouter/api/v1/key", get(openrouter_key_ok))- .route("/openrouter/api/v1/models", get(openrouter_models))- .route("/openrouter-bad/api/v1/key", get(openrouter_key_bad))- .route("/object-error/models", get(object_error_models))- .route("/v1/models", get(synthetic_ollama_models))- .route("/legacy/v1/chat/completions", post(legacy_chat))- .route("/other/v1/chat/completions", post(other_chat))- .route("/api/tags", get(ollama_tags))- .route("/api/show", post(ollama_show))- .route("/tags-500/api/tags", get(tags_500))- .with_state(state.clone());- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind mock");- let addr = listener.local_addr().expect("addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve mock");- });- (format!("http://{addr}"), state)-}--async fn always_404(State(state): State<MockState>, headers: HeaderMap) -> impl IntoResponse {- remember(- &state,- "/fallback/v1/chat/completions",- &headers,- Value::Null,- );- (StatusCode::NOT_FOUND, "missing chat endpoint").into_response()-}--async fn responses_fallback(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/fallback/v1/responses", &headers, body);- Json(json!({"output_text": "round22 responses text"})).into_response()-}--async fn merge_chat(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/merge/v1/chat/completions", &headers, body);- Json(json!({"choices":[{"message":{"content":"merged ok"}}]})).into_response()-}--async fn custom_auth_chat(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/custom-auth/v1/chat/completions", &headers, body);- Json(json!({"choices":[{"message":{"content":"custom auth ok"}}]})).into_response()-}--async fn openrouter_key_ok(- State(state): State<MockState>,- headers: HeaderMap,-) -> impl IntoResponse {- remember(&state, "/openrouter/api/v1/key", &headers, Value::Null);- Json(json!({"data": {"label": "ok"}})).into_response()-}--async fn openrouter_models() -> impl IntoResponse {- Json(json!({"object":"list","data":[{"id":"or-model","owned_by":"openrouter"}]}))-}--async fn openrouter_key_bad(- State(state): State<MockState>,- headers: HeaderMap,-) -> impl IntoResponse {- remember(&state, "/openrouter-bad/api/v1/key", &headers, Value::Null);- Json(json!({"error": {"message": "bad key sk-openrouter-bad"}})).into_response()-}--async fn object_error_models() -> impl IntoResponse {- Json(json!({"error": {"message": "nested provider failure"}}))-}--async fn synthetic_ollama_models(- State(state): State<MockState>,- headers: HeaderMap,-) -> impl IntoResponse {- remember(&state, "/v1/models", &headers, Value::Null);- Json(json!({"object":"list","data":[{"id":"ollama-synth","context_length":4096}]}))-}--async fn legacy_chat(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/legacy/v1/chat/completions", &headers, body);- Json(json!({"choices":[{"message":{"content":"legacy direct ok"}}]})).into_response()-}--async fn other_chat(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/other/v1/chat/completions", &headers, body);- Json(json!({"choices":[{"message":{"content":"other no key ok"}}]})).into_response()-}--async fn ollama_tags() -> impl IntoResponse {- Json(json!({- "models": [- {"name": "round22-existing", "model": "round22-existing", "size": 1}- ]- }))-}--async fn ollama_show() -> impl IntoResponse {- Json(json!({"model_info": {"general.context_length": 8192}}))-}--async fn tags_500() -> impl IntoResponse {- (StatusCode::INTERNAL_SERVER_ERROR, "tags failed").into_response()-}--fn remember(state: &MockState, path: &str, headers: &HeaderMap, body: Value) {- state.requests.lock().expect("requests").push(SeenRequest {- path: path.to_string(),- auth: auth_header(headers),- user_agent: headers- .get(header::USER_AGENT)- .and_then(|value| value.to_str().ok())- .map(ToOwned::to_owned),- body,- });-}--fn auth_header(headers: &HeaderMap) -> Option<String> {- headers- .get(header::AUTHORIZATION)- .or_else(|| headers.get("x-api-key"))- .or_else(|| headers.get("x-custom-auth"))- .and_then(|value| value.to_str().ok())- .map(ToOwned::to_owned)-}--fn provider_entry(- id: &str,- slug: &str,- endpoint: &str,- auth_style: CloudAuthStyle,- default_model: Option<&str>,-) -> CloudProviderCreds {- CloudProviderCreds {- id: id.to_string(),- slug: slug.to_string(),- label: slug.to_string(),- endpoint: endpoint.to_string(),- auth_style,- default_model: default_model.map(ToString::to_string),- }-}--fn temp_config(tmp: &TempDir) -> Config {- let root = tmp.path().join(".openhuman");- std::fs::create_dir_all(root.join("workspace")).expect("workspace dir");- let mut config = Config {- config_path: root.join("config.toml"),- workspace_dir: root.join("workspace"),- ..Default::default()- };- config.secrets.encrypt = false;- config.api_url = Some("http://127.0.0.1:9".to_string());- config-}--fn write_stub_script(tmp: &TempDir, name: &str, body: &str) -> PathBuf {- let path = tmp.path().join(name);- std::fs::write(&path, body).expect("write stub");- make_executable(&path);- path-}--fn make_executable(path: &Path) {- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut perms = std::fs::metadata(path).expect("metadata").permissions();- perms.set_mode(0o755);- std::fs::set_permissions(path, perms).expect("chmod");- }-}diff --git a/tests/raw_coverage/inference_provider_raw_coverage_e2e.rs b/tests/raw_coverage/inference_provider_raw_coverage_e2e.rsdeleted file mode 100644index 9b3969e337..0000000000--- a/tests/raw_coverage/inference_provider_raw_coverage_e2e.rs+++ /dev/null@@ -1,540 +0,0 @@-//! Round 15 raw/E2E coverage for inference provider and local runtime paths.-//!-//! These tests use only loopback HTTP mocks and temp workspaces. They do not-//! require real Ollama, LM Studio, Piper, Whisper, Python, or model binaries.--use crate::env_guard::EnvVarGuard;-use std::collections::HashMap;-use std::sync::{Arc, Mutex};--use axum::body::Body;-use axum::extract::State;-use axum::http::{header, HeaderMap, Response, StatusCode};-use axum::response::IntoResponse;-use axum::routing::{get, post};-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};--use openhuman_core::config::schema::cloud_providers::{- AuthStyle as CloudAuthStyle, CloudProviderCreds,-};-use openhuman_core::config::Config;-use tinyinference_local::service::LocalAiService;-use openhuman_core::inference::provider::factory::{- auth_key_for_slug, create_chat_model_from_string_with_model_id, provider_for_role,-};-use openhuman_core::inference::provider::list_configured_models;-use openhuman_core::security::credentials::{- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,-};--/// One captured mock request: method/path, optional auth header, JSON body.-type RecordedRequest = (String, Option<String>, Value);--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<RecordedRequest>>>,-}--// Serialize env mutation against every other aggregated suite via the-// single crate-wide SHARED_ENV_LOCK (these tests use an `EnvVarGuard` struct-// that does not itself hold a lock). Poison is recovered so a panic-// elsewhere cannot wedge the suite.-fn __shared_env_lock() -> tokio::sync::MutexGuard<'static, ()> {- crate::SHARED_ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .blocking_lock()-}--async fn __shared_env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {- crate::SHARED_ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock().await-}--#[tokio::test]-async fn provider_factory_and_model_listing_cover_cloud_local_and_invalid_shapes() {- let _env_lock = __shared_env_lock_async().await;- let (base, _state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- let _workspace_env = EnvVarGuard::set(- "OPENHUMAN_WORKSPACE",- config.config_path.parent().expect("config parent"),- );- seed_session(&config);- config.cloud_providers = vec![- CloudProviderCreds {- id: "custom-id".to_string(),- slug: "custom".to_string(),- label: "Custom".to_string(),- endpoint: format!("{base}/v1"),- auth_style: CloudAuthStyle::Bearer,- default_model: Some("demo-chat".to_string()),- },- CloudProviderCreds {- id: "openrouter-id".to_string(),- slug: "openrouter".to_string(),- label: "OpenRouter".to_string(),- endpoint: format!("{base}/openrouter"),- auth_style: CloudAuthStyle::Bearer,- default_model: None,- },- CloudProviderCreds {- id: "missing-id".to_string(),- slug: "missing".to_string(),- label: "Missing".to_string(),- endpoint: format!("{base}/missing"),- auth_style: CloudAuthStyle::None,- default_model: None,- },- CloudProviderCreds {- id: "html-id".to_string(),- slug: "html".to_string(),- label: "HTML".to_string(),- endpoint: format!("{base}/html"),- auth_style: CloudAuthStyle::None,- default_model: None,- },- CloudProviderCreds {- id: "wrong-data-id".to_string(),- slug: "wrong-data".to_string(),- label: "Wrong Data".to_string(),- endpoint: format!("{base}/wrong-data"),- auth_style: CloudAuthStyle::None,- default_model: None,- },- CloudProviderCreds {- id: "error-payload-id".to_string(),- slug: "error-payload".to_string(),- label: "Error Payload".to_string(),- endpoint: format!("{base}/error-payload"),- auth_style: CloudAuthStyle::None,- default_model: None,- },- ];- config.chat_provider = Some("custom:[email protected]".to_string());- config.reasoning_provider = None;- config.local_ai.base_url = Some(base.clone());-- AuthService::from_config(&config)- .store_provider_token(- &auth_key_for_slug("custom"),- DEFAULT_AUTH_PROFILE_NAME,- "custom-key",- HashMap::new(),- true,- )- .expect("store custom key");- AuthService::from_config(&config)- .store_provider_token(- &auth_key_for_slug("openrouter"),- DEFAULT_AUTH_PROFILE_NAME,- "openrouter-key",- HashMap::new(),- true,- )- .expect("store openrouter key");- config.save().await.expect("save temp config");-- assert_eq!(provider_for_role("chat", &config), "custom:[email protected]");- // #6109: an unset route no longer borrows a sibling's BYOK provider; with no- // `primary_cloud` configured it falls through to the managed backend.- assert_eq!(provider_for_role("reasoning", &config), "openhuman");-- let (_provider, model) =- create_chat_model_from_string_with_model_id("chat", "custom:[email protected]", &config, 0.7)- .expect("cloud model");- assert_eq!(model, "demo-chat");-- let (_local_provider, local_model) = create_chat_model_from_string_with_model_id(- "chat",- "ollama:gemma3:[email protected]",- &config,- 0.7,- )- .expect("ollama model");- assert_eq!(local_model, "gemma3:1b-it-qat");-- let empty_model =- match create_chat_model_from_string_with_model_id("chat", "ollama:", &config, 0.7) {- Ok(_) => panic!("expected empty model error"),- Err(err) => err,- };- assert!(empty_model.to_string().contains("empty model"));-- let listed = list_configured_models("custom")- .await- .expect("list models")- .value;- assert_eq!(listed["models"][0]["id"], "demo-chat");- assert_eq!(listed["models"][1]["context_window"], 8192);-- let local_listed = list_configured_models("ollama")- .await- .expect("synthetic ollama list")- .value;- assert_eq!(local_listed["models"][0]["id"], "demo-chat");-- // PR #2959 reverted the list_models 404 suppression: a 404 from /models- // now surfaces as a real error instead of a synthetic `unsupported: true`- // success, so the failure fires to Sentry for a root-cause fix.- let missing_err = list_configured_models("missing")- .await- .expect_err("404 list_models now surfaces as an error");- assert!(- missing_err.contains("provider returned 404"),- "404 list_models error should surface the status: {missing_err:?}"- );-- let openrouter = list_configured_models("openrouter")- .await- .expect("openrouter key validation and list")- .value;- assert_eq!(openrouter["models"][0]["owned_by"], "test-suite");-- for provider_id in ["html", "wrong-data", "error-payload", ""] {- let err = list_configured_models(provider_id)- .await- .expect_err("invalid model listing");- assert!(- err.contains("provider")- || err.contains("provider_id")- || err.contains("OpenRouter")- || err.contains("parse JSON")- );- }-}--#[tokio::test]-async fn local_service_public_inference_and_diagnostics_use_loopback_ollama() {- let _env_lock = __shared_env_lock_async().await;- let (base, _state) = serve_mock().await;- let _ollama_env = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = true;- config.local_ai.base_url = Some(base);- config.local_ai.chat_model_id = "gemma3:1b-it-qat".to_string();- config.local_ai.vision_model_id = "llava:mock".to_string();- config.local_ai.embedding_model_id = "bge-m3".to_string();-- let runtime = openhuman_core::inference::local_runtime_config(&config);- let service = LocalAiService::new(&runtime);- let prompt = service- .prompt(&runtime, "Say hi", Some(8), true)- .await- .expect("prompt");- assert_eq!(prompt, "chat:gemma3:1b-it-qat");-- let summarized = service- .summarize(&runtime, "one two three", Some(16))- .await- .expect("summarize");- assert_eq!(summarized, "chat:gemma3:1b-it-qat");-- let completion = service- .inline_complete_interactive(- &runtime,- "OpenHuman is",- "concise",- Some("short"),- &["OpenHuman is useful".to_string()],- Some(6),- )- .await- .expect("inline");- assert_eq!(completion, "chat:gemma3:1b-it-qat");-- let diagnostics = service.diagnostics(&runtime).await.expect("diagnostics");- assert_eq!(diagnostics["ollama_running"], true);- assert_eq!(diagnostics["expected"]["chat_found"], true);- assert!(- diagnostics["installed_models"]- .as_array()- .expect("installed_models")- .len()- >= 4- );-- let disabled_config = Config::default();- let disabled_runtime = openhuman_core::inference::local_runtime_config(&disabled_config);- let disabled_err = service- .prompt(&disabled_runtime, "disabled", None, false)- .await- .expect_err("disabled prompt");- assert_eq!(disabled_err, "local ai is disabled");-}--fn temp_config(tmp: &TempDir) -> Config {- let root = tmp.path().join(".openhuman");- std::fs::create_dir_all(root.join("workspace")).expect("workspace dir");- let mut config = Config {- config_path: root.join("config.toml"),- workspace_dir: root.join("workspace"),- ..Default::default()- };- config.secrets.encrypt = false;- config.api_url = Some("http://127.0.0.1:9".to_string());- config-}--fn seed_session(config: &Config) {- AuthService::from_config(config)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "session-token",- HashMap::new(),- true,- )- .expect("seed session");-}--async fn serve_mock() -> (String, MockState) {- let state = MockState::default();- let app = Router::new()- .route("/v1/chat/completions", post(chat_completions))- .route("/v1/responses", post(responses))- .route("/v1/models", get(models))- .route("/missing/models", get(missing_models))- .route("/html/models", get(html_models))- .route("/wrong-data/models", get(wrong_data_models))- .route("/error-payload/models", get(error_payload_models))- .route("/openrouter/key", get(openrouter_key))- .route("/openrouter/models", get(models))- .route("/api/tags", get(ollama_tags))- .route("/api/show", post(ollama_show))- .route("/api/generate", post(ollama_generate))- .with_state(state.clone());- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind mock");- let addr = listener.local_addr().expect("addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve mock");- });- (format!("http://{addr}"), state)-}--async fn chat_completions(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/v1/chat/completions", &headers, body.clone());- let model = body["model"].as_str().unwrap_or_default();- if model == "responses-only" {- return (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response();- }- if model == "budget-model" {- return (- StatusCode::BAD_REQUEST,- Json(json!({"error": {"message": "budget exhausted for sk-very-secret"}})),- )- .into_response();- }- if model == "stream-model" && body["stream"] == true {- return sse_response();- }- if model == "tool-model" {- return Json(json!({- "choices": [{- "message": {- "content": "tool response",- "reasoning_content": "hidden reasoning",- "tool_calls": [{- "id": "call_1",- "type": "function",- "function": {- "name": "lookup",- "arguments": { "query": "openhuman" }- }- }]- }- }],- "usage": {- "prompt_tokens": 1,- "completion_tokens": 2,- "prompt_tokens_details": { "cached_tokens": 1 }- },- "openhuman": {- "usage": {- "input_tokens": 11,- "output_tokens": 7,- "cached_input_tokens": 3- },- "billing": { "charged_amount_usd": 0.0042 }- }- }))- .into_response();- }- Json(json!({- "choices": [{- "message": {- "content": format!("chat:{model}"),- "function_call": {- "name": "legacy_tool",- "arguments": "{\"ok\":true}"- }- }- }]- }))- .into_response()-}--async fn responses(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> impl IntoResponse {- remember(&state, "/v1/responses", &headers, body);- Json(json!({- "output": [{- "content": [{ "type": "output_text", "text": "nested fallback text" }]- }],- "output_text": "responses fallback text"- }))-}--fn sse_response() -> Response<Body> {- let chunks = [- json!({"choices":[{"delta":{"content":"hello "}}]}).to_string(),- json!({"choices":[{"delta":{"reasoning_content":"thinking"}}]}).to_string(),- json!({"choices":[{"delta":{"content":"world","tool_calls":[{- "index":0,- "id":"call_stream",- "type":"function",- "function":{"name":"lookup","arguments":"{\"query\""}- }]}}]})- .to_string(),- json!({"choices":[{"delta":{"tool_calls":[{- "index":0,- "function":{"arguments":":\"stream\"}"}- }]}}]})- .to_string(),- json!({- "choices": [],- "usage": {- "prompt_tokens": 5,- "completion_tokens": 6,- "prompt_tokens_details": { "cached_tokens": 2 }- }- })- .to_string(),- ];- let body = chunks- .into_iter()- .map(|chunk| format!("data: {chunk}\n\n"))- .chain(std::iter::once("data: [DONE]\n\n".to_string()))- .collect::<String>();- Response::builder()- .status(StatusCode::OK)- .header(header::CONTENT_TYPE, "text/event-stream")- .body(Body::from(body))- .expect("sse response")-}--async fn models(State(state): State<MockState>, headers: HeaderMap) -> impl IntoResponse {- remember(&state, "/v1/models", &headers, Value::Null);- Json(json!({- "object": "list",- "data": [- { "id": "demo-chat", "owned_by": "test-suite" },- { "id": "demo-coder", "owned_by": "test-suite", "context_window": 8192 },- { "owned_by": "ignored-without-id" }- ]- }))-}--async fn missing_models() -> impl IntoResponse {- (- StatusCode::NOT_FOUND,- Json(json!({"error": "models unsupported"})),- )-}--async fn html_models() -> impl IntoResponse {- (StatusCode::OK, "<html>login</html>")-}--async fn wrong_data_models() -> impl IntoResponse {- Json(json!({ "object": "error", "data": { "message": "wrong shape" } }))-}--async fn error_payload_models() -> impl IntoResponse {- Json(json!({ "error": { "message": "bad sk-secret-key" } }))-}--async fn openrouter_key(headers: HeaderMap) -> impl IntoResponse {- let auth = header_value(&headers, "authorization").unwrap_or_default();- if auth == "Bearer openrouter-key" {- Json(json!({"data": {"label": "ok"}})).into_response()- } else {- (- StatusCode::UNAUTHORIZED,- Json(json!({"error": "missing key"})),- )- .into_response()- }-}--async fn ollama_tags() -> impl IntoResponse {- Json(json!({- "models": [- { "name": "gemma3:1b-it-qat", "model": "gemma3:1b-it-qat" },- { "name": "llava:mock", "model": "llava:mock" },- { "name": "bge-m3", "model": "bge-m3" },- { "name": "demo-chat", "model": "demo-chat" }- ]- }))-}--async fn ollama_show(Json(body): Json<Value>) -> impl IntoResponse {- let model = body- .get("model")- .or_else(|| body.get("name"))- .and_then(Value::as_str)- .unwrap_or_default();- if model == "___nonexistent_probe___" {- return (- StatusCode::NOT_FOUND,- Json(json!({"error": "model not found"})),- )- .into_response();- }- Json(json!({- "model_info": {- "general.context_length": if model == "bge-m3" { 8192 } else { 4096 }- }- }))- .into_response()-}--async fn ollama_generate(Json(_body): Json<Value>) -> impl IntoResponse {- Json(json!({- "model": "gemma3:1b-it-qat",- "response": "generated final",- "done": true,- "prompt_eval_count": 8,- "prompt_eval_duration": 400000000,- "eval_count": 6,- "eval_duration": 300000000- }))-}--fn remember(state: &MockState, path: &str, headers: &HeaderMap, body: Value) {- state.requests.lock().expect("requests").push((- path.to_string(),- header_value(headers, "authorization"),- body,- ));-}--fn header_value(headers: &HeaderMap, key: &str) -> Option<String> {- headers- .get(key)- .and_then(|value| value.to_str().ok())- .map(ToOwned::to_owned)-}diff --git a/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs b/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rsdeleted file mode 100644index 69e191869e..0000000000--- a/tests/raw_coverage/inference_voice_http_round23_raw_coverage_e2e.rs+++ /dev/null@@ -1,432 +0,0 @@-//! Round 23 raw/E2E coverage for inference voice/http/local-service gaps.-//!-//! This suite uses temp workspaces, fake binaries, and loopback HTTP/WS servers-//! only. It must not call host Ollama, MLX, Python, Whisper, Piper, models, or-//! download endpoints, and OpenHuman itself must not launch any of them.--use crate::env_guard::EnvVarGuard;-use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::sync::{Arc, Mutex, OnceLock};--use axum::body::Body;-use axum::extract::ws::WebSocketUpgrade;-use axum::extract::State;-use axum::http::{header, HeaderMap, Response, StatusCode};-use axum::response::IntoResponse;-use axum::routing::{get, post};-use axum::{Json, Router};-use futures_util::{SinkExt, StreamExt};-use openhuman_core::config::schema::cloud_providers::{- AuthStyle as CloudAuthStyle, CloudProviderCreds,-};-use openhuman_core::config::Config;-use openhuman_core::core::types::AppState;-use openhuman_core::inference::host_runtime::local_ai_status;-use tinyinference_local::service::LocalAiService;-use openhuman_core::inference::http;-use openhuman_core::security::credentials::{- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,-};-use openhuman_core::voice::streaming::handle_dictation_ws;-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};-use tokio_tungstenite::tungstenite::Message as WsMessage;--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<(String, Value)>>>,-}--/// Serializes the whole suite's process-global env access.-///-/// `cargo test` and `cargo llvm-cov` run a binary's tests on multiple threads-/// by default. These tests mutate `OPENHUMAN_WORKSPACE`, `OPENHUMAN_OLLAMA_BASE_URL`,-/// and binary path env vars, so every test takes this guard before reading or-/// writing config that may be influenced by process env.-static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;--fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .blocking_lock()-}--async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock().await-}--#[tokio::test]-async fn http_models_and_chat_use_mocked_ollama_without_real_runtime() {- let _env = env_lock_async().await;- let (base, state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.default_model = Some("[email protected]".to_string());- config.chat_provider = Some("ollama:[email protected]".to_string());- config.reasoning_provider = Some("round23:[email protected]".to_string());- config.local_ai.provider = "ollama".to_string();- config.local_ai.base_url = Some(base.clone());- config.local_ai.chat_model_id = "configured-chat".to_string();- config.cloud_providers = vec![CloudProviderCreds {- id: "round23-id".to_string(),- slug: "round23".to_string(),- label: "Round 23".to_string(),- endpoint: format!("{base}/cloud"),- auth_style: CloudAuthStyle::None,- default_model: Some("[email protected]".to_string()),- }];- config.save().await.expect("save config");-- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);- store_app_session(&config);-- let app = http::router().with_state(AppState {- core_version: "round23-test".to_string(),- });- let url = serve_app(app).await;- let client = reqwest::Client::new();-- let models: Value = client- .get(format!("{url}/models"))- .send()- .await- .expect("models response")- .json()- .await- .expect("models json");- let ids = models["data"]- .as_array()- .expect("models array")- .iter()- .map(|item| item["id"].as_str().unwrap_or_default().to_string())- .collect::<Vec<_>>();- assert!(ids.contains(&"openhuman".to_string()));- assert!(ids.contains(&"reasoning-v1".to_string()));- assert!(ids.contains(&"ollama:configured-chat".to_string()));- assert!(ids.contains(&"ollama:route-chat".to_string()));- assert!(ids.contains(&"round23:cloud-chat".to_string()));- assert!(!ids.iter().any(|id| id.contains('@')));-- let chat: Value = client- .post(format!("{url}/chat/completions"))- .json(&json!({- "model": "bare-chat",- "messages": [{ "role": "user", "content": "hello http" }],- "temperature": 0.2- }))- .send()- .await- .expect("chat response")- .json()- .await- .expect("chat json");- assert_eq!(- chat["choices"][0]["message"]["content"],- "round23 chat bare-chat"- );- assert_eq!(chat["model"], "bare-chat");-- let stream_text = client- .post(format!("{url}/chat/completions"))- .json(&json!({- "model": "ollama:stream-chat",- "stream": true,- "messages": [{ "role": "user", "content": "stream please" }]- }))- .send()- .await- .expect("stream response")- .text()- .await- .expect("stream text");- assert!(- stream_text.contains("round23 stream"),- "stream_text={stream_text}"- );- assert!(stream_text.contains("[DONE]"));-- let bad: Value = client- .post(format!("{url}/chat/completions"))- .json(&json!({ "model": "ollama:", "messages": [] }))- .send()- .await- .expect("bad response")- .json()- .await- .expect("bad json");- assert!(bad["error"]["message"]- .as_str()- .unwrap_or_default()- .contains("empty model"));-- let seen = state.requests.lock().expect("requests").clone();- assert!(seen- .iter()- .any(|(path, body)| path == "/v1/chat/completions" && body["model"] == "bare-chat"));-}--#[tokio::test]-async fn dictation_ws_empty_stop_and_audio_cap_do_not_load_whisper() {- let _env = env_lock_async().await;- let tmp = tempdir().expect("tempdir");- let mut config = temp_config(&tmp);- config.dictation.streaming = false;- config.dictation.llm_refinement = false;-- let ws_url = serve_dictation_ws(config).await;-- let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url)- .await- .expect("connect empty dictation ws");- ws.send(WsMessage::Text(r#"{"type":"stop"}"#.into()))- .await- .expect("send stop");- let final_msg = ws.next().await.expect("final frame").expect("final ok");- let final_json: Value =- serde_json::from_str(final_msg.to_text().expect("text frame")).expect("final json");- assert_eq!(final_json["type"], "final");- assert_eq!(final_json["text"], "");- assert_eq!(final_json["raw_text"], "");-- let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url)- .await- .expect("connect capped dictation ws");- ws.send(WsMessage::Binary(vec![0u8; 9_600_002].into()))- .await- .expect("send oversized pcm");- let error_msg = ws.next().await.expect("error frame").expect("error ok");- let error_json: Value =- serde_json::from_str(error_msg.to_text().expect("text frame")).expect("error json");- assert_eq!(error_json["type"], "error");- assert!(error_json["message"]- .as_str()- .unwrap_or_default()- .contains("Recording limit reached"));-}--#[tokio::test]-async fn local_service_reports_endpoint_state_from_mocked_ollama_without_spawning() {- let _env = env_lock_async().await;- let (base, _state) = serve_mock().await;- let tmp = tempdir().expect("tempdir");- // Runtime binaries on PATH leave a marker if run: OpenHuman probes the- // user's endpoint and must never launch a runtime itself.- let scripts = tempdir().expect("scripts");- let spawn_marker = scripts.path().join("spawned.marker");- let marker_script = format!("#!/bin/sh\ntouch '{}'\nexit 42\n", spawn_marker.display());- for name in ["ollama", "python", "python3", "mlx_lm.generate", "piper"] {- write_stub_script(scripts.path(), name, &marker_script);- }-- let mut config = temp_config(&tmp);- config.local_ai.runtime_enabled = true;- config.local_ai.opt_in_confirmed = true;- config.local_ai.provider = "ollama".to_string();- config.local_ai.base_url = Some(base.clone());- config.local_ai.chat_model_id = "gemma3:1b-it-qat".to_string();- config.local_ai.embedding_model_id = "bge-m3".to_string();- config.local_ai.vision_model_id = "vision-ready".to_string();- config.local_ai.tts_voice_id = "round23-voice".to_string();- config.save().await.expect("save config");-- let _path = EnvVarGuard::set("PATH", scripts.path());- let _workspace = EnvVarGuard::set("OPENHUMAN_WORKSPACE", config.config_path.parent().unwrap());- let _ollama_base = EnvVarGuard::set("OPENHUMAN_OLLAMA_BASE_URL", &base);- let _piper_bin = EnvVarGuard::unset("PIPER_BIN");- let _ollama_bin = EnvVarGuard::unset("OLLAMA_BIN");-- let runtime = openhuman_core::inference::local_runtime_config(&config);- let service = LocalAiService::new(&runtime);- service.bootstrap(&runtime).await;- let status = service.status();- assert_eq!(status.state, "ready");- assert_eq!(status.vision_mode, "ondemand");- assert_eq!(status.chat_model_id, "gemma3:1b-it-qat");-- let diagnostics = service.diagnostics(&runtime).await.expect("diagnostics");- assert_eq!(diagnostics["expected"]["chat_found"], true);- assert_eq!(diagnostics["expected"]["embedding_found"], true);- assert_eq!(diagnostics["expected"]["vision_found"], true);- assert_eq!(diagnostics["repair_actions"], json!([]));-- // No transcription assertion here: `transcribe_with_prompt` is a hosted- // call to the backend proxy since the whisper.cpp engine was deleted.-- let ops_status = local_ai_status(&config).await.expect("ops status").value;- assert_eq!(ops_status.provider, "ollama");- assert!(- !spawn_marker.exists(),- "OpenHuman must never launch a local runtime binary"- );-}--async fn serve_mock() -> (String, MockState) {- let state = MockState::default();- let app = Router::new()- .route("/v1/chat/completions", post(ollama_chat_completions))- .route("/api/tags", get(ollama_tags))- .route("/api/show", post(ollama_show))- .with_state(state.clone());- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind mock");- let addr = listener.local_addr().expect("mock addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve mock");- });- (format!("http://{addr}"), state)-}--async fn serve_app(app: Router) -> String {- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind app");- let addr = listener.local_addr().expect("app addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve app");- });- format!("http://{addr}")-}--async fn serve_dictation_ws(config: Config) -> String {- let config = Arc::new(config);- let app = Router::new().route(- "/ws/dictation",- get({- let config = config.clone();- move |ws: WebSocketUpgrade| {- let config = config.clone();- async move { ws.on_upgrade(move |socket| handle_dictation_ws(socket, config)) }- }- }),- );- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind ws");- let addr = listener.local_addr().expect("ws addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve ws");- });- format!("ws://{addr}/ws/dictation")-}--async fn ollama_chat_completions(- State(state): State<MockState>,- headers: HeaderMap,- Json(body): Json<Value>,-) -> Response<Body> {- remember(&state, "/v1/chat/completions", body.clone());- assert!(- headers.get(header::AUTHORIZATION).is_none(),- "ollama-compatible local requests should be authless"- );- let model = body["model"].as_str().unwrap_or_default();- if body["stream"].as_bool().unwrap_or(false) {- return sse_response([- json!({"choices":[{"delta":{"content":"round23 stream"}}]}),- json!({"choices":[{"delta":{},"finish_reason":"stop"}]}),- ]);- }- Json(json!({- "id": "mock-chat",- "object": "chat.completion",- "choices": [{ "message": { "role": "assistant", "content": format!("round23 chat {model}") } }]- }))- .into_response()-}--async fn ollama_tags() -> impl IntoResponse {- Json(json!({- "models": [- { "name": "configured-chat", "model": "configured-chat" },- { "name": "gemma3:1b-it-qat", "model": "gemma3:1b-it-qat" },- { "name": "bge-m3", "model": "bge-m3" },- { "name": "vision-ready", "model": "vision-ready" }- ]- }))-}--async fn ollama_show(Json(body): Json<Value>) -> impl IntoResponse {- let model = body- .get("model")- .or_else(|| body.get("name"))- .and_then(Value::as_str)- .unwrap_or_default();- if model == "___nonexistent_probe___" {- return (- StatusCode::NOT_FOUND,- Json(json!({"error": "model not found"})),- )- .into_response();- }- Json(json!({- "model_info": {- "general.context_length": 4096,- "llama.context_length": 4096- }- }))- .into_response()-}--fn sse_response<const N: usize>(events: [Value; N]) -> Response<Body> {- let mut body = events- .into_iter()- .map(|event| format!("data: {}\n\n", event))- .collect::<String>();- body.push_str("data: [DONE]\n\n");- Response::builder()- .status(StatusCode::OK)- .header(header::CONTENT_TYPE, "text/event-stream")- .body(Body::from(body))- .expect("sse response")-}--fn remember(state: &MockState, path: &str, body: Value) {- state- .requests- .lock()- .expect("requests")- .push((path.to_string(), body));-}--fn temp_config(tmp: &TempDir) -> Config {- let root = tmp.path().join(".openhuman");- std::fs::create_dir_all(root.join("workspace")).expect("workspace dir");- let mut config = Config {- config_path: root.join("config.toml"),- workspace_dir: root.join("workspace"),- ..Default::default()- };- config.secrets.encrypt = false;- config.api_url = Some("http://127.0.0.1:9".to_string());- config-}--fn store_app_session(config: &Config) {- AuthService::from_config(config)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "round23-session-token",- HashMap::new(),- true,- )- .expect("store app session");-}--fn write_stub_script(dir: &Path, name: &str, body: &str) -> PathBuf {- let path = dir.join(name);- std::fs::write(&path, body).expect("write stub");- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mut perms = std::fs::metadata(&path).expect("metadata").permissions();- perms.set_mode(0o755);- std::fs::set_permissions(&path, perms).expect("chmod");- }- path-}diff --git a/tests/raw_coverage/tools_composio_large_round25_raw_coverage_e2e.rs b/tests/raw_coverage/tools_composio_large_round25_raw_coverage_e2e.rsdeleted file mode 100644index 45462dfe54..0000000000--- a/tests/raw_coverage/tools_composio_large_round25_raw_coverage_e2e.rs+++ /dev/null@@ -1,404 +0,0 @@-//! Round25 focused raw coverage for large Composio direct-mode misses.-//!-//! The direct-mode factory normally pins Composio's production HTTPS API.-//! This test uses debug-only loopback base overrides and temp config stores so-//! no real network, keychain, or backend session is required.--use crate::env_guard::EnvVarGuard;-use std::sync::{Arc, Mutex, OnceLock};--use axum::body::to_bytes;-use axum::extract::{Request, State};-use axum::http::{Method, StatusCode};-use axum::response::{IntoResponse, Response};-use axum::routing::any;-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::{Builder, TempDir};--use openhuman_core::config::Config;-use openhuman_core::integrations::composio::ops::{- cached_active_integrations, composio_authorize, composio_execute, composio_list_connections,- composio_list_toolkits, composio_list_tools, fetch_connected_integrations_status,-};-use openhuman_core::integrations::composio::tools::ComposioListToolsTool;-use openhuman_core::integrations::composio::{- invalidate_connected_integrations_cache, FetchConnectedIntegrationsStatus,-};-use tinytools::{Tool, ToolCallOptions};--static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;--#[derive(Clone, Debug)]-struct RecordedRequest {- method: Method,- path: String,- query: String,- body: Value,- api_key: Option<String>,-}--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<RecordedRequest>>>,-}--struct Harness {- _tmp: TempDir,- config: Config,- _guards: Vec<EnvVarGuard>,-}--fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .blocking_lock()-}--async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock()- .await-}--async fn setup_direct_config(base: &str) -> Harness {- crate::tinyhumans_boot::boot();- std::fs::create_dir_all("target").expect("target dir");- let tmp = Builder::new()- .prefix("tools-composio-large-round25-")- .tempdir_in("target")- .expect("round25 tempdir");- let root = tmp.path().join("openhuman");- let workspace = root.join("workspace");- std::fs::create_dir_all(&workspace).expect("workspace dir");-- let guards = vec![- EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &root),- EnvVarGuard::set_path("HOME", tmp.path()),- EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),- EnvVarGuard::set(- "OPENHUMAN_COMPOSIO_DIRECT_BASE_V2",- format!("{base}/api/v2"),- ),- EnvVarGuard::set(- "OPENHUMAN_COMPOSIO_DIRECT_BASE_V3",- format!("{base}/api/v3"),- ),- EnvVarGuard::unset("BACKEND_URL"),- EnvVarGuard::unset("VITE_BACKEND_URL"),- EnvVarGuard::unset("OPENHUMAN_API_URL"),- EnvVarGuard::unset("OPENHUMAN_CORE_RPC_URL"),- EnvVarGuard::unset("OPENHUMAN_CORE_PORT"),- ];-- let mut config = Config {- workspace_dir: workspace,- config_path: root.join("config.toml"),- ..Config::default()- };- config.composio.mode = "direct".to_string();- config.composio.api_key = Some(" ck_round25_direct ".to_string());- config.composio.entity_id = " entity-round25 ".to_string();- config.secrets.encrypt = false;- config.observability.analytics_enabled = false;- config.save().await.expect("save config");-- Harness {- _tmp: tmp,- config,- _guards: guards,- }-}--#[tokio::test]-async fn round25_direct_mode_ops_use_loopback_factory_for_tools_connections_and_execute() {- let _lock = env_lock_async().await;- invalidate_connected_integrations_cache();-- let state = MockState::default();- let base = start_loopback(- Router::new()- .fallback(any(composio_direct_handler))- .with_state(state.clone()),- )- .await;- let harness = setup_direct_config(&base).await;-- let toolkits = composio_list_toolkits(&harness.config)- .await- .expect("direct list toolkits")- .value;- assert!(toolkits.toolkits.is_empty());-- let connections = composio_list_connections(- &openhuman_core::core::runtime::DispatchCtx::ambient(),- &harness.config,- )- .await- .expect("direct list connections")- .value;- assert_eq!(connections.connections.len(), 3);- assert!(connections- .connections- .iter()- .any(|conn| conn.id == "acct-gmail" && conn.normalized_toolkit() == "gmail"));-- let listed = composio_list_tools(- &openhuman_core::core::runtime::DispatchCtx::ambient(),- &harness.config,- None,- Some(vec![" readOnlyHint ".into(), " ".into()]),- )- .await- .expect("direct list tools")- .value;- assert!(listed- .tools- .iter()- .any(|tool| tool.function.name == "GMAIL_FETCH_EMAILS"));-- let markdown = ComposioListToolsTool::new(Arc::new(harness.config.clone()))- .execute_with_options(- json!({ "toolkits": ["gmail"], "tags": ["readOnlyHint"], "include_unconnected": true }),- ToolCallOptions {- prefer_markdown: true,- },- )- .await- .expect("direct list tools tool markdown");- assert!(!markdown.is_error, "{}", markdown.output());- assert_eq!(markdown.output(), "{\"tools\":[]}");-- let authorize = composio_authorize(- &openhuman_core::core::runtime::DispatchCtx::host_default(),- &harness.config,- " gmail ",- Some(json!({ "ignored_in_direct": true })),- )- .await- .expect("direct authorize")- .value;- assert_eq!(authorize.connection_id, "");- assert_eq!(- authorize.connect_url,- "https://connect.example.test/round25"- );-- let executed = composio_execute(- &harness.config,- "GMAIL_FETCH_EMAILS",- Some(json!({ "query": "label:INBOX" })),- None,- )- .await- .expect("direct execute")- .value;- assert!(executed.successful, "{executed:?}");- assert_eq!(- executed.data.pointer("/messages/0/id"),- Some(&json!("msg-round25"))- );- assert_eq!(executed.cost_usd, 0.0);-- let failed_execute = composio_execute(- &harness.config,- "GMAIL_SEND_EMAIL",- Some(json!({ "to": "[email protected]" })),- None,- )- .await- .expect("direct execute provider failure")- .value;- assert!(!failed_execute.successful);- assert!(failed_execute- .error- .as_deref()- .unwrap_or_default()- .contains("provider rejected send"));-- match fetch_connected_integrations_status(&harness.config).await {- FetchConnectedIntegrationsStatus::Authoritative(integrations) => {- assert!(integrations- .iter()- .any(|item| item.toolkit == "gmail" && item.connected));- assert!(integrations- .iter()- .any(|item| item.toolkit == "slack" && item.connected));- assert!(!integrations- .iter()- .any(|item| item.toolkit == "github" && item.connected));- }- FetchConnectedIntegrationsStatus::Unavailable => {- panic!("direct loopback integrations should be authoritative")- }- }- assert!(cached_active_integrations(&harness.config).is_some());-- let requests = state.requests.lock().expect("requests").clone();- assert!(requests.iter().all(|request| {- request.api_key.as_deref() == Some("ck_round25_direct") || request.path == "/health"- }));- assert!(requests.iter().any(|request| {- request.method == Method::GET- && request.path.ends_with("/connected_accounts")- && request.query.contains("limit=200")- }));- assert!(requests.iter().any(|request| {- request.method == Method::GET- && request.path.ends_with("/tools")- && request.query.contains("tags=readOnlyHint")- }));- assert!(requests.iter().any(|request| {- request.method == Method::POST- && request.path.ends_with("/connected_accounts/link")- && request.body["toolkit"] == "gmail"- && request.body["entity_id"] == " entity-round25 "- }));- assert!(requests.iter().any(|request| {- request.method == Method::POST- && request.path.ends_with("/tools/execute/GMAIL_FETCH_EMAILS")- && request.body["arguments"]["query"] == "label:INBOX"- && request.body["entity_id"] == " entity-round25 "- }));-}--async fn start_loopback(app: Router) -> String {- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind loopback");- let addr = listener.local_addr().expect("local addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("loopback server");- });- format!("http://127.0.0.1:{}", addr.port())-}--async fn composio_direct_handler(State(state): State<MockState>, request: Request) -> Response {- let (parts, body) = request.into_parts();- let method = parts.method;- let path = parts.uri.path().to_string();- let query = parts.uri.query().unwrap_or_default().to_string();- let api_key = parts- .headers- .get("x-api-key")- .and_then(|value| value.to_str().ok())- .map(ToString::to_string);- let body_bytes = to_bytes(body, 1024 * 1024).await.expect("body bytes");- let body_json = if body_bytes.is_empty() {- Value::Null- } else {- serde_json::from_slice(&body_bytes).unwrap_or(Value::Null)- };-- state- .requests- .lock()- .expect("requests")- .push(RecordedRequest {- method: method.clone(),- path: path.clone(),- query: query.clone(),- body: body_json,- api_key,- });-- // TinyConnectors v0.3 serves direct-mode routes from the configured base- // without the host's historical `/api/v3` prefix. Keep this fixture- // tolerant of both shapes while retaining the recorded raw request above.- let route = path- .strip_prefix("/api/v3")- .map_or_else(|| path.clone(), ToString::to_string);-- match (method, format!("/api/v3{route}").as_str()) {- (Method::GET, "/api/v3/connected_accounts") => Json(json!({- "items": [- {- "id": "acct-gmail",- "status": "ACTIVE",- "toolkit": { "slug": "gmail" },- "created_at": "2026-05-30T00:00:00Z"- },- {- "id": "acct-github",- "status": "INITIATED",- "toolkit": "github",- "createdAt": "2026-05-30T00:00:01Z"- },- {- "id": "acct-slack",- "status": "CONNECTED",- "appName": "slack",- "created_at": "2026-05-30T00:00:02Z"- },- {- "id": " ",- "status": "ACTIVE",- "toolkit": "dropme"- }- ]- }))- .into_response(),- (Method::GET, "/api/v3/tools") => Json(json!({- "items": [- {- "slug": "GMAIL_FETCH_EMAILS",- "description": "Fetch Gmail messages",- "toolkit": { "slug": "gmail" },- "input_parameters": {- "type": "object",- "properties": {- "query": { "type": "string" }- }- }- },- {- "slug": "",- "description": "Malformed row should be dropped",- "toolkit": { "slug": "gmail" }- },- {- "name": "SLACK_FETCH_MESSAGES",- "description": "Fetch Slack messages",- "appName": "slack",- "parameters": {- "type": "object",- "properties": {- "channel": { "type": "string" }- }- }- }- ]- }))- .into_response(),- (Method::GET, "/api/v3/auth_configs") => Json(json!({- "items": [- { "id": "auth-disabled", "status": "disabled", "enabled": false },- { "id": "auth-round25", "status": "enabled", "enabled": true }- ]- }))- .into_response(),- (Method::POST, "/api/v3/connected_accounts/link") => Json(json!({- "redirectUrl": "https://connect.example.test/round25"- }))- .into_response(),- (Method::POST, "/api/v3/tools/execute/GMAIL_FETCH_EMAILS") => Json(json!({- "successful": true,- "data": {- "messages": [- { "id": "msg-round25", "subject": "Coverage" }- ]- }- }))- .into_response(),- (Method::POST, "/api/v3/tools/execute/GMAIL_SEND_EMAIL") => Json(json!({- "successful": false,- "error": "provider rejected send",- "data": {- "status": "blocked"- }- }))- .into_response(),- _ => (StatusCode::NOT_FOUND, Json(json!({ "error": "not found" }))).into_response(),- }-}diff --git a/tests/raw_coverage/tools_composio_network_leftovers_raw_coverage_e2e.rs b/tests/raw_coverage/tools_composio_network_leftovers_raw_coverage_e2e.rsdeleted file mode 100644index a235c621ab..0000000000--- a/tests/raw_coverage/tools_composio_network_leftovers_raw_coverage_e2e.rs+++ /dev/null@@ -1,411 +0,0 @@-//! Round20 raw/E2E coverage for Composio tool leftovers and adjacent-//! network-tool branches. All HTTP traffic stays on loopback mocks.--use crate::env_guard::EnvVarGuard;-use std::collections::HashMap;-use std::sync::{Arc, Mutex, OnceLock};--use axum::body::to_bytes;-use axum::extract::{Request, State};-use axum::http::{Method, StatusCode};-use axum::response::{IntoResponse, Response};-use axum::routing::any;-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::{Builder, TempDir};--use openhuman_core::config::Config;-use openhuman_core::integrations::composio::ops::{composio_authorize, composio_list_tools};-use openhuman_core::security::credentials::{- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,-};-use openhuman_core::integrations::composio::tools::{- ComposioListConnectionsTool, ComposioListToolkitsTool, ComposioListToolsTool,-};-use tinytools::{Tool, ToolCallOptions};--static ENV_LOCK: &OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;--#[derive(Clone, Debug)]-struct RecordedRequest {- method: Method,- path: String,- query: String,- body: Value,- api_key: Option<String>,-}--#[derive(Clone, Default)]-struct MockState {- requests: Arc<Mutex<Vec<RecordedRequest>>>,- connections_fail: Arc<Mutex<bool>>,-}--struct Harness {- _tmp: TempDir,- config: Config,- _guards: Vec<EnvVarGuard>,-}--fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .blocking_lock()-}--async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| tokio::sync::Mutex::new(()))- .lock().await-}--fn tempdir() -> TempDir {- std::fs::create_dir_all("target").expect("target dir");- Builder::new()- .prefix("tools-composio-network-leftovers-round20-")- .tempdir_in("target")- .expect("round20 tempdir")-}--async fn setup_config() -> Harness {- crate::tinyhumans_boot::boot();- let tmp = tempdir();- let root = tmp.path().join("openhuman");- let workspace = root.join("workspace");- std::fs::create_dir_all(&workspace).expect("workspace dir");-- let guards = vec![- EnvVarGuard::set_path("OPENHUMAN_WORKSPACE", &root),- EnvVarGuard::set_path("HOME", tmp.path()),- EnvVarGuard::unset("BACKEND_URL"),- EnvVarGuard::unset("VITE_BACKEND_URL"),- EnvVarGuard::unset("OPENHUMAN_API_URL"),- EnvVarGuard::unset("OPENHUMAN_CORE_RPC_URL"),- EnvVarGuard::unset("OPENHUMAN_CORE_PORT"),- EnvVarGuard::unset("OPENHUMAN_LSP_ENABLED"),- ];-- let mut config = Config {- workspace_dir: workspace,- config_path: root.join("config.toml"),- ..Config::default()- };- config.secrets.encrypt = false;- config.observability.analytics_enabled = false;- config.save().await.expect("save config");-- Harness {- _tmp: tmp,- config,- _guards: guards,- }-}--fn store_session_token(config: &Config) {- AuthService::from_config(config)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "round20-session-token",- HashMap::new(),- true,- )- .expect("store app session token");-}--#[tokio::test]-async fn round20_backend_agent_tools_cover_markdown_filtering_and_errors() {- let _lock = env_lock_async().await;- let state = MockState::default();- let base = start_loopback(- Router::new()- .fallback(any(composio_backend_handler))- .with_state(state.clone()),- )- .await;- let mut harness = setup_config().await;- harness.config.api_url = Some(base);- harness.config.save().await.expect("save backend config");- store_session_token(&harness.config);-- let config = Arc::new(harness.config.clone());- let list_toolkits = ComposioListToolkitsTool::new(config.clone());- let toolkits = list_toolkits- .execute(json!({}))- .await- .expect("list toolkits");- assert!(!toolkits.is_error);- assert!(toolkits.output().contains("gmail"));-- let connections_tool = ComposioListConnectionsTool::new(config.clone());- let connections = connections_tool- .execute(json!({}))- .await- .expect("list connections");- assert!(!connections.is_error);- assert!(connections.output().contains("conn-gmail"));- assert!(!connections.output().contains("conn-pending"));-- let list_tools = ComposioListToolsTool::new(config.clone());- let markdown = list_tools- .execute_with_options(- json!({- "toolkits": ["gmail", "github"],- "tags": ["readOnlyHint", "repos"],- "include_unconnected": true- }),- ToolCallOptions {- prefer_markdown: true,- },- )- .await- .expect("list tools markdown");- assert!(!markdown.is_error);- assert!(markdown.output().contains("GMAIL_FETCH_EMAILS"));- assert!(markdown- .markdown_formatted- .as_deref()- .unwrap_or_default()- .contains("# Composio tools"));-- let connected_only = list_tools- .execute(json!({ "toolkits": ["gmail", "github"] }))- .await- .expect("list tools connected only");- assert!(!connected_only.is_error);- assert!(connected_only.output().contains("GMAIL_FETCH_EMAILS"));- assert!(!connected_only.output().contains("GITHUB_STAR_REPOSITORY"));-- let unsupported = list_tools- .execute(json!({- "toolkits": ["totallycustom"],- "include_unconnected": true- }))- .await- .expect("unsupported toolkit empty list");- assert!(unsupported.is_error);- assert!(unsupported.output().contains("no agent-ready actions"));-- *state.connections_fail.lock().expect("connections flag") = true;- let connection_error = list_tools- .execute(json!({ "toolkits": ["gmail"] }))- .await- .expect("connection prefilter error");- assert!(connection_error.is_error);- assert!(connection_error- .output()- .contains("failed to fetch connections"));-- let requests = state.requests.lock().expect("requests").clone();- assert!(requests.iter().any(|request| {- request.method == Method::GET- && request.path == "/agent-integrations/composio/tools"- && request.query.contains("toolkits=gmail")- && request.query.contains("github")- && request.query.contains("tags=readOnlyHint")- && request.query.contains("repos")- }));- assert!(requests.iter().any(|request| {- request.method == Method::GET- && request.path == "/agent-integrations/composio/tools"- && request.query.contains("toolkits=gmail")- && request.query.contains("github")- && !request.query.contains("tags=")- }));-}--#[tokio::test]-async fn round20_composio_ops_cover_authorize_scopes() {- let _lock = env_lock_async().await;- let state = MockState::default();- let base = start_loopback(- Router::new()- .fallback(any(composio_backend_handler))- .with_state(state.clone()),- )- .await;- let mut harness = setup_config().await;- harness.config.api_url = Some(base);- harness.config.save().await.expect("save backend config");- store_session_token(&harness.config);-- let legacy_extra = composio_authorize(- &openhuman_core::core::runtime::DispatchCtx::host_default(),- &harness.config,- "gmail",- Some(json!({ "oauth_scopes": [123] })),- )- .await- .expect("module ignores non-string legacy OAuth scope entries")- .value;- assert_eq!(legacy_extra.connection_id, "conn-authorize");-- let authorized = composio_authorize(- &openhuman_core::core::runtime::DispatchCtx::host_default(),- &harness.config,- " gmail ",- Some(json!({ "waba_id": "waba-round20" })),- )- .await- .expect("authorize with required gmail scope")- .value;- assert_eq!(authorized.connection_id, "conn-authorize");-- let listed = composio_list_tools(- &openhuman_core::core::runtime::DispatchCtx::host_default(),- &harness.config,- Some(vec!["gmail".into(), "github".into()]),- Some(vec!["readOnlyHint".into()]),- )- .await- .expect("ops list tools")- .value;- // The connector module lists only curated actions (b80c12358a): its- // GitHub catalog has no GITHUB_STAR_REPOSITORY, so the mock's second- // tool is gated out.- let names: Vec<&str> = listed- .tools- .iter()- .map(|tool| tool.function.name.as_str())- .collect();- assert_eq!(names, ["GMAIL_FETCH_EMAILS"]);-- let requests = state.requests.lock().expect("requests").clone();- let authorize_body = requests- .iter()- .rfind(|request| request.path == "/agent-integrations/composio/authorize")- .expect("authorize request with the requested WABA id")- .body- .clone();- assert_eq!(authorize_body["toolkit"], "gmail");- assert_eq!(authorize_body["waba_id"], "waba-round20");- assert!(authorize_body["oauth_scopes"]- .as_array()- .expect("oauth scopes array")- .iter()- .any(|scope| scope- .as_str()- .unwrap_or_default()- .contains("gmail.readonly")));-}--async fn start_loopback(app: Router) -> String {- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind loopback");- let addr = listener.local_addr().expect("loopback addr");- tokio::spawn(async move {- axum::serve(listener, app).await.expect("serve loopback");- });- format!("http://127.0.0.1:{}", addr.port())-}--async fn composio_backend_handler(State(state): State<MockState>, request: Request) -> Response {- let method = request.method().clone();- let uri = request.uri().clone();- let path = uri.path().to_string();- let query = uri.query().unwrap_or_default().to_string();- let bytes = to_bytes(request.into_body(), usize::MAX)- .await- .expect("request body");- let body: Value = if bytes.is_empty() {- json!({})- } else {- serde_json::from_slice(&bytes).expect("json body")- };- state- .requests- .lock()- .expect("requests")- .push(RecordedRequest {- method: method.clone(),- path: path.clone(),- query: query.clone(),- body: body.clone(),- api_key: None,- });-- match (method, path.as_str()) {- (Method::GET, "/agent-integrations/composio/toolkits") => ok(json!({- "toolkits": ["gmail", "github", "totallycustom"]- })),- (Method::GET, "/agent-integrations/composio/connections") => {- if *state.connections_fail.lock().expect("connections flag") {- return fail(StatusCode::BAD_GATEWAY, "connections unavailable");- }- ok(json!({- "connections": [- {- "id": "conn-gmail",- "toolkit": "gmail",- "status": "ACTIVE",- "createdAt": "2026-05-30T00:00:00Z"- },- {- "id": "conn-pending",- "toolkit": "github",- "status": "PENDING",- "createdAt": "2026-05-30T00:00:01Z"- }- ]- }))- }- (Method::POST, "/agent-integrations/composio/authorize") => ok(json!({- "connectUrl": "https://connect.example/round20",- "connectionId": "conn-authorize"- })),- (Method::GET, "/agent-integrations/composio/tools") => {- if query.contains("totallycustom") {- ok(json!({ "tools": [] }))- } else {- ok(json!({- "tools": [- {- "type": "function",- "function": {- "name": "GMAIL_FETCH_EMAILS",- "description": "Fetch Gmail messages\nwith whitespace",- "parameters": {- "type": "object",- "required": ["query"],- "properties": {- "query": { "type": "string" },- "max_results": { "type": "integer" }- }- }- }- },- {- "type": "function",- "function": {- "name": "GITHUB_STAR_REPOSITORY",- "description": "Star a repository",- "parameters": {- "type": "object",- "required": ["owner", "repo"],- "properties": {- "owner": { "type": "string" },- "repo": { "type": "string" }- }- }- }- }- ]- }))- }- }- _ => fail(StatusCode::NOT_FOUND, &format!("unhandled backend {path}")),- }-}--fn ok(data: Value) -> Response {- Json(json!({ "success": true, "data": data })).into_response()-}--fn fail(status: StatusCode, error: &str) -> Response {- (- status,- Json(json!({ "success": false, "error": error.to_string() })),- )- .into_response()-}diff --git a/tests/raw_coverage/worker_b_raw_coverage_e2e.rs b/tests/raw_coverage/worker_b_domain_e2e.rssimilarity index 100%rename from tests/raw_coverage/worker_b_raw_coverage_e2e.rsrename to tests/raw_coverage/worker_b_domain_e2e.rs