The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor: extract inline test modules to separate test files
Steven Enamakel548b5510f37c
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rsnew file mode 100644index 0000000000..63fa43ca07--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs@@ -0,0 +1,263 @@+//! Public entry points (`start`/`stop`/`resume`) and the spawned engine loop+//! that drives a run's phase DAG to completion.++use anyhow::{anyhow, Context, Result};+use serde_json::Value;++use crate::agent::orchestration::parent_context::with_root_parent;+use crate::config::Config;+use tinyagents_session::run_ledger::{+ get_workflow_run, upsert_workflow_run, WorkflowRun, WorkflowRunStatus, WorkflowRunUpsert,+};++use super::super::ops::definition_by_id;+use super::super::types::WorkflowDefinition;+use super::cancel::{clear_cancel_flag, lookup_cancel_flag, register_cancel_flag};+use super::state::{init_phase_states, persist};+use super::LOG_TARGET;++/// Start a new workflow run and return immediately.+///+/// Resolves `definition_id` to a builtin [`WorkflowDefinition`], creates a+/// `Running` ledger row with `phase_states` initialised to one `pending` entry+/// per phase, persists it, then `tokio::spawn`s the engine loop. The returned+/// [`WorkflowRun`] is the freshly-created row (status `Running`); callers poll+/// `workflow_run_get` to observe progress.+pub async fn start_workflow_run(+ config: &Config,+ definition_id: &str,+ input: Value,+ parent_thread_id: Option<String>,+) -> Result<WorkflowRun> {+ log::debug!(+ target: LOG_TARGET,+ "[workflow_run_engine] start.entry definition={definition_id} parent_thread={parent_thread_id:?}"+ );+ let definition = definition_by_id(definition_id)+ .ok_or_else(|| anyhow!("unknown workflow definition: {definition_id}"))?;++ let run_id = format!("wfrun-{}", uuid::Uuid::new_v4());+ let phase_states = init_phase_states(&definition);++ let run = upsert_workflow_run(+ &config.workspace_dir,+ WorkflowRunUpsert {+ id: run_id.clone(),+ definition_id: definition.id.clone(),+ parent_thread_id,+ input: input.clone(),+ phase_states,+ child_run_ids: Vec::new(),+ status: WorkflowRunStatus::Running,+ summary: None,+ started_at: None,+ completed_at: None,+ },+ )+ .context("persist initial workflow run")?;++ register_cancel_flag(&run_id);++ // Spawn the engine loop. Clone what the task needs (the engine reloads+ // config inside the task so it can build a real Agent without holding a+ // borrow across the spawn boundary).+ let task_run_id = run_id.clone();+ // Task-locals don't cross `tokio::spawn`, so capture the starting turn's+ // origin here and re-scope it around the engine loop — the phases spawn+ // sub-agents whose tool calls the approval gate judges by that label.+ // Inherit-only: `None` leaves the loop unlabelled and failing closed.+ let inherited_origin = crate::agent::turn_origin::capture();+ tokio::spawn(async move {+ match Config::load_or_init().await {+ Ok(task_config) => {+ crate::agent::turn_origin::with_inherited_origin(+ inherited_origin,+ run_engine_loop(&task_config, &task_run_id, definition),+ )+ .await;+ }+ Err(err) => {+ log::error!(+ target: LOG_TARGET,+ "[workflow_run_engine] start.config_load_failed run={task_run_id} err={err}"+ );+ }+ }+ });++ log::debug!(+ target: LOG_TARGET,+ "[workflow_run_engine] start.spawned run={run_id} phases={}",+ run.phase_states.as_object().map(|m| m.len()).unwrap_or(0)+ );+ Ok(run)+}++/// Signal a running workflow to stop after its current phase.+///+/// Flips the run's cancellation flag (checked by the loop between phases) and+/// eagerly marks the persisted row `Interrupted` so a poller sees the intent+/// immediately even while the in-flight phase drains. Idempotent: stopping a+/// terminal or unknown run is a no-op that returns the current row.+pub async fn stop_workflow_run(config: &Config, id: &str) -> Result<Option<WorkflowRun>> {+ log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.entry run={id}");+ let Some(run) = get_workflow_run(&config.workspace_dir, id)? else {+ log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.unknown run={id}");+ return Ok(None);+ };++ if matches!(+ run.status,+ WorkflowRunStatus::Completed | WorkflowRunStatus::Failed | WorkflowRunStatus::Cancelled+ ) {+ log::debug!(+ target: LOG_TARGET,+ "[workflow_run_engine] stop.already_terminal run={id} status={}",+ run.status.as_str()+ );+ return Ok(Some(run));+ }++ if let Some(signal) = super::cancel::lookup_cancel_signal(id) {+ signal.flag.store(true, std::sync::atomic::Ordering::SeqCst);+ signal.token.cancel();+ } else {+ // No live loop (e.g. process restart) — register a flag anyway so a+ // future resume observes the stop intent.+ let signal = super::cancel::register_cancel_signal(id);+ signal.flag.store(true, std::sync::atomic::Ordering::SeqCst);+ signal.token.cancel();+ }++ let updated = upsert_workflow_run(+ &config.workspace_dir,+ WorkflowRunUpsert {+ id: run.id.clone(),+ definition_id: run.definition_id.clone(),+ parent_thread_id: run.parent_thread_id.clone(),+ input: run.input.clone(),+ phase_states: run.phase_states.clone(),+ child_run_ids: run.child_run_ids.clone(),+ status: WorkflowRunStatus::Interrupted,+ summary: run.summary.clone(),+ started_at: Some(run.started_at),+ completed_at: None,+ },+ )+ .context("persist workflow run interrupt")?;++ log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.marked_interrupted run={id}");+ Ok(Some(updated))+}++/// Resume an interrupted (or otherwise incomplete) workflow run.+///+/// Reloads the run, clears any stale cancellation flag, flips the row back to+/// `Running`, and spawns a fresh engine loop. Phases already `completed` in+/// `phase_states` are skipped; the loop continues from the first incomplete+/// phase whose dependencies are satisfied. Returns the run row (now `Running`),+/// or an error if the run is unknown / already terminal-complete / its+/// definition no longer exists.+pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRun> {+ log::debug!(target: LOG_TARGET, "[workflow_run_engine] resume.entry run={id}");+ let run = get_workflow_run(&config.workspace_dir, id)?+ .ok_or_else(|| anyhow!("unknown workflow run: {id}"))?;++ if matches!(run.status, WorkflowRunStatus::Completed) {+ return Err(anyhow!("workflow run {id} is already completed"));+ }++ let definition = definition_by_id(&run.definition_id)+ .ok_or_else(|| anyhow!("definition {} no longer exists", run.definition_id))?;++ // Clear any prior cancellation intent and re-register a fresh flag.+ clear_cancel_flag(id);+ register_cancel_flag(id);++ let resumed = upsert_workflow_run(+ &config.workspace_dir,+ WorkflowRunUpsert {+ id: run.id.clone(),+ definition_id: run.definition_id.clone(),+ parent_thread_id: run.parent_thread_id.clone(),+ input: run.input.clone(),+ phase_states: run.phase_states.clone(),+ child_run_ids: run.child_run_ids.clone(),+ status: WorkflowRunStatus::Running,+ summary: run.summary.clone(),+ started_at: Some(run.started_at),+ completed_at: None,+ },+ )+ .context("persist workflow run resume")?;++ let task_run_id = id.to_string();+ // Same inherit-only origin propagation as `start_workflow_run`: the resumed+ // loop runs on a fresh task, which would otherwise drop the caller's label.+ let inherited_origin = crate::agent::turn_origin::capture();+ tokio::spawn(async move {+ match Config::load_or_init().await {+ Ok(task_config) => {+ crate::agent::turn_origin::with_inherited_origin(+ inherited_origin,+ run_engine_loop(&task_config, &task_run_id, definition),+ )+ .await;+ }+ Err(err) => {+ log::error!(+ target: LOG_TARGET,+ "[workflow_run_engine] resume.config_load_failed run={task_run_id} err={err}"+ );+ }+ }+ });++ log::debug!(target: LOG_TARGET, "[workflow_run_engine] resume.spawned run={id}");+ Ok(resumed)+}++/// Build the root parent context + drive the phase DAG to completion.+///+/// Separated from [`start_workflow_run`] so it can run on the spawned task with+/// an owned [`Config`]. Errors are recorded on the run row (status `Failed`)+/// rather than propagated — there is no caller to receive them.+pub(super) async fn run_engine_loop(config: &Config, run_id: &str, definition: WorkflowDefinition) {+ let cancel = lookup_cancel_flag(run_id).unwrap_or_else(|| register_cancel_flag(run_id));++ let outcome = with_root_parent(config, "workflow_engine", "workflow", "workflow", async {+ super::super::graph::drive_phases(config, run_id, &definition, &cancel).await+ })+ .await+ // Flatten: outer Err = root-parent build failure, inner = drive_phases result.+ .unwrap_or_else(Err);++ if let Err(err) = outcome {+ log::error!(+ target: LOG_TARGET,+ "[workflow_run_engine] loop.failed run={run_id} err={err}"+ );+ // Best-effort terminal failure write, preserving partial phase state.+ if let Ok(Some(run)) = get_workflow_run(&config.workspace_dir, run_id) {+ if !matches!(+ run.status,+ WorkflowRunStatus::Completed+ | WorkflowRunStatus::Failed+ | WorkflowRunStatus::Cancelled+ | WorkflowRunStatus::Interrupted+ ) {+ let _ = persist(+ config,+ &run,+ run.phase_states.clone(),+ run.child_run_ids.clone(),+ WorkflowRunStatus::Failed,+ Some(format!("engine error: {err}")),+ true,+ );+ }+ }+ }++ clear_cancel_flag(run_id);+}diff --git a/crates/openhuman-core/src/bin/rss_bench.rs b/crates/openhuman-core/src/bin/rss_bench.rsindex e79528c994..08becccf21 100644--- a/crates/openhuman-core/src/bin/rss_bench.rs+++ b/crates/openhuman-core/src/bin/rss_bench.rs@@ -376,47 +376,7 @@ async fn main() -> Result<()> {}}-#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn build_roster_constructs_bare_agents_with_isolated_workspaces() {- let roster = build_roster(8).expect("8-agent roster builds");- assert_eq!(roster.agents.len(), 8);- assert_eq!(roster._workspaces.len(), 8);- // Each agent got a distinct workspace directory.- let mut dirs: Vec<_> = roster- ._workspaces- .iter()- .map(|w| w.path().to_path_buf())- .collect();- dirs.sort();- dirs.dedup();- assert_eq!(dirs.len(), 8, "workspaces must be isolated per agent");- }- #[test]- fn warm_up_turn_completes_without_network() {- // The agent-turn future is large in debug builds. Run it on a worker- // with explicit stack headroom instead of libtest's smaller default.- let runtime = tokio::runtime::Builder::new_multi_thread()- .worker_threads(1)- .enable_all()- .thread_stack_size(8 * 1024 * 1024)- .build()- .expect("test runtime builds");- runtime- .block_on(runtime.spawn(async {- let mut roster = build_roster(1).expect("1-agent roster builds");- warm_up(&mut roster).await.expect("warm-up turn completes");- // The mock provider reports usage, so last_turn_usage is populated —- // proving the embedding cost-metering contract works on the bare Agent.- assert!(- roster.agents[0].last_turn_usage().is_some(),- "usage should be readable after a turn"- );- }))- .expect("warm-up task joins");- }-}+#[cfg(test)]+#[path = "rss_bench_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/bin/rss_bench_tests.rs b/crates/openhuman-core/src/bin/rss_bench_tests.rsnew file mode 100644index 0000000000..74eef62e6e--- /dev/null+++ b/crates/openhuman-core/src/bin/rss_bench_tests.rs@@ -0,0 +1,41 @@+use super::*;++#[test]+fn build_roster_constructs_bare_agents_with_isolated_workspaces() {+ let roster = build_roster(8).expect("8-agent roster builds");+ assert_eq!(roster.agents.len(), 8);+ assert_eq!(roster._workspaces.len(), 8);+ // Each agent got a distinct workspace directory.+ let mut dirs: Vec<_> = roster+ ._workspaces+ .iter()+ .map(|w| w.path().to_path_buf())+ .collect();+ dirs.sort();+ dirs.dedup();+ assert_eq!(dirs.len(), 8, "workspaces must be isolated per agent");+}++#[test]+fn warm_up_turn_completes_without_network() {+ // The agent-turn future is large in debug builds. Run it on a worker+ // with explicit stack headroom instead of libtest's smaller default.+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(1)+ .enable_all()+ .thread_stack_size(8 * 1024 * 1024)+ .build()+ .expect("test runtime builds");+ runtime+ .block_on(runtime.spawn(async {+ let mut roster = build_roster(1).expect("1-agent roster builds");+ warm_up(&mut roster).await.expect("warm-up turn completes");+ // The mock provider reports usage, so last_turn_usage is populated —+ // proving the embedding cost-metering contract works on the bare Agent.+ assert!(+ roster.agents[0].last_turn_usage().is_some(),+ "usage should be readable after a turn"+ );+ }))+ .expect("warm-up task joins");+}diff --git a/crates/openhuman-core/src/core/types.rs b/crates/openhuman-core/src/core/types.rsindex 2d1af93416..400114208c 100644--- a/crates/openhuman-core/src/core/types.rs+++ b/crates/openhuman-core/src/core/types.rs@@ -250,246 +250,5 @@ pub fn approval_gate_boot_decision(}#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn invocation_result_ok_serializes_value() {- let result = InvocationResult::ok(json!({"key": "value"})).unwrap();- assert_eq!(result.value, json!({"key": "value"}));- assert!(result.logs.is_empty());- }-- #[test]- fn invocation_result_with_logs() {- let result =- InvocationResult::with_logs(json!(42), vec!["log1".into(), "log2".into()]).unwrap();- assert_eq!(result.value, json!(42));- assert_eq!(result.logs.len(), 2);- }-- #[test]- fn invocation_to_rpc_json_no_logs_returns_value_directly() {- let inv = InvocationResult {- value: json!({"data": true}),- logs: vec![],- };- let json = invocation_to_rpc_json(inv);- assert_eq!(json, json!({"data": true}));- }-- #[test]- fn invocation_to_rpc_json_with_logs_wraps_in_envelope() {- let inv = InvocationResult {- value: json!({"data": true}),- logs: vec!["info".into()],- };- let json = invocation_to_rpc_json(inv);- assert!(json.get("result").is_some());- assert!(json.get("logs").is_some());- assert_eq!(json["result"], json!({"data": true}));- assert_eq!(json["logs"][0], "info");- }-- /// The two controller return paths must produce byte-identical JSON for the- /// same (value, logs) pair.- ///- /// `RpcOutcome::into_cli_compatible_json` (the registry path, 152 call- /// sites) and `invocation_to_rpc_json` (the dynamic-dispatch path) used to- /// carry independent copies of the same envelope rule. Nothing linked them,- /// so a fix or a normalisation applied to one would have left the other- /// answering the old shape — the divergence would have been invisible until- /// a caller hit the wrong path. Both now delegate to- /// `rpc::apply_log_envelope`; this asserts they still agree, so a future- /// edit cannot re-fork them without failing here.- ///- /// It deliberately asserts *agreement*, not a particular shape: the shape- /// itself is the open question in #6080, and pinning it here would enshrine- /// the defect as intended behaviour.- #[test]- fn both_controller_return_paths_apply_the_same_log_envelope() {- for (value, logs) in [- (json!({ "data": true }), Vec::<String>::new()),- (json!({ "data": true }), vec!["one".to_string()]),- (json!(null), vec!["log on a null value".to_string()]),- (json!([1, 2, 3]), Vec::<String>::new()),- // A value that already carries a `result` key: the envelope must- // treat it as opaque data, not as an envelope to flatten.- (json!({ "result": "inner", "logs": ["not mine"] }), vec![]),- ] {- let via_dispatch = invocation_to_rpc_json(InvocationResult {- value: value.clone(),- logs: logs.clone(),- });- let via_registry = crate::rpc::RpcOutcome::new(value.clone(), logs.clone())- .into_cli_compatible_json()- .expect("a serde_json::Value always serializes");-- assert_eq!(- via_dispatch, via_registry,- "the dispatch and registry paths disagreed for value={value} logs={logs:?}; \- both must go through rpc::apply_log_envelope"- );- }- }-- #[test]- fn command_response_serde_roundtrip() {- let resp = CommandResponse {- result: "ok".to_string(),- logs: vec!["log1".into()],- };- let json = serde_json::to_string(&resp).unwrap();- let back: CommandResponse<String> = serde_json::from_str(&json).unwrap();- assert_eq!(back.result, "ok");- assert_eq!(back.logs.len(), 1);- }-- #[test]- fn rpc_request_deserializes() {- let json = r#"{"jsonrpc":"2.0","id":1,"method":"test","params":{}}"#;- let req: RpcRequest = serde_json::from_str(json).unwrap();- assert_eq!(req.method, "test");- assert_eq!(req.id, json!(1));- }-- #[test]- fn rpc_request_params_default_to_null() {- let json = r#"{"jsonrpc":"2.0","id":"abc","method":"foo"}"#;- let req: RpcRequest = serde_json::from_str(json).unwrap();- assert!(req.params.is_null());- }-- #[test]- fn rpc_success_serializes() {- let resp = RpcSuccess {- jsonrpc: "2.0",- id: json!(42),- result: json!({"ok": true}),- };- let json = serde_json::to_string(&resp).unwrap();- assert!(json.contains("\"jsonrpc\":\"2.0\""));- assert!(json.contains("\"id\":42"));- }-- #[test]- fn rpc_failure_serializes() {- let resp = RpcFailure {- jsonrpc: "2.0",- id: json!("req-1"),- error: RpcError {- code: -32601,- message: "Method not found".into(),- data: Some(json!({"detail": "unknown"})),- },- };- let json = serde_json::to_string(&resp).unwrap();- assert!(json.contains("-32601"));- assert!(json.contains("Method not found"));- }-- #[test]- fn rpc_failure_serializes_without_data() {- let resp = RpcFailure {- jsonrpc: "2.0",- id: json!(null),- error: RpcError {- code: -32700,- message: "Parse error".into(),- data: None,- },- };- let json = serde_json::to_string(&resp).unwrap();- assert!(json.contains("-32700"));- }-- #[test]- fn app_state_clone() {- let state = AppState {- core_version: "0.1.0".into(),- };- let cloned = state.clone();- assert_eq!(cloned.core_version, "0.1.0");- }-- #[test]- fn host_kind_tag_is_stable() {- // Downstream consumers (event-bus subscribers, log shippers) key- // on the exact tag strings; pin them so a rename is loud.- assert_eq!(HostKind::TauriShell.tag(), "tauri-shell");- assert_eq!(HostKind::Cli.tag(), "cli");- assert_eq!(HostKind::Docker.tag(), "docker");- assert_eq!(HostKind::Library.tag(), "library");- }-- #[test]- fn host_kind_is_desktop_shell_only_for_tauri() {- assert!(HostKind::TauriShell.is_desktop_shell());- assert!(!HostKind::Cli.is_desktop_shell());- assert!(!HostKind::Docker.is_desktop_shell());- assert!(!HostKind::Library.is_desktop_shell());- }-- #[test]- fn desktop_shell_ignores_env_override() {- // Operator sets OPENHUMAN_APPROVAL_GATE=0 inside a Tauri-shell- // boot — the gate MUST still install, and the override-ignored- // signal MUST fire so the UI can banner.- let d = approval_gate_boot_decision(HostKind::TauriShell, true);- assert!(d.install_gate, "tauri shell must always install the gate");- assert!(- d.override_ignored,- "tauri shell must surface that an override was attempted + ignored"- );- assert!(- !d.gate_disabled_by_override,- "desktop path never reports the gate as disabled by env"- );- }-- #[test]- fn desktop_shell_with_no_override_keeps_gate_silent() {- // Normal Tauri boot, no env override — gate installs, no banners,- // no warning event. This is the steady-state desktop path.- let d = approval_gate_boot_decision(HostKind::TauriShell, false);- assert!(d.install_gate);- assert!(!d.override_ignored);- assert!(!d.gate_disabled_by_override);- }-- #[test]- fn standalone_cli_honors_env_override_with_warning_signal() {- let d = approval_gate_boot_decision(HostKind::Cli, true);- assert!(!d.install_gate, "CLI must honor the operator env override");- assert!(- d.gate_disabled_by_override,- "CLI must surface the elevated-privilege state via the disabled event"- );- assert!(- !d.override_ignored,- "CLI doesn't ignore; it honors — only desktop ignores"- );- }-- #[test]- fn standalone_docker_honors_env_override_with_warning_signal() {- let d = approval_gate_boot_decision(HostKind::Docker, true);- assert!(!d.install_gate);- assert!(d.gate_disabled_by_override);- assert!(!d.override_ignored);- }-- #[test]- fn standalone_with_no_env_override_installs_gate_silently() {- for host in [HostKind::Cli, HostKind::Docker, HostKind::Library] {- let d = approval_gate_boot_decision(host, false);- assert!(- d.install_gate,- "{host:?} with no override must install the gate"- );- assert!(!d.override_ignored);- assert!(!d.gate_disabled_by_override);- }- }-}+#[path = "types_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/core/types_tests.rs b/crates/openhuman-core/src/core/types_tests.rsnew file mode 100644index 0000000000..32d6ecd7d9--- /dev/null+++ b/crates/openhuman-core/src/core/types_tests.rs@@ -0,0 +1,242 @@+use super::*;+ use super::*;+ use serde_json::json;++ #[test]+ fn invocation_result_ok_serializes_value() {+ let result = InvocationResult::ok(json!({"key": "value"})).unwrap();+ assert_eq!(result.value, json!({"key": "value"}));+ assert!(result.logs.is_empty());+ }++ #[test]+ fn invocation_result_with_logs() {+ let result =+ InvocationResult::with_logs(json!(42), vec!["log1".into(), "log2".into()]).unwrap();+ assert_eq!(result.value, json!(42));+ assert_eq!(result.logs.len(), 2);+ }++ #[test]+ fn invocation_to_rpc_json_no_logs_returns_value_directly() {+ let inv = InvocationResult {+ value: json!({"data": true}),+ logs: vec![],+ };+ let json = invocation_to_rpc_json(inv);+ assert_eq!(json, json!({"data": true}));+ }++ #[test]+ fn invocation_to_rpc_json_with_logs_wraps_in_envelope() {+ let inv = InvocationResult {+ value: json!({"data": true}),+ logs: vec!["info".into()],+ };+ let json = invocation_to_rpc_json(inv);+ assert!(json.get("result").is_some());+ assert!(json.get("logs").is_some());+ assert_eq!(json["result"], json!({"data": true}));+ assert_eq!(json["logs"][0], "info");+ }++ /// The two controller return paths must produce byte-identical JSON for the+ /// same (value, logs) pair.+ ///+ /// `RpcOutcome::into_cli_compatible_json` (the registry path, 152 call+ /// sites) and `invocation_to_rpc_json` (the dynamic-dispatch path) used to+ /// carry independent copies of the same envelope rule. Nothing linked them,+ /// so a fix or a normalisation applied to one would have left the other+ /// answering the old shape — the divergence would have been invisible until+ /// a caller hit the wrong path. Both now delegate to+ /// `rpc::apply_log_envelope`; this asserts they still agree, so a future+ /// edit cannot re-fork them without failing here.+ ///+ /// It deliberately asserts *agreement*, not a particular shape: the shape+ /// itself is the open question in #6080, and pinning it here would enshrine+ /// the defect as intended behaviour.+ #[test]+ fn both_controller_return_paths_apply_the_same_log_envelope() {+ for (value, logs) in [+ (json!({ "data": true }), Vec::<String>::new()),+ (json!({ "data": true }), vec!["one".to_string()]),+ (json!(null), vec!["log on a null value".to_string()]),+ (json!([1, 2, 3]), Vec::<String>::new()),+ // A value that already carries a `result` key: the envelope must+ // treat it as opaque data, not as an envelope to flatten.+ (json!({ "result": "inner", "logs": ["not mine"] }), vec![]),+ ] {+ let via_dispatch = invocation_to_rpc_json(InvocationResult {+ value: value.clone(),+ logs: logs.clone(),+ });+ let via_registry = crate::rpc::RpcOutcome::new(value.clone(), logs.clone())+ .into_cli_compatible_json()+ .expect("a serde_json::Value always serializes");++ assert_eq!(+ via_dispatch, via_registry,+ "the dispatch and registry paths disagreed for value={value} logs={logs:?}; \+ both must go through rpc::apply_log_envelope"+ );+ }+ }++ #[test]+ fn command_response_serde_roundtrip() {+ let resp = CommandResponse {+ result: "ok".to_string(),+ logs: vec!["log1".into()],+ };+ let json = serde_json::to_string(&resp).unwrap();+ let back: CommandResponse<String> = serde_json::from_str(&json).unwrap();+ assert_eq!(back.result, "ok");+ assert_eq!(back.logs.len(), 1);+ }++ #[test]+ fn rpc_request_deserializes() {+ let json = r#"{"jsonrpc":"2.0","id":1,"method":"test","params":{}}"#;+ let req: RpcRequest = serde_json::from_str(json).unwrap();+ assert_eq!(req.method, "test");+ assert_eq!(req.id, json!(1));+ }++ #[test]+ fn rpc_request_params_default_to_null() {+ let json = r#"{"jsonrpc":"2.0","id":"abc","method":"foo"}"#;+ let req: RpcRequest = serde_json::from_str(json).unwrap();+ assert!(req.params.is_null());+ }++ #[test]+ fn rpc_success_serializes() {+ let resp = RpcSuccess {+ jsonrpc: "2.0",+ id: json!(42),+ result: json!({"ok": true}),+ };+ let json = serde_json::to_string(&resp).unwrap();+ assert!(json.contains("\"jsonrpc\":\"2.0\""));+ assert!(json.contains("\"id\":42"));+ }++ #[test]+ fn rpc_failure_serializes() {+ let resp = RpcFailure {+ jsonrpc: "2.0",+ id: json!("req-1"),+ error: RpcError {+ code: -32601,+ message: "Method not found".into(),+ data: Some(json!({"detail": "unknown"})),+ },+ };+ let json = serde_json::to_string(&resp).unwrap();+ assert!(json.contains("-32601"));+ assert!(json.contains("Method not found"));+ }++ #[test]+ fn rpc_failure_serializes_without_data() {+ let resp = RpcFailure {+ jsonrpc: "2.0",+ id: json!(null),+ error: RpcError {+ code: -32700,+ message: "Parse error".into(),+ data: None,+ },+ };+ let json = serde_json::to_string(&resp).unwrap();+ assert!(json.contains("-32700"));+ }++ #[test]+ fn app_state_clone() {+ let state = AppState {+ core_version: "0.1.0".into(),+ };+ let cloned = state.clone();+ assert_eq!(cloned.core_version, "0.1.0");+ }++ #[test]+ fn host_kind_tag_is_stable() {+ // Downstream consumers (event-bus subscribers, log shippers) key+ // on the exact tag strings; pin them so a rename is loud.+ assert_eq!(HostKind::TauriShell.tag(), "tauri-shell");+ assert_eq!(HostKind::Cli.tag(), "cli");+ assert_eq!(HostKind::Docker.tag(), "docker");+ assert_eq!(HostKind::Library.tag(), "library");+ }++ #[test]+ fn host_kind_is_desktop_shell_only_for_tauri() {+ assert!(HostKind::TauriShell.is_desktop_shell());+ assert!(!HostKind::Cli.is_desktop_shell());+ assert!(!HostKind::Docker.is_desktop_shell());+ assert!(!HostKind::Library.is_desktop_shell());+ }++ #[test]+ fn desktop_shell_ignores_env_override() {+ // Operator sets OPENHUMAN_APPROVAL_GATE=0 inside a Tauri-shell+ // boot — the gate MUST still install, and the override-ignored+ // signal MUST fire so the UI can banner.+ let d = approval_gate_boot_decision(HostKind::TauriShell, true);+ assert!(d.install_gate, "tauri shell must always install the gate");+ assert!(+ d.override_ignored,+ "tauri shell must surface that an override was attempted + ignored"+ );+ assert!(+ !d.gate_disabled_by_override,+ "desktop path never reports the gate as disabled by env"+ );+ }++ #[test]+ fn desktop_shell_with_no_override_keeps_gate_silent() {+ // Normal Tauri boot, no env override — gate installs, no banners,+ // no warning event. This is the steady-state desktop path.+ let d = approval_gate_boot_decision(HostKind::TauriShell, false);+ assert!(d.install_gate);+ assert!(!d.override_ignored);+ assert!(!d.gate_disabled_by_override);+ }++ #[test]+ fn standalone_cli_honors_env_override_with_warning_signal() {+ let d = approval_gate_boot_decision(HostKind::Cli, true);+ assert!(!d.install_gate, "CLI must honor the operator env override");+ assert!(+ d.gate_disabled_by_override,+ "CLI must surface the elevated-privilege state via the disabled event"+ );+ assert!(+ !d.override_ignored,+ "CLI doesn't ignore; it honors — only desktop ignores"+ );+ }++ #[test]+ fn standalone_docker_honors_env_override_with_warning_signal() {+ let d = approval_gate_boot_decision(HostKind::Docker, true);+ assert!(!d.install_gate);+ assert!(d.gate_disabled_by_override);+ assert!(!d.override_ignored);+ }++ #[test]+ fn standalone_with_no_env_override_installs_gate_silently() {+ for host in [HostKind::Cli, HostKind::Docker, HostKind::Library] {+ let d = approval_gate_boot_decision(host, false);+ assert!(+ d.install_gate,+ "{host:?} with no override must install the gate"+ );+ assert!(!d.override_ignored);+ assert!(!d.gate_disabled_by_override);+ }+ }diff --git a/crates/openhuman-core/src/integrations/composio/schemas_part_01.rs b/crates/openhuman-core/src/integrations/composio/schemas_part_01.rsdeleted file mode 100644index ec78a768f0..0000000000--- a/crates/openhuman-core/src/integrations/composio/schemas_part_01.rs+++ /dev/null@@ -1,167 +0,0 @@-use serde::de::DeserializeOwned;-use serde_json::{Map, Value};--use crate::core::all::{ControllerFuture, RegisteredController};-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-use crate::config::rpc as config_rpc;-use crate::rpc::RpcOutcome;--#[derive(Debug, serde::Deserialize)]-struct TriggerHistoryParams {- limit: Option<usize>,-}--#[derive(Debug, serde::Deserialize)]-struct ListGithubReposParams {- connection_id: Option<String>,-}--#[derive(Debug, serde::Deserialize)]-struct CreateTriggerParams {- slug: String,- connection_id: Option<String>,- trigger_config: Option<Value>,-}--#[derive(Debug, serde::Deserialize)]-struct ListAvailableTriggersParams {- toolkit: String,- connection_id: Option<String>,-}--#[derive(Debug, serde::Deserialize)]-struct ListTriggersParams {- toolkit: Option<String>,-}--#[derive(Debug, serde::Deserialize)]-struct EnableTriggerParams {- connection_id: String,- slug: String,- trigger_config: Option<Value>,-}--pub fn all_controller_schemas() -> Vec<ControllerSchema> {- vec![- schemas("list_toolkits"),- schemas("list_capabilities"),- schemas("list_agent_ready_toolkits"),- schemas("list_connections"),- schemas("authorize"),- schemas("delete_connection"),- schemas("list_tools"),- schemas("execute"),- schemas("list_github_repos"),- schemas("create_trigger"),- schemas("get_user_profile"),- schemas("refresh_all_identities"),- schemas("sync"),- schemas("list_trigger_history"),- schemas("get_user_scopes"),- schemas("set_user_scopes"),- schemas("list_available_triggers"),- schemas("list_triggers"),- schemas("enable_trigger"),- schemas("disable_trigger"),- schemas("get_mode"),- schemas("set_api_key"),- schemas("clear_api_key"),- ]-}--pub fn all_registered_controllers() -> Vec<RegisteredController> {- vec![- RegisteredController {- schema: schemas("list_toolkits"),- handler: handle_list_toolkits,- },- RegisteredController {- schema: schemas("list_capabilities"),- handler: handle_list_capabilities,- },- RegisteredController {- schema: schemas("list_agent_ready_toolkits"),- handler: handle_list_agent_ready_toolkits,- },- RegisteredController {- schema: schemas("list_connections"),- handler: handle_list_connections,- },- RegisteredController {- schema: schemas("authorize"),- handler: handle_authorize,- },- RegisteredController {- schema: schemas("delete_connection"),- handler: handle_delete_connection,- },- RegisteredController {- schema: schemas("list_tools"),- handler: handle_list_tools,- },- RegisteredController {- schema: schemas("execute"),- handler: handle_execute,- },- RegisteredController {- schema: schemas("list_github_repos"),- handler: handle_list_github_repos,- },- RegisteredController {- schema: schemas("create_trigger"),- handler: handle_create_trigger,- },- RegisteredController {- schema: schemas("get_user_profile"),- handler: handle_get_user_profile,- },- RegisteredController {- schema: schemas("refresh_all_identities"),- handler: handle_refresh_all_identities,- },- RegisteredController {- schema: schemas("sync"),- handler: handle_sync,- },- RegisteredController {- schema: schemas("list_trigger_history"),- handler: handle_list_trigger_history,- },- RegisteredController {- schema: schemas("get_user_scopes"),- handler: handle_get_user_scopes,- },- RegisteredController {- schema: schemas("set_user_scopes"),- handler: handle_set_user_scopes,- },- RegisteredController {- schema: schemas("list_available_triggers"),- handler: handle_list_available_triggers,- },- RegisteredController {- schema: schemas("list_triggers"),- handler: handle_list_triggers,- },- RegisteredController {- schema: schemas("enable_trigger"),- handler: handle_enable_trigger,- },- RegisteredController {- schema: schemas("disable_trigger"),- handler: handle_disable_trigger,- },- RegisteredController {- schema: schemas("get_mode"),- handler: handle_get_mode,- },- RegisteredController {- schema: schemas("set_api_key"),- handler: handle_set_api_key,- },- RegisteredController {- schema: schemas("clear_api_key"),- handler: handle_clear_api_key,- },- ]-}diff --git a/crates/openhuman-core/src/integrations/composio/schemas_part_02.rs b/crates/openhuman-core/src/integrations/composio/schemas_part_02.rsdeleted file mode 100644index 9ef1e0e024..0000000000--- a/crates/openhuman-core/src/integrations/composio/schemas_part_02.rs+++ /dev/null@@ -1,678 +0,0 @@--pub fn schemas(function: &str) -> ControllerSchema {- match function {- "list_toolkits" => ControllerSchema {- namespace: "composio",- function: "list_toolkits",- description: "List the Composio toolkits currently enabled on the backend allowlist.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "toolkits",- ty: TypeSchema::Array(Box::new(TypeSchema::String)),- comment: "Toolkit slugs enabled by the backend (e.g. gmail, notion).",- required: true,- }],- },- "list_capabilities" => ControllerSchema {- namespace: "composio",- function: "list_capabilities",- description: "List OpenHuman's built-in Composio capability matrix without requiring a signed-in Composio session.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "capabilities",- ty: TypeSchema::Json,- comment: "Array of capability rows describing native providers, curated catalogs, sync, trigger, and memory-ingest support.",- required: true,- }],- },- "list_agent_ready_toolkits" => ControllerSchema {- namespace: "composio",- function: "list_agent_ready_toolkits",- description:- "List every toolkit slug that ships an agent-ready curated catalog. Connected \- toolkits not in this list should be surfaced in the UI as preview / agent \- integration coming soon. See issue #2283.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "toolkits",- ty: TypeSchema::Array(Box::new(TypeSchema::String)),- comment: "Sorted toolkit slugs with curated catalogs (e.g. gmail, notion, one_drive, excel, todoist).",- required: true,- }],- },- "list_connections" => ControllerSchema {- namespace: "composio",- function: "list_connections",- description:- "List the caller's active Composio OAuth connections filtered to the allowlist.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "connections",- ty: TypeSchema::Json,- comment: "Array of {id, toolkit, status, createdAt} objects.",- required: true,- }],- },- "authorize" => ControllerSchema {- namespace: "composio",- function: "authorize",- description: "Begin an OAuth handoff for a toolkit and return the hosted connect URL.",- inputs: vec![- FieldSchema {- name: "toolkit",- ty: TypeSchema::String,- comment: "Toolkit slug to authorize (must be in the backend allowlist).",- required: true,- },- FieldSchema {- name: "extra_params",- ty: TypeSchema::Json,- comment: "Optional JSON object of additional auth fields forwarded to Composio \- (e.g. {\"waba_id\": \"...\") for toolkits that require them). \- The core may also add toolkit-specific OAuth scope hints such as \- Gmail's oauth_scopes value. Reserved keys (toolkit, toolkit_version, \- auth, client_id) are rejected.",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "connectUrl",- ty: TypeSchema::String,- comment: "Composio-hosted OAuth URL to open in a browser.",- required: true,- },- FieldSchema {- name: "connectionId",- ty: TypeSchema::String,- comment: "New Composio connection id created by this authorize call.",- required: true,- },- ],- },- "delete_connection" => ControllerSchema {- namespace: "composio",- function: "delete_connection",- description: "Delete a Composio connection and optionally remove source-scoped memory.",- inputs: vec![- FieldSchema {- name: "connection_id",- ty: TypeSchema::String,- comment: "Identifier of the connection to delete.",- required: true,- },- FieldSchema {- name: "clear_memory",- ty: TypeSchema::Bool,- comment: "When true, delete memory chunks ingested from this connection.",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "deleted",- ty: TypeSchema::Bool,- comment: "True when the backend confirmed the deletion.",- required: true,- },- FieldSchema {- name: "memory_chunks_deleted",- ty: TypeSchema::U64,- comment: "Number of memory chunks deleted for this connection.",- required: true,- },- ],- },- "list_tools" => ControllerSchema {- namespace: "composio",- function: "list_tools",- description:- "List OpenAI-function-calling tool schemas for one or more Composio toolkits.",- inputs: vec![- FieldSchema {- name: "toolkits",- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(- TypeSchema::String,- )))),- comment: "Optional list of toolkit slugs to filter by. Omit to get all.",- required: false,- },- FieldSchema {- name: "tags",- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(- TypeSchema::String,- )))),- comment: "Optional Composio action tags to filter by (OR semantics — \- multiple tags broaden the result). Case-insensitive.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "tools",- ty: TypeSchema::Json,- comment: "Array of OpenAI function-calling tool schemas.",- required: true,- }],- },- "execute" => ControllerSchema {- namespace: "composio",- function: "execute",- description: "Execute a Composio action (tool slug) against a connected account.",- inputs: vec![- FieldSchema {- name: "tool",- ty: TypeSchema::String,- comment: "Composio action slug, e.g. GMAIL_SEND_EMAIL.",- required: true,- },- FieldSchema {- name: "arguments",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment: "Tool-specific arguments conforming to the tool's JSON schema.",- required: false,- },- FieldSchema {- name: "connection_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Optional Composio connection id to target a specific account when multiple are connected for the same toolkit. Omit to use the default (oldest active).",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Execution envelope: { data, successful, error?, costUsd }.",- required: true,- }],- },- "list_github_repos" => ControllerSchema {- namespace: "composio",- function: "list_github_repos",- description:- "List repositories available through the caller's authorized GitHub Composio connection.",- inputs: vec![FieldSchema {- name: "connection_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment:- "Optional GitHub connection id. If omitted, backend picks the first active GitHub connection.",- required: false,- }],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Payload: { connectionId, repositories:[{ owner, repo, fullName, ... }] }.",- required: true,- }],- },- "create_trigger" => ControllerSchema {- namespace: "composio",- function: "create_trigger",- description:- "Create a Composio trigger instance for a connected account. For GitHub triggers, pass owner/repo in trigger_config.",- inputs: vec![- FieldSchema {- name: "slug",- ty: TypeSchema::String,- comment: "Trigger slug, e.g. GITHUB_PULL_REQUEST_EVENT.",- required: true,- },- FieldSchema {- name: "connection_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Optional connected account id. Backend resolves from slug toolkit when omitted.",- required: false,- },- FieldSchema {- name: "trigger_config",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment:- "Trigger config object. For GitHub, include owner/repo or repoFullName.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Payload: { triggerId, status? }.",- required: true,- }],- },- "get_user_profile" => ControllerSchema {- namespace: "composio",- function: "get_user_profile",- description:- "Fetch a normalized user profile for a Composio connection by dispatching to \- the toolkit's native provider implementation.",- inputs: vec![FieldSchema {- name: "connection_id",- ty: TypeSchema::String,- comment: "Composio connection id (from list_connections / authorize).",- required: true,- }],- outputs: vec![FieldSchema {- name: "profile",- ty: TypeSchema::Json,- comment: "Normalized profile: { toolkit, connectionId, displayName?, email?, \- username?, avatarUrl?, extras }.",- required: true,- }],- },- "refresh_all_identities" => ControllerSchema {- namespace: "composio",- function: "refresh_all_identities",- description:- "Re-fetch user profile for every active Composio connection and persist as \- IdentityKind-tagged rows in user_profile (#1365). Best-effort per connection \- — failures don't abort the others.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "report",- ty: TypeSchema::Json,- comment: "{ refreshed, failed, skippedNoProvider, skippedInactive, \- rowsWritten } — aggregate counts; per-connection trail in envelope \- messages.",- required: true,- }],- },- "sync" => ControllerSchema {- namespace: "composio",- function: "sync",- description:- "Run a sync pass for a Composio connection by dispatching to the toolkit's \- native provider implementation. Persists results into the memory layer.",- inputs: vec![- FieldSchema {- name: "connection_id",- ty: TypeSchema::String,- comment: "Composio connection id (from list_connections / authorize).",- required: true,- },- FieldSchema {- name: "reason",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment:- "Optional reason: 'manual' (default), 'periodic', 'connection_created'.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "outcome",- ty: TypeSchema::Json,- comment: "SyncOutcome: { toolkit, connectionId, reason, itemsIngested, \- startedAtMs, finishedAtMs, summary, details }.",- required: true,- }],- },- "list_trigger_history" => ControllerSchema {- namespace: "composio",- function: "list_trigger_history",- description:- "List recent ComposeIO trigger events archived by the core and report the daily JSONL archive paths.",- inputs: vec![FieldSchema {- name: "limit",- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),- comment: "Maximum number of archived trigger events to return.",- required: false,- }],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Trigger history payload: { archive_dir, current_day_file, entries }.",- required: true,- }],- },- "get_user_scopes" => ControllerSchema {- namespace: "composio",- function: "get_user_scopes",- description:- "Read the per-toolkit user scope preference (read/write/admin) used to gate \- composio_execute. Defaults to {read:true, write:true, admin:false} when no \- pref is stored.",- inputs: vec![FieldSchema {- name: "toolkit",- ty: TypeSchema::String,- comment: "Toolkit slug, e.g. 'gmail' or 'notion'.",- required: true,- }],- outputs: vec![FieldSchema {- name: "pref",- ty: TypeSchema::Json,- comment: "Scope pref: { read: bool, write: bool, admin: bool }.",- required: true,- }],- },- "set_user_scopes" => ControllerSchema {- namespace: "composio",- function: "set_user_scopes",- description:- "Persist a per-toolkit user scope preference. The agent will only be able to \- invoke composio actions whose classified scope is enabled here.",- inputs: vec![- FieldSchema {- name: "toolkit",- ty: TypeSchema::String,- comment: "Toolkit slug, e.g. 'gmail' or 'notion'.",- required: true,- },- FieldSchema {- name: "read",- ty: TypeSchema::Bool,- comment: "Allow read-classified actions (GET / FETCH / LIST / SEARCH).",- required: true,- },- FieldSchema {- name: "write",- ty: TypeSchema::Bool,- comment: "Allow write-classified actions (SEND / CREATE / UPDATE).",- required: true,- },- FieldSchema {- name: "admin",- ty: TypeSchema::Bool,- comment: "Allow admin-classified actions (DELETE / TRASH / SHARE).",- required: true,- },- ],- outputs: vec![FieldSchema {- name: "pref",- ty: TypeSchema::Json,- comment: "Stored scope pref: { read, write, admin }.",- required: true,- }],- },- "list_available_triggers" => ControllerSchema {- namespace: "composio",- function: "list_available_triggers",- description:- "List the catalog of triggers the caller can enable for a toolkit. \- For GitHub, pass `connection_id` to fan out into per-repo entries.",- inputs: vec![- FieldSchema {- name: "toolkit",- ty: TypeSchema::String,- comment: "Toolkit slug, e.g. 'gmail' or 'github'.",- required: true,- },- FieldSchema {- name: "connection_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment:- "Optional connection id. Optional for most toolkits; pass when \- requesting GitHub per-repo catalog entries.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "triggers",- ty: TypeSchema::Json,- comment:- "Array of {slug, scope, defaultConfig?, requiredConfigKeys?, repo?}.",- required: true,- }],- },- "list_triggers" => ControllerSchema {- namespace: "composio",- function: "list_triggers",- description: "List the user's currently enabled Composio triggers.",- inputs: vec![FieldSchema {- name: "toolkit",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Optional toolkit slug to filter by.",- required: false,- }],- outputs: vec![FieldSchema {- name: "triggers",- ty: TypeSchema::Json,- comment:- "Array of {id, slug, toolkit, connectionId, triggerConfig?, state?}.",- required: true,- }],- },- "enable_trigger" => ControllerSchema {- namespace: "composio",- function: "enable_trigger",- description:- "Enable a single Composio trigger on a connection the caller owns.",- inputs: vec![- FieldSchema {- name: "connection_id",- ty: TypeSchema::String,- comment: "Connection id to attach the trigger to.",- required: true,- },- FieldSchema {- name: "slug",- ty: TypeSchema::String,- comment: "Trigger slug, e.g. 'GMAIL_NEW_GMAIL_MESSAGE'.",- required: true,- },- FieldSchema {- name: "trigger_config",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment: "Optional trigger config object.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Payload: {triggerId, slug, connectionId}.",- required: true,- }],- },- "disable_trigger" => ControllerSchema {- namespace: "composio",- function: "disable_trigger",- description: "Disable (delete) a Composio trigger owned by the caller.",- inputs: vec![FieldSchema {- name: "trigger_id",- ty: TypeSchema::String,- comment: "Identifier of the trigger to delete.",- required: true,- }],- outputs: vec![FieldSchema {- name: "deleted",- ty: TypeSchema::Bool,- comment: "True when the backend confirmed deletion.",- required: true,- }],- },- "get_mode" => ControllerSchema {- namespace: "composio",- function: "get_mode",- description:- "Read the current Composio routing mode and whether a direct-mode API key is stored. \- Never returns the key itself.",- inputs: vec![],- outputs: vec![- FieldSchema {- name: "mode",- ty: TypeSchema::String,- comment: "Current mode: 'backend' (default) or 'direct'.",- required: true,- },- FieldSchema {- name: "api_key_set",- ty: TypeSchema::Bool,- comment: "True if a direct-mode Composio API key is in the encrypted keychain.",- required: true,- },- ],- },- "set_api_key" => ControllerSchema {- namespace: "composio",- function: "set_api_key",- description:- "Persist a user-provided Composio API key for direct mode in the encrypted \- keychain. Optionally flip composio.mode to 'direct' atomically. The key is \- NEVER logged or returned — only its length is recorded in tracing.",- inputs: vec![- FieldSchema {- name: "api_key",- ty: TypeSchema::String,- comment: "The Composio API key from https://app.composio.dev/api-keys.",- required: true,- },- FieldSchema {- name: "activate_direct",- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),- comment: "When true, also set composio.mode = 'direct'. Default false.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "{ stored: bool, mode: string } — current mode after the operation.",- required: true,- }],- },- "clear_api_key" => ControllerSchema {- namespace: "composio",- function: "clear_api_key",- description:- "Remove the stored direct-mode Composio API key and reset composio.mode \- back to 'backend'.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "{ cleared: bool, mode: 'backend' }.",- required: true,- }],- },- _other => ControllerSchema {- namespace: "composio",- function: "unknown",- description: "Unknown composio controller function.",- inputs: vec![FieldSchema {- name: "function",- ty: TypeSchema::String,- comment: "Unknown function requested for schema lookup.",- required: true,- }],- outputs: vec![FieldSchema {- name: "error",- ty: TypeSchema::String,- comment: "Lookup error details.",- required: true,- }],- },- }-}--// ── Handlers ────────────────────────────────────────────────────────--fn handle_list_toolkits(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async {- let config = config_rpc::load_config_with_timeout().await?;- to_json(super::ops::composio_list_toolkits(&config).await?)- })-}--fn handle_list_capabilities(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async {- let config = config_rpc::load_config_with_timeout().await?;- to_json(super::ops::composio_list_capabilities(&config).await?)- })-}--fn handle_list_agent_ready_toolkits(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async { to_json(super::ops::composio_list_agent_ready_toolkits().await?) })-}--fn handle_list_connections(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async {- let config = config_rpc::load_config_with_timeout().await?;- to_json(super::ops::composio_list_connections(&config).await?)- })-}--fn handle_authorize(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let toolkit = read_required_non_empty(¶ms, "toolkit")?;- let extra_params = params.get("extra_params").cloned();- to_json(super::ops::composio_authorize(&config, &toolkit, extra_params).await?)- })-}--fn handle_delete_connection(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let connection_id = read_required_non_empty(¶ms, "connection_id")?;- let clear_memory = read_optional::<bool>(¶ms, "clear_memory")?.unwrap_or(false);- to_json(- super::ops::composio_delete_connection(&config, &connection_id, clear_memory).await?,- )- })-}--fn handle_list_tools(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let toolkits = read_optional::<Vec<String>>(¶ms, "toolkits")?;- let tags = read_optional::<Vec<String>>(¶ms, "tags")?;- to_json(super::ops::composio_list_tools(&config, toolkits, tags).await?)- })-}--fn handle_execute(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let tool = read_required_non_empty(¶ms, "tool")?;- let arguments = read_optional::<Value>(¶ms, "arguments")?;- let connection_id = read_optional::<String>(¶ms, "connection_id")?;- to_json(- super::ops::composio_execute(&config, &tool, arguments, connection_id.as_deref())- .await?,- )- })-}--fn handle_list_github_repos(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let payload: ListGithubReposParams = serde_json::from_value(Value::Object(params))- .map_err(|e| format!("invalid params: {e}"))?;- to_json(super::ops::composio_list_github_repos(&config, payload.connection_id).await?)- })-}--fn handle_create_trigger(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let payload: CreateTriggerParams = serde_json::from_value(Value::Object(params))- .map_err(|e| format!("invalid params: {e}"))?;- let slug = payload.slug.trim();- if slug.is_empty() {- return Err("invalid params: 'slug' must not be empty".to_string());- }- to_json(- super::ops::composio_create_trigger(- &config,- slug,- payload.connection_id,- payload.trigger_config,- )- .await?,- )- })-}--fn handle_list_trigger_history(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let payload: TriggerHistoryParams = serde_json::from_value(Value::Object(params))- .map_err(|e| format!("invalid params: {e}"))?;- to_json(super::ops::composio_list_trigger_history(&config, payload.limit).await?)- })-}--fn handle_get_user_profile(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let connection_id = read_required_non_empty(¶ms, "connection_id")?;- to_json(super::ops::composio_get_user_profile(&config, &connection_id).await?)- })-}diff --git a/crates/openhuman-core/src/integrations/composio/schemas_part_03.rs b/crates/openhuman-core/src/integrations/composio/schemas_part_03.rsdeleted file mode 100644index 2d09d779d4..0000000000--- a/crates/openhuman-core/src/integrations/composio/schemas_part_03.rs+++ /dev/null@@ -1,242 +0,0 @@--fn handle_refresh_all_identities(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- to_json(super::ops::composio_refresh_all_identities(&config).await?)- })-}--fn handle_sync(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let connection_id = read_required_non_empty(¶ms, "connection_id")?;- let reason = read_optional::<String>(¶ms, "reason")?;- to_json(super::ops::composio_sync(&config, &connection_id, reason).await?)- })-}--fn handle_get_user_scopes(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let toolkit = match read_required_non_empty(¶ms, "toolkit") {- Ok(v) => v,- Err(e) => {- tracing::warn!(- method = "composio.get_user_scopes",- error = %e,- "[composio:scopes] missing required `toolkit` param"- );- return Err(e);- }- };- tracing::debug!(- method = "composio.get_user_scopes",- toolkit = %toolkit,- "[composio:scopes] handler entry"- );- // Reads through the bound memory driver's `Graph` family, not through- // the engine's `load_or_default` (which resolved the in-process client- // itself — openhuman#5560 deleted that client). The read still fails- // OPEN onto the default pref for every failure mode, deliberately; see- // `ops::user_scopes`.- //- // The config load is `?`-free for the same reason: this handler has- // never had a failing path, and turning "settings file momentarily- // unreadable" into an RPC error would make the scopes panel fail where- // it used to render the defaults.- let pref = match config_rpc::load_config_with_timeout().await {- Ok(config) => super::ops::load_user_scope_pref(&config, &toolkit).await,- Err(error) => {- tracing::warn!(- method = "composio.get_user_scopes",- toolkit = %toolkit,- %error,- "[composio:scopes] config load failed, using default pref (read+write)"- );- super::providers::UserScopePref::default()- }- };- tracing::debug!(- method = "composio.get_user_scopes",- toolkit = %toolkit,- read = pref.read,- write = pref.write,- admin = pref.admin,- "[composio:scopes] handler exit"- );- to_json(crate::rpc::RpcOutcome::new(pref, vec![]))- })-}--fn handle_set_user_scopes(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let toolkit = match read_required_non_empty(¶ms, "toolkit") {- Ok(v) => v,- Err(e) => {- tracing::warn!(- method = "composio.set_user_scopes",- error = %e,- "[composio:scopes] missing required `toolkit` param"- );- return Err(e);- }- };- let read: bool = read_required(¶ms, "read")?;- let write: bool = read_required(¶ms, "write")?;- let admin: bool = read_required(¶ms, "admin")?;- let pref = super::providers::UserScopePref { read, write, admin };- tracing::debug!(- method = "composio.set_user_scopes",- toolkit = %toolkit,- read = pref.read,- write = pref.write,- admin = pref.admin,- "[composio:scopes] handler entry"- );- // Writes through the bound memory driver's `Graph` family. This half- // fails CLOSED, as it did before: the old code refused with "memory- // client not initialised" rather than reporting a save it had not- // done, and `ops::user_scopes::save` refuses on the same three- // grounds (no driver, no `Graph` family, backend write failure).- let config = config_rpc::load_config_with_timeout().await?;- if let Err(e) = super::ops::save_user_scope_pref(&config, &toolkit, pref).await {- tracing::error!(- method = "composio.set_user_scopes",- toolkit = %toolkit,- error = %e,- "[composio:scopes] save failed"- );- return Err(e);- }- tracing::debug!(- method = "composio.set_user_scopes",- toolkit = %toolkit,- read = pref.read,- write = pref.write,- admin = pref.admin,- "[composio:scopes] handler exit"- );- to_json(crate::rpc::RpcOutcome::new(pref, vec![]))- })-}--fn handle_list_available_triggers(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let payload: ListAvailableTriggersParams = serde_json::from_value(Value::Object(params))- .map_err(|e| format!("invalid params: {e}"))?;- let toolkit = payload.toolkit.trim();- if toolkit.is_empty() {- return Err("invalid params: 'toolkit' must not be empty".to_string());- }- to_json(- super::ops::composio_list_available_triggers(&config, toolkit, payload.connection_id)- .await?,- )- })-}--fn handle_list_triggers(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let payload: ListTriggersParams = serde_json::from_value(Value::Object(params))- .map_err(|e| format!("invalid params: {e}"))?;- to_json(super::ops::composio_list_triggers(&config, payload.toolkit).await?)- })-}--fn handle_enable_trigger(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let payload: EnableTriggerParams = serde_json::from_value(Value::Object(params))- .map_err(|e| format!("invalid params: {e}"))?;- let connection_id = payload.connection_id.trim();- let slug = payload.slug.trim();- if connection_id.is_empty() {- return Err("invalid params: 'connection_id' must not be empty".to_string());- }- if slug.is_empty() {- return Err("invalid params: 'slug' must not be empty".to_string());- }- to_json(- super::ops::composio_enable_trigger(- &config,- connection_id,- slug,- payload.trigger_config,- )- .await?,- )- })-}--fn handle_disable_trigger(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let trigger_id = read_required_non_empty(¶ms, "trigger_id")?;- to_json(super::ops::composio_disable_trigger(&config, &trigger_id).await?)- })-}--fn handle_get_mode(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- tracing::debug!("[composio-direct] rpc get_mode entry");- let config = config_rpc::load_config_with_timeout().await?;- to_json(super::ops::composio_get_mode(&config).await?)- })-}--fn handle_set_api_key(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- tracing::debug!("[composio-direct] rpc set_api_key entry");- let config = config_rpc::load_config_with_timeout().await?;- let api_key = read_required_non_empty(¶ms, "api_key")?;- let activate_direct = read_optional::<bool>(¶ms, "activate_direct")?.unwrap_or(false);- to_json(super::ops::composio_set_api_key(&config, &api_key, activate_direct).await?)- })-}--fn handle_clear_api_key(_params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- tracing::debug!("[composio-direct] rpc clear_api_key entry");- let config = config_rpc::load_config_with_timeout().await?;- to_json(super::ops::composio_clear_api_key(&config).await?)- })-}--// ── Param helpers ───────────────────────────────────────────────────--fn read_required<T: DeserializeOwned>(params: &Map<String, Value>, key: &str) -> Result<T, String> {- let value = params- .get(key)- .cloned()- .ok_or_else(|| format!("missing required param '{key}'"))?;- serde_json::from_value(value).map_err(|e| format!("invalid '{key}': {e}"))-}--/// Read a required `String` parameter and reject blank / whitespace-only-/// input at the RPC boundary instead of letting it reach the backend.-/// Returns the trimmed value.-fn read_required_non_empty(params: &Map<String, Value>, key: &str) -> Result<String, String> {- let raw = read_required::<String>(params, key)?;- let trimmed = raw.trim();- if trimmed.is_empty() {- return Err(format!("'{key}' must not be empty"));- }- Ok(trimmed.to_string())-}--fn read_optional<T: DeserializeOwned>(- params: &Map<String, Value>,- key: &str,-) -> Result<Option<T>, String> {- match params.get(key) {- None | Some(Value::Null) => Ok(None),- Some(value) => serde_json::from_value(value.clone())- .map(Some)- .map_err(|e| format!("invalid '{key}': {e}")),- }-}--fn to_json<T: serde::Serialize>(outcome: RpcOutcome<T>) -> Result<Value, String> {- outcome.into_cli_compatible_json()-}diff --git a/crates/openhuman-core/src/voice/server/types.rs b/crates/openhuman-core/src/voice/server/types.rsnew file mode 100644index 0000000000..2507b3eead--- /dev/null+++ b/crates/openhuman-core/src/voice/server/types.rs@@ -0,0 +1,72 @@+//! Wire and config types for the voice server: run state, status snapshot,+//! and the tunables that shape a recording → transcription pass.++use crate::voice::hotkey::ActivationMode;++/// Running state of the voice server.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ServerState {+ /// Server is not running.+ Stopped,+ /// Server is running and idle, waiting for hotkey.+ Idle,+ /// Actively recording audio.+ Recording,+ /// Transcribing recorded audio.+ Transcribing,+}++/// Status snapshot of the voice server.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct VoiceServerStatus {+ pub state: ServerState,+ pub hotkey: String,+ pub activation_mode: ActivationMode,+ pub transcription_count: u64,+ pub last_error: Option<String>,+}++/// Default silence threshold (RMS energy). Recordings with peak RMS below+/// this are considered silent and skipped. Matches OpenWhispr's 0.002 default.+pub(super) const DEFAULT_SILENCE_THRESHOLD: f32 = 0.002;++/// Maximum number of recent transcriptions to keep as context for the STT engine's+/// initial_prompt, improving continuity across consecutive recordings.+pub(super) const MAX_RECENT_TRANSCRIPTS: usize = 5;++/// Maximum character length of the combined initial prompt (dictionary ++/// recent transcripts). The prompt token budget is limited.+pub(super) const MAX_INITIAL_PROMPT_CHARS: usize = 500;++/// Configuration for the voice server.+#[derive(Debug, Clone)]+pub struct VoiceServerConfig {+ pub hotkey: String,+ pub activation_mode: ActivationMode,+ /// Skip LLM post-processing on transcriptions.+ pub skip_cleanup: bool,+ /// Optional conversation context for better transcription accuracy.+ pub context: Option<String>,+ /// Minimum recording duration in seconds. Shorter recordings are discarded.+ pub min_duration_secs: f32,+ /// RMS energy threshold for silence detection. Recordings with peak+ /// energy below this are treated as silence and skipped.+ pub silence_threshold: f32,+ /// Custom vocabulary words to bias the STT engine toward (passed as initial_prompt).+ pub custom_dictionary: Vec<String>,+}++impl Default for VoiceServerConfig {+ fn default() -> Self {+ Self {+ hotkey: "Fn".to_string(),+ activation_mode: ActivationMode::Push,+ skip_cleanup: false,+ context: None,+ min_duration_secs: 0.3,+ silence_threshold: DEFAULT_SILENCE_THRESHOLD,+ custom_dictionary: Vec::new(),+ }+ }+}diff --git a/crates/openhuman-embed/src/call.rs b/crates/openhuman-embed/src/call.rsindex a3b3a2210a..57a1bcd651 100644--- a/crates/openhuman-embed/src/call.rs+++ b/crates/openhuman-embed/src/call.rs@@ -107,58 +107,5 @@ fn unwrap_outcome_envelope(value: serde_json::Value) -> serde_json::Value {}#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn unwraps_a_logged_outcome() {- let wire = json!({- "result": { "browser_allow_all": true, "log_prompts": false },- "logs": ["runtime flags read"]- });- assert_eq!(- unwrap_outcome_envelope(wire),- json!({ "browser_allow_all": true, "log_prompts": false })- );- }-- #[test]- fn passes_through_an_unlogged_value() {- let wire = json!({ "browser_allow_all": true, "log_prompts": false });- assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);- }-- #[test]- fn passes_through_non_objects() {- assert_eq!(unwrap_outcome_envelope(json!(7)), json!(7));- assert_eq!(unwrap_outcome_envelope(json!(null)), json!(null));- assert_eq!(unwrap_outcome_envelope(json!([1, 2])), json!([1, 2]));- }-- #[test]- fn does_not_unwrap_a_domain_type_that_merely_has_a_result_field() {- // Three keys — not an envelope.- let wire = json!({ "result": "ok", "logs": ["a"], "extra": 1 });- assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);-- // `logs` is not an array of strings — not an envelope.- let wire = json!({ "result": "ok", "logs": 3 });- assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);-- let wire = json!({ "result": "ok", "logs": [{ "level": "info" }] });- assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);-- // Two keys but no `result` — not an envelope.- let wire = json!({ "value": "ok", "logs": ["a"] });- assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);- }-- #[test]- fn unwraps_an_empty_log_array_envelope() {- // Defensive: `into_cli_compatible_json` does not currently emit this- // (empty logs return the bare value), but the shape is unambiguous.- let wire = json!({ "result": { "a": 1 }, "logs": [] });- assert_eq!(unwrap_outcome_envelope(wire), json!({ "a": 1 }));- }-}+#[path = "call_tests.rs"]+mod tests;diff --git a/crates/openhuman-embed/src/call_tests.rs b/crates/openhuman-embed/src/call_tests.rsnew file mode 100644index 0000000000..72cce47887--- /dev/null+++ b/crates/openhuman-embed/src/call_tests.rs@@ -0,0 +1,53 @@+use super::*;+use serde_json::json;++#[test]+fn unwraps_a_logged_outcome() {+ let wire = json!({+ "result": { "browser_allow_all": true, "log_prompts": false },+ "logs": ["runtime flags read"]+ });+ assert_eq!(+ unwrap_outcome_envelope(wire),+ json!({ "browser_allow_all": true, "log_prompts": false })+ );+}++#[test]+fn passes_through_an_unlogged_value() {+ let wire = json!({ "browser_allow_all": true, "log_prompts": false });+ assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);+}++#[test]+fn passes_through_non_objects() {+ assert_eq!(unwrap_outcome_envelope(json!(7)), json!(7));+ assert_eq!(unwrap_outcome_envelope(json!(null)), json!(null));+ assert_eq!(unwrap_outcome_envelope(json!([1, 2])), json!([1, 2]));+}++#[test]+fn does_not_unwrap_a_domain_type_that_merely_has_a_result_field() {+ // Three keys — not an envelope.+ let wire = json!({ "result": "ok", "logs": ["a"], "extra": 1 });+ assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);++ // `logs` is not an array of strings — not an envelope.+ let wire = json!({ "result": "ok", "logs": 3 });+ assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);++ let wire = json!({ "result": "ok", "logs": [{ "level": "info" }] });+ assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);++ // Two keys but no `result` — not an envelope.+ let wire = json!({ "value": "ok", "logs": ["a"] });+ assert_eq!(unwrap_outcome_envelope(wire.clone()), wire);+}++#[test]+fn unwraps_an_empty_log_array_envelope() {+ // Defensive: `into_cli_compatible_json` does not currently emit this+ // (empty logs return the bare value), but the shape is unambiguous.+ let wire = json!({ "result": { "a": 1 }, "logs": [] });+ assert_eq!(unwrap_outcome_envelope(wire), json!({ "a": 1 }));+}diff --git a/crates/openhuman-embed/src/config.rs b/crates/openhuman-embed/src/config.rsindex 1cdfe84ce2..ef6b0da5d8 100644--- a/crates/openhuman-embed/src/config.rs+++ b/crates/openhuman-embed/src/config.rs@@ -58,38 +58,5 @@ impl Config<'_> {}#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn runtime_flags_decodes_the_core_wire_shape() {- // Exactly what `RuntimeFlagsOut` serializes to. If the core struct- // gains or renames a field, this fails and the facade type gets- // updated deliberately rather than drifting.- let wire = json!({ "browser_allow_all": true, "log_prompts": false });- let flags: RuntimeFlags = serde_json::from_value(wire).expect("decodes");- assert!(flags.browser_allow_all);- assert!(!flags.log_prompts);- }-- #[test]- fn runtime_flags_round_trips() {- let original = RuntimeFlags {- browser_allow_all: false,- log_prompts: true,- };- let encoded = serde_json::to_value(&original).expect("encodes");- let decoded: RuntimeFlags = serde_json::from_value(encoded).expect("decodes");- assert_eq!(decoded, original);- }-- #[test]- fn runtime_flags_rejects_a_missing_field() {- // No `#[serde(default)]`: a shape change must fail loudly at the- // facade boundary rather than silently defaulting to `false`, which- // would read as "the flag is off" instead of "we lost the field".- let wire = json!({ "browser_allow_all": true });- assert!(serde_json::from_value::<RuntimeFlags>(wire).is_err());- }-}+#[path = "config_tests.rs"]+mod tests;diff --git a/crates/openhuman-embed/src/config_tests.rs b/crates/openhuman-embed/src/config_tests.rsnew file mode 100644index 0000000000..7f7998b6a2--- /dev/null+++ b/crates/openhuman-embed/src/config_tests.rs@@ -0,0 +1,33 @@+use super::*;+use serde_json::json;++#[test]+fn runtime_flags_decodes_the_core_wire_shape() {+ // Exactly what `RuntimeFlagsOut` serializes to. If the core struct+ // gains or renames a field, this fails and the facade type gets+ // updated deliberately rather than drifting.+ let wire = json!({ "browser_allow_all": true, "log_prompts": false });+ let flags: RuntimeFlags = serde_json::from_value(wire).expect("decodes");+ assert!(flags.browser_allow_all);+ assert!(!flags.log_prompts);+}++#[test]+fn runtime_flags_round_trips() {+ let original = RuntimeFlags {+ browser_allow_all: false,+ log_prompts: true,+ };+ let encoded = serde_json::to_value(&original).expect("encodes");+ let decoded: RuntimeFlags = serde_json::from_value(encoded).expect("decodes");+ assert_eq!(decoded, original);+}++#[test]+fn runtime_flags_rejects_a_missing_field() {+ // No `#[serde(default)]`: a shape change must fail loudly at the+ // facade boundary rather than silently defaulting to `false`, which+ // would read as "the flag is off" instead of "we lost the field".+ let wire = json!({ "browser_allow_all": true });+ assert!(serde_json::from_value::<RuntimeFlags>(wire).is_err());+}diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rsindex ee80618c00..4c0886d0e1 100644--- a/crates/openhuman-embed/src/error.rs+++ b/crates/openhuman-embed/src/error.rs@@ -188,78 +188,5 @@ impl CoreError {}#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn structured_envelope_becomes_domain_error() {- let raw = StructuredRpcError {- message: "thread thread-9 not found".to_string(),- data: Some(json!({ "kind": "ThreadNotFound", "thread_id": "thread-9" })),- expected_user_state: true,- }- .encode();-- let err = CoreError::from_rpc_string("openhuman.threads_get", raw);-- assert!(matches!(err, CoreError::Domain { .. }));- assert_eq!(err.kind(), Some("ThreadNotFound"));- assert!(err.is_expected_user_state());- assert!(!err.is_unavailable());- assert_eq!(err.method(), "openhuman.threads_get");- }-- #[test]- fn unknown_method_becomes_unavailable_not_rpc() {- // This is the gated-domain path: DomainSet removes the controller, so- // dispatch reports unknown-method. Hosts must be able to tell this from- // a real failure or they render an error where they should hide a tab.- let raw = format!("{UNKNOWN_METHOD_PREFIX}openhuman.flows_list");- let err = CoreError::from_rpc_string("openhuman.flows_list", raw);-- assert!(err.is_unavailable(), "gated method must map to Unavailable");- assert!(!err.is_expected_user_state());- assert_eq!(err.kind(), None);- }-- #[test]- fn plain_string_becomes_rpc_error() {- let err = CoreError::from_rpc_string("openhuman.config_get_config", "disk on fire".into());-- assert!(matches!(err, CoreError::Rpc { .. }));- assert!(!err.is_unavailable());- assert!(!err.is_expected_user_state());- }-- #[test]- fn structured_envelope_wins_over_unknown_method_prefix() {- // A domain may legitimately produce a message that starts with the- // unknown-method prefix. The envelope is authoritative.- let raw = StructuredRpcError {- message: format!("{UNKNOWN_METHOD_PREFIX}some.thing"),- data: Some(json!({ "kind": "BadRequest" })),- expected_user_state: false,- }- .encode();-- let err = CoreError::from_rpc_string("openhuman.x_y", raw);-- assert!(matches!(err, CoreError::Domain { .. }));- assert!(!err.is_unavailable());- assert_eq!(err.kind(), Some("BadRequest"));- }-- #[test]- fn expected_user_state_defaults_false_when_absent_from_envelope() {- let raw = StructuredRpcError {- message: "nope".to_string(),- data: None,- expected_user_state: false,- }- .encode();-- let err = CoreError::from_rpc_string("openhuman.a_b", raw);- assert!(!err.is_expected_user_state());- }-}+#[path = "error_tests.rs"]+mod tests;diff --git a/crates/openhuman-embed/src/error_tests.rs b/crates/openhuman-embed/src/error_tests.rsnew file mode 100644index 0000000000..582220232b--- /dev/null+++ b/crates/openhuman-embed/src/error_tests.rs@@ -0,0 +1,73 @@+use super::*;+use serde_json::json;++#[test]+fn structured_envelope_becomes_domain_error() {+ let raw = StructuredRpcError {+ message: "thread thread-9 not found".to_string(),+ data: Some(json!({ "kind": "ThreadNotFound", "thread_id": "thread-9" })),+ expected_user_state: true,+ }+ .encode();++ let err = CoreError::from_rpc_string("openhuman.threads_get", raw);++ assert!(matches!(err, CoreError::Domain { .. }));+ assert_eq!(err.kind(), Some("ThreadNotFound"));+ assert!(err.is_expected_user_state());+ assert!(!err.is_unavailable());+ assert_eq!(err.method(), "openhuman.threads_get");+}++#[test]+fn unknown_method_becomes_unavailable_not_rpc() {+ // This is the gated-domain path: DomainSet removes the controller, so+ // dispatch reports unknown-method. Hosts must be able to tell this from+ // a real failure or they render an error where they should hide a tab.+ let raw = format!("{UNKNOWN_METHOD_PREFIX}openhuman.flows_list");+ let err = CoreError::from_rpc_string("openhuman.flows_list", raw);++ assert!(err.is_unavailable(), "gated method must map to Unavailable");+ assert!(!err.is_expected_user_state());+ assert_eq!(err.kind(), None);+}++#[test]+fn plain_string_becomes_rpc_error() {+ let err = CoreError::from_rpc_string("openhuman.config_get_config", "disk on fire".into());++ assert!(matches!(err, CoreError::Rpc { .. }));+ assert!(!err.is_unavailable());+ assert!(!err.is_expected_user_state());+}++#[test]+fn structured_envelope_wins_over_unknown_method_prefix() {+ // A domain may legitimately produce a message that starts with the+ // unknown-method prefix. The envelope is authoritative.+ let raw = StructuredRpcError {+ message: format!("{UNKNOWN_METHOD_PREFIX}some.thing"),+ data: Some(json!({ "kind": "BadRequest" })),+ expected_user_state: false,+ }+ .encode();++ let err = CoreError::from_rpc_string("openhuman.x_y", raw);++ assert!(matches!(err, CoreError::Domain { .. }));+ assert!(!err.is_unavailable());+ assert_eq!(err.kind(), Some("BadRequest"));+}++#[test]+fn expected_user_state_defaults_false_when_absent_from_envelope() {+ let raw = StructuredRpcError {+ message: "nope".to_string(),+ data: None,+ expected_user_state: false,+ }+ .encode();++ let err = CoreError::from_rpc_string("openhuman.a_b", raw);+ assert!(!err.is_expected_user_state());+}diff --git a/crates/openhuman-embed/src/medulla.rs b/crates/openhuman-embed/src/medulla.rsindex ce2041f8f3..83b3f60f65 100644--- a/crates/openhuman-embed/src/medulla.rs+++ b/crates/openhuman-embed/src/medulla.rs@@ -161,38 +161,5 @@ impl Medulla<'_> {}#[cfg(test)]-mod tests {- use openhuman_core::medulla::all_medulla_registered_controllers;-- /// Every method this facade dispatches must name a registered controller.- ///- /// The facade's method names are strings; a typo or a renamed controller- /// would otherwise surface as `CoreError::Unavailable` at runtime, which is- /// indistinguishable from a domain the host gated off on purpose. Pinning- /// them here turns that into a test failure.- #[test]- fn every_dispatched_method_is_registered() {- let registered: Vec<String> = all_medulla_registered_controllers()- .iter()- .map(|c| c.rpc_method_name())- .collect();-- for method in [- "openhuman.medulla_status",- "openhuman.medulla_list_sessions",- "openhuman.medulla_create_session",- "openhuman.medulla_get_session",- "openhuman.medulla_send_message",- "openhuman.medulla_abort",- "openhuman.medulla_list_messages",- "openhuman.medulla_list_events",- "openhuman.medulla_roster",- ] {- assert!(- registered.iter().any(|m| m == method),- "facade dispatches `{method}`, which no controller registers. \- Registered: {registered:?}"- );- }- }-}+#[path = "medulla_tests.rs"]+mod tests;diff --git a/crates/openhuman-embed/src/medulla_tests.rs b/crates/openhuman-embed/src/medulla_tests.rsnew file mode 100644index 0000000000..599a856009--- /dev/null+++ b/crates/openhuman-embed/src/medulla_tests.rs@@ -0,0 +1,33 @@+use openhuman_core::medulla::all_medulla_registered_controllers;++/// Every method this facade dispatches must name a registered controller.+///+/// The facade's method names are strings; a typo or a renamed controller+/// would otherwise surface as `CoreError::Unavailable` at runtime, which is+/// indistinguishable from a domain the host gated off on purpose. Pinning+/// them here turns that into a test failure.+#[test]+fn every_dispatched_method_is_registered() {+ let registered: Vec<String> = all_medulla_registered_controllers()+ .iter()+ .map(|c| c.rpc_method_name())+ .collect();++ for method in [+ "openhuman.medulla_status",+ "openhuman.medulla_list_sessions",+ "openhuman.medulla_create_session",+ "openhuman.medulla_get_session",+ "openhuman.medulla_send_message",+ "openhuman.medulla_abort",+ "openhuman.medulla_list_messages",+ "openhuman.medulla_list_events",+ "openhuman.medulla_roster",+ ] {+ assert!(+ registered.iter().any(|m| m == method),+ "facade dispatches `{method}`, which no controller registers. \+ Registered: {registered:?}"+ );+ }+}