The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(cron): move expired-context callback test into its own module
Steven Enamakel8400d116fe31
diff --git a/crates/openhuman-core/src/cron/bus_host.rs b/crates/openhuman-core/src/cron/bus_host.rsindex 7c1b2e1b5c..dffeb096d4 100644--- a/crates/openhuman-core/src/cron/bus_host.rs+++ b/crates/openhuman-core/src/cron/bus_host.rs@@ -356,6 +356,10 @@ pub(crate) fn kind_refusal(binding: &Binding, job: &CronJob) -> Option<String> {#[path = "bus_host_tests.rs"]mod tests;+#[cfg(all(test, feature = "modules"))]+#[path = "bus_host_context_tests.rs"]+mod context_tests;+#[cfg(test)]#[path = "bus_host_trusted_system_tests.rs"]mod trusted_system_tests;diff --git a/crates/openhuman-core/src/cron/bus_host_context_tests.rs b/crates/openhuman-core/src/cron/bus_host_context_tests.rsnew file mode 100644index 0000000000..d05b403135--- /dev/null+++ b/crates/openhuman-core/src/cron/bus_host_context_tests.rs@@ -0,0 +1,71 @@+use super::tests::{config, flow_job};+use super::*;+use std::sync::atomic::{AtomicUsize, Ordering};+use tempfile::TempDir;++#[tokio::test]+async fn an_expired_bound_callback_fails_closed_under_another_ambient_context() {+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};++ let tmp = TempDir::new().unwrap();+ let config = config(&tmp);+ let expired = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(+ ContextOverlay::new(+ config.clone(),+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .session_agent(format!(+ "expired-callback-{}",+ uuid::Uuid::new_v4().simple()+ )),+ );+ let expired_weak = Arc::downgrade(&expired);+ let dispatch = DispatchCtx::new(Arc::clone(&expired));+ let security = Arc::new(SecurityPolicy::from_config(+ &config.autonomy,+ &config.workspace_dir,+ &config.action_dir,+ ));+ let binding = Binding::new(&dispatch, &config, security);+ let host = ScheduleHost {+ executor: Arc::new(HostExecutor::new(binding.clone())),+ binding,+ };+ drop(dispatch);+ drop(expired);+ assert!(+ expired_weak.upgrade().is_none(),+ "the bound context is truly expired before the callback"+ );++ let other = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(+ ContextOverlay::new(+ config.clone(),+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .session_agent("other-callback-scope"),+ );+ let name = format!("expired-callback-{}", uuid::Uuid::new_v4().simple());+ let calls = Arc::new(AtomicUsize::new(0));+ let handler_calls = Arc::clone(&calls);+ let _handler = crate::cron::system_job_handlers::register(+ &name,+ Arc::new(move |_| {+ handler_calls.fetch_add(1, Ordering::SeqCst);+ Box::pin(async { Ok(()) })+ }),+ );+ let job = flow_job(&config, &format!("system:{name}"));+ let result = CoreContext::scope(other, async {+ host.execute(job, "expired-context-run".to_string()).await+ })+ .await;+ assert!(result.is_err(), "an expired bound callback must be refused");+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 0,+ "the callback must not execute under the unrelated ambient context"+ );+}diff --git a/crates/openhuman-core/src/cron/bus_host_tests.rs b/crates/openhuman-core/src/cron/bus_host_tests.rsindex b8ae84bf5d..8c26fe0b35 100644--- a/crates/openhuman-core/src/cron/bus_host_tests.rs+++ b/crates/openhuman-core/src/cron/bus_host_tests.rs@@ -3,15 +3,15 @@ use super::*;// the contract's `ScheduleHost` interface, against the real (linked) module.use crate::cron::handlers::{- kind_handler, register_kind, JobKindHandler, JobOutcome, JobRunContext,+ JobKindHandler, JobOutcome, JobRunContext, kind_handler, register_kind,};use async_trait::async_trait;use std::sync::atomic::{AtomicUsize, Ordering};use tempfile::TempDir;use tinyflows_bus::schedule::types::{DeliveryConfig, DeliveryStatus, Schedule};-use tinyflows_bus::schedule::{callbacks, DeliveryProjection, CALLBACK_INTERFACE};+use tinyflows_bus::schedule::{CALLBACK_INTERFACE, DeliveryProjection, callbacks};-fn config(tmp: &TempDir) -> Config {+pub(super) fn config(tmp: &TempDir) -> Config {let config = Config {workspace_dir: tmp.path().join("workspace"),action_dir: tmp.path().join("workspace"),@@ -60,7 +60,7 @@ fn shell_job(config: &Config, command: &str) -> CronJob {.unwrap()}-fn flow_job(config: &Config, flow_id: &str) -> CronJob {+pub(super) fn flow_job(config: &Config, flow_id: &str) -> CronJob {crate::cron::add_flow_schedule_job(config,flow_id,@@ -123,73 +123,6 @@ async fn execute_runs_the_registered_handler_and_reports_a_retryable_failure() {assert_eq!(calls.load(Ordering::SeqCst), 1);}-#[tokio::test]-async fn an_expired_bound_callback_fails_closed_under_another_ambient_context() {- use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};-- let tmp = TempDir::new().unwrap();- let config = config(&tmp);- let expired = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(- ContextOverlay::new(- config.clone(),- DomainSet::full(),- crate::tools::toolpacks::ToolGroups::none(),- )- .session_agent(format!(- "expired-callback-{}",- uuid::Uuid::new_v4().simple()- )),- );- let expired_weak = Arc::downgrade(&expired);- let dispatch = DispatchCtx::new(Arc::clone(&expired));- let security = Arc::new(SecurityPolicy::from_config(- &config.autonomy,- &config.workspace_dir,- &config.action_dir,- ));- let binding = Binding::new(&dispatch, &config, security);- let host = ScheduleHost {- executor: Arc::new(HostExecutor::new(binding.clone())),- binding,- };- drop(dispatch);- drop(expired);- assert!(- expired_weak.upgrade().is_none(),- "the bound context is truly expired before the callback"- );-- let other = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(- ContextOverlay::new(- config.clone(),- DomainSet::full(),- crate::tools::toolpacks::ToolGroups::none(),- )- .session_agent("other-callback-scope"),- );- let name = format!("expired-callback-{}", uuid::Uuid::new_v4().simple());- let calls = Arc::new(AtomicUsize::new(0));- let handler_calls = Arc::clone(&calls);- let _handler = crate::cron::system_job_handlers::register(- &name,- Arc::new(move |_| {- handler_calls.fetch_add(1, Ordering::SeqCst);- Box::pin(async { Ok(()) })- }),- );- let job = flow_job(&config, &format!("system:{name}"));- let result = CoreContext::scope(other, async {- host.execute(job, "expired-context-run".to_string()).await- })- .await;- assert!(result.is_err(), "an expired bound callback must be refused");- assert_eq!(- calls.load(Ordering::SeqCst),- 0,- "the callback must not execute under the unrelated ambient context"- );-}-#[tokio::test]async fn a_permanent_handler_outcome_stops_the_retry_loop() {let tmp = TempDir::new().unwrap();diff --git a/crates/openhuman-core/src/cron/bus_host_trusted_system_tests.rs b/crates/openhuman-core/src/cron/bus_host_trusted_system_tests.rsindex 785af91181..ff8533c47d 100644--- a/crates/openhuman-core/src/cron/bus_host_trusted_system_tests.rs+++ b/crates/openhuman-core/src/cron/bus_host_trusted_system_tests.rs@@ -1,7 +1,7 @@use super::*;use std::sync::atomic::{AtomicUsize, Ordering};use tempfile::TempDir;-use tinyflows_bus::schedule::{callbacks, Attempt, CALLBACK_INTERFACE};+use tinyflows_bus::schedule::{Attempt, CALLBACK_INTERFACE, callbacks};fn config(tmp: &TempDir) -> Config {let config = Config {diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rsindex 8ef491a579..afc5495086 100644--- a/tests/json_rpc_e2e.rs+++ b/tests/json_rpc_e2e.rs@@ -19,17 +19,17 @@ use std::sync::{Arc, Mutex, OnceLock};use std::time::Duration;use axum::extract::State;-use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode, Uri};+use axum::http::{HeaderMap, StatusCode, Uri, header::AUTHORIZATION};use axum::routing::{get, post};use axum::{Json, Router};use futures_util::StreamExt;-use serde_json::{json, Value};+use serde_json::{Value, json};use sha2::{Digest, Sha256};use tempfile::tempdir;use tinyinference_llm::message::Message;use tinyinference_llm::model::ModelRequest;-use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};+use openhuman_core::core::auth::{CORE_TOKEN_ENV_VAR, init_rpc_token};use openhuman_core::platform::connectivity::rpc::pick_listen_port;use openhuman_rpc::server::build_core_http_router;@@ -1539,10 +1539,12 @@ async fn json_rpc_tokenjuice_detect_and_cache_stats() {).await;let stats_result = assert_no_jsonrpc_error(&stats, "tokenjuice_cache_stats");- assert!(stats_result- .get("entries")- .and_then(Value::as_u64)- .is_some());+ assert!(+ stats_result+ .get("entries")+ .and_then(Value::as_u64)+ .is_some()+ );assert!(stats_result.get("bytes").and_then(Value::as_u64).is_some());rpc_join.abort();@@ -1567,14 +1569,18 @@ async fn json_rpc_tokenjuice_settings_and_savings() {let settings = get_result.get("settings").expect("settings_get returns a settings object");- assert!(settings- .get("router_enabled")- .and_then(Value::as_bool)- .is_some());- assert!(settings- .get("ccr_min_tokens")- .and_then(Value::as_u64)- .is_some());+ assert!(+ settings+ .get("router_enabled")+ .and_then(Value::as_bool)+ .is_some()+ );+ assert!(+ settings+ .get("ccr_min_tokens")+ .and_then(Value::as_u64)+ .is_some()+ );// settings_update: flip the CCR token threshold and confirm it round-trips.let updated = post_json_rpc(@@ -1603,11 +1609,13 @@ async fn json_rpc_tokenjuice_settings_and_savings() {.await;let savings_result = assert_no_jsonrpc_error(&savings, "tokenjuice_savings_stats");assert!(savings_result.get("attributionModel").is_some());- assert!(savings_result- .get("total")- .and_then(|t| t.get("tokensSaved"))- .and_then(Value::as_u64)- .is_some());+ assert!(+ savings_result+ .get("total")+ .and_then(|t| t.get("tokensSaved"))+ .and_then(Value::as_u64)+ .is_some()+ );assert!(savings_result.get("cache").is_some());// savings_reset: zeroes the totals.@@ -1817,24 +1825,32 @@ async fn json_rpc_agent_registry_manages_defaults_and_custom_agents() {.iter().find(|definition| definition.get("id").and_then(Value::as_str) == Some("critic")).expect("safe agent library should include critic");- assert!(memory_agent- .get("display_name")- .and_then(Value::as_str)- .is_some());- assert!(memory_agent- .get("when_to_use")- .and_then(Value::as_str)- .is_some());+ assert!(+ memory_agent+ .get("display_name")+ .and_then(Value::as_str)+ .is_some()+ );+ assert!(+ memory_agent+ .get("when_to_use")+ .and_then(Value::as_str)+ .is_some()+ );assert!(memory_agent.get("system_prompt").is_none());assert!(memory_agent.get("tools").is_some());- assert!(memory_agent- .get("direct_tool_count")- .and_then(Value::as_u64)- .is_some());- assert!(memory_agent- .get("can_run_as_user_facing_worker")- .and_then(Value::as_bool)- .is_some());+ assert!(+ memory_agent+ .get("direct_tool_count")+ .and_then(Value::as_u64)+ .is_some()+ );+ assert!(+ memory_agent+ .get("can_run_as_user_facing_worker")+ .and_then(Value::as_bool)+ .is_some()+ );let missing = post_json_rpc(&rpc_base,@@ -2721,7 +2737,7 @@ async fn json_rpc_cron_manual_worker_survives_caller_cancel_on_published_tinyflocron::system_job_handlers,};use tinybus::EventHandler;- use tokio::sync::{mpsc, oneshot, Semaphore};+ use tokio::sync::{Semaphore, mpsc, oneshot};let _env_lock = json_rpc_e2e_env_lock_async().await;let tmp = tempdir().expect("tempdir");@@ -3072,7 +3088,9 @@ async fn json_rpc_cron_manual_worker_survives_caller_cancel_on_published_tinyflolet terminal_run = manual_history.as_array().and_then(|runs| runs.first())- .unwrap_or_else(|| panic!("the released worker committed terminal history: {manual_history}"));+ .unwrap_or_else(|| {+ panic!("the released worker committed terminal history: {manual_history}")+ });assert!(terminal_run["output"].as_str()@@ -3922,10 +3940,12 @@ async fn json_rpc_thread_working_dir_binds_before_the_first_message() {).await;let cleared = assert_no_jsonrpc_error(&cleared, "threads_update_working_dir clear");- assert!(cleared- .get("data")- .and_then(|d| d.get("actionDir"))- .is_none());+ assert!(+ cleared+ .get("data")+ .and_then(|d| d.get("actionDir"))+ .is_none()+ );// 3. A protected folder is refused.let ssh = home.join(".ssh");@@ -4140,8 +4160,7 @@ async fn json_rpc_thread_generate_title_falls_back_when_provider_path_is_unavailassert_ne!(generated_title, original_title);assert_eq!(- generated_title,- "summarize latest five",+ generated_title, "summarize latest five","fallback title should be the 3-word shape derived from the first user message (filler stripped), got: {generated_title}");@@ -4322,11 +4341,13 @@ async fn json_rpc_thread_turn_state_lifecycle() {).await;let missing_outer = assert_no_jsonrpc_error(&get_turn_missing, "turn_state_get_turn (absent)");- assert!(missing_outer- .get("data")- .and_then(|d| d.get("turnState"))- .map(|v| v.is_null())- .unwrap_or(true));+ assert!(+ missing_outer+ .get("data")+ .and_then(|d| d.get("turnState"))+ .map(|v| v.is_null())+ .unwrap_or(true)+ );// clear → cleared:truelet cleared = post_json_rpc(@@ -4354,11 +4375,13 @@ async fn json_rpc_thread_turn_state_lifecycle() {).await;let again_outer = assert_no_jsonrpc_error(&got_again, "turn_state_get (after clear)");- assert!(again_outer- .get("data")- .and_then(|d| d.get("turnState"))- .map(|v| v.is_null())- .unwrap_or(true));+ assert!(+ again_outer+ .get("data")+ .and_then(|d| d.get("turnState"))+ .map(|v| v.is_null())+ .unwrap_or(true)+ );api_join.abort();rpc_join.abort();@@ -7061,7 +7084,9 @@ async fn json_rpc_wallet_solana_prepare_execute_round_trips() {);assert_eq!(exec_result.get("transactionHash").and_then(Value::as_str),- Some("5xS9pXmqVz8R1nuRZTfsdsAxBdBFmtnAtuYbCsmK5DYzGn5vR4VqWGmiR5McLnYx8oFqLdo62q4qiUZpQyR4Hkn3"),+ Some(+ "5xS9pXmqVz8R1nuRZTfsdsAxBdBFmtnAtuYbCsmK5DYzGn5vR4VqWGmiR5McLnYx8oFqLdo62q4qiUZpQyR4Hkn3"+ ),);mock_join.abort();@@ -7919,12 +7944,14 @@ async fn json_rpc_local_ai_ollama_endpoint_normalizes_bind_address_and_clears()).await;let clear_result = assert_no_jsonrpc_error(&clear, "clear ollama base_url");- assert!(clear_result- .get("result")- .and_then(|value| value.get("config"))- .and_then(|config| config.get("local_ai"))- .and_then(|local_ai| local_ai.get("base_url"))- .is_none_or(Value::is_null));+ assert!(+ clear_result+ .get("result")+ .and_then(|value| value.get("config"))+ .and_then(|config| config.get("local_ai"))+ .and_then(|local_ai| local_ai.get("base_url"))+ .is_none_or(Value::is_null)+ );mock_join.abort();rpc_join.abort();@@ -8706,10 +8733,12 @@ async fn voice_live_settings_round_trip_over_json_rpc() {.await;let tested = assert_no_jsonrpc_error(&tested, "voice_live_test_provider");assert_eq!(tested["ok"], false);- assert!(tested["error"]- .as_str()- .unwrap_or_default()- .contains("not_configured"));+ assert!(+ tested["error"]+ .as_str()+ .unwrap_or_default()+ .contains("not_configured")+ );mock_join.abort();rpc_join.abort();@@ -10993,9 +11022,11 @@ async fn json_rpc_task_sources_crud_and_status() {.as_array().expect("list returns array").clone();- assert!(sources- .iter()- .any(|s| s.get("id").and_then(Value::as_str) == Some(id.as_str())));+ assert!(+ sources+ .iter()+ .any(|s| s.get("id").and_then(Value::as_str) == Some(id.as_str()))+ );// ── get roundtrips ───────────────────────────────────────────────let get = post_json_rpc(@@ -12097,9 +12128,11 @@ async fn json_rpc_flows_full_arc_discover_build_create_run_inner() {// only the approval needed for the real run_flow tool call below, so the// streaming builder exposes that tool without parking the deterministic// test completion for a human decision.- let mut approval_config = openhuman_core::config::Config::default();- approval_config.workspace_dir = openhuman_home.join("workspace");- approval_config.config_path = openhuman_home.join("config.toml");+ let mut approval_config = openhuman_core::config::Config {+ workspace_dir: openhuman_home.join("workspace"),+ config_path: openhuman_home.join("config.toml"),+ ..openhuman_core::config::Config::default()+ };approval_config.autonomy.auto_approvediff --git a/tests/support/scripted_stack.rs b/tests/support/scripted_stack.rsindex d5126d5470..0371c76ffd 100644--- a/tests/support/scripted_stack.rs+++ b/tests/support/scripted_stack.rs@@ -13,9 +13,9 @@use std::sync::{Mutex, MutexGuard};-use axum::http::HeaderMap;use axum::Json;-use serde_json::{json, Value};+use axum::http::HeaderMap;+use serde_json::{Value, json};/// Lock `m`, recovering the data when a panicking test poisoned it.pub fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {