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(security): cover approval gate subagent flows
Steven Enamakel89b3e90402b0
diff --git a/crates/openhuman-core/src/security/approval/gate_subagent_tests.rs b/crates/openhuman-core/src/security/approval/gate_subagent_tests.rsnew file mode 100644index 0000000000..025b2cca2c--- /dev/null+++ b/crates/openhuman-core/src/security/approval/gate_subagent_tests.rs@@ -0,0 +1,222 @@+//! Sub-agent approval parks: an async-delegated sub-agent's card is routed to+//! the parent chat thread and marked `detached` (so the client keeps it across+//! the parent turn's end), every sub-agent park uses the shorter+//! [`SUBAGENT_APPROVAL_TTL`], and an expiry tells the model nobody answered.+//!+//! Production evidence: every failed `media_generate_image` /+//! `media_generate_video` / `skill_registry_install` in `image_agent`,+//! `video_agent` and `skill_setup` ended at exactly 600s with "The approval+//! request expired before anyone responded" — the card was set while the+//! parent turn ran, cleared by its `chat_done`, and never shown again.++use super::*;++/// The origin an async sub-agent inherits: the parent's `WebChat` label.+fn async_subagent_origin(thread: &str) -> AgentTurnOrigin {+ AgentTurnOrigin::WebChat {+ thread_id: thread.into(),+ client_id: "client-sub".into(),+ request_id: Some("parent-turn".into()),+ }+}++async fn requested_event(+ rx: &mut tinybus::events::EventReceiver<crate::core::events::DomainEvent>,+ tool: &str,+) -> crate::core::events::DomainEvent {+ loop {+ match rx.recv().await {+ Some(ref ev @ crate::core::events::DomainEvent::ApprovalRequested { ref tool_name, .. })+ if tool_name == tool =>+ {+ return ev.clone()+ }+ Some(_) => continue,+ None => panic!("the bus closed before the expected event arrived"),+ }+ }+}++async fn wait_parked(gate: &ApprovalGate) -> PendingApproval {+ for _ in 0..200 {+ if let Some(row) = gate.list_pending().unwrap().into_iter().next() {+ return row;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ panic!("the call never parked");+}++fn window(row: &PendingApproval, before: chrono::DateTime<chrono::Utc>) -> chrono::Duration {+ row.expires_at.expect("a parked approval sets expires_at") - before+}++#[test]+fn the_subagent_clamp_shortens_a_default_park_and_never_extends_a_shorter_one() {+ assert_eq!(+ ApprovalGate::resolve_park_ttl(DEFAULT_APPROVAL_TTL, false, true),+ SUBAGENT_APPROVAL_TTL+ );+ assert!(SUBAGENT_APPROVAL_TTL < DEFAULT_APPROVAL_TTL);+ let short = Duration::from_secs(30);+ assert_eq!(ApprovalGate::resolve_park_ttl(short, false, true), short);+}++#[tokio::test]+async fn an_async_subagent_park_reaches_the_parent_thread_detached_with_a_short_window() {+ let _env = EnvVarGuard::locked_unset_async("OPENHUMAN_APPROVAL_TTL_SECS").await;+ crate::core::bus::init().await.expect("bus init");+ let mut events = crate::core::bus::BUS+ .get()+ .expect("event bus initialized above")+ .receiver();+ let (gate, _dir) = test_gate();+ let gate = Arc::new(gate);+ let tool = "media_generate_image_async_subagent_test";++ let before = chrono::Utc::now();+ let g = gate.clone();+ // Origin propagated, APPROVAL_CHAT_CONTEXT not — the state+ // `spawn_async_subagent` leaves its detached child in.+ let handle = tokio::spawn(async move {+ turn_origin::with_origin(+ async_subagent_origin("thread-parent"),+ g.intercept(tool, "generate an image", serde_json::json!({})),+ )+ .await+ });++ let event = requested_event(&mut events, tool).await;+ let crate::core::events::DomainEvent::ApprovalRequested {+ request_id,+ thread_id,+ client_id,+ detached,+ ..+ } = event+ else {+ unreachable!()+ };+ assert_eq!(thread_id.as_deref(), Some("thread-parent"), "routed to the parent thread");+ assert_eq!(client_id.as_deref(), Some("client-sub"));+ assert!(detached, "a park that can outlive its turn is marked detached");+ assert!(gate.request_is_detached(&request_id), "the replay path sees it too");++ let row = wait_parked(&gate).await;+ assert!(+ window(&row, before)+ <= chrono::Duration::from_std(SUBAGENT_APPROVAL_TTL).unwrap()+ + chrono::Duration::seconds(5),+ "a sub-agent park uses SUBAGENT_APPROVAL_TTL, got {}",+ window(&row, before)+ );++ decide_parked(&gate, &request_id, ApprovalDecision::ApproveOnce);+ assert!(matches!(handle.await.unwrap(), GateOutcome::Allow));+}++#[tokio::test]+async fn an_inline_chat_park_is_not_detached_and_keeps_the_full_window() {+ let _env = EnvVarGuard::locked_unset_async("OPENHUMAN_APPROVAL_TTL_SECS").await;+ crate::core::bus::init().await.expect("bus init");+ let mut events = crate::core::bus::BUS+ .get()+ .expect("event bus initialized above")+ .receiver();+ let (gate, _dir) = test_gate();+ let gate = Arc::new(gate);+ let tool = "shell_inline_chat_park_test";++ let before = chrono::Utc::now();+ let g = gate.clone();+ let handle = tokio::spawn(async move {+ turn_origin::with_origin(+ web_origin(),+ APPROVAL_CHAT_CONTEXT.scope(chat_ctx(), g.intercept(tool, "run", serde_json::json!({}))),+ )+ .await+ });++ let crate::core::events::DomainEvent::ApprovalRequested {+ request_id,+ detached,+ ..+ } = requested_event(&mut events, tool).await+ else {+ unreachable!()+ };+ assert!(!detached, "a park inside the chat turn ends with it");+ let row = wait_parked(&gate).await;+ assert!(+ window(&row, before) > chrono::Duration::from_std(SUBAGENT_APPROVAL_TTL).unwrap(),+ "the main chat keeps its full window, got {}",+ window(&row, before)+ );++ decide_parked(&gate, &request_id, ApprovalDecision::ApproveOnce);+ assert!(matches!(handle.await.unwrap(), GateOutcome::Allow));+}++#[tokio::test]+async fn an_inline_subagent_park_uses_the_short_window_without_being_detached() {+ let _env = EnvVarGuard::locked_unset_async("OPENHUMAN_APPROVAL_TTL_SECS").await;+ let (gate, _dir) = test_gate();+ let gate = Arc::new(gate);++ let before = chrono::Utc::now();+ let g = gate.clone();+ // A blocking sub-agent runs inline under the parent's chat context, one+ // spawn level down.+ let handle = tokio::spawn(async move {+ turn_origin::with_origin(+ web_origin(),+ APPROVAL_CHAT_CONTEXT.scope(+ chat_ctx(),+ crate::agent::harness::with_spawn_depth(+ 1,+ g.intercept("skill_registry_install", "install", serde_json::json!({})),+ ),+ ),+ )+ .await+ });++ let row = wait_parked(&gate).await;+ assert!(!gate.request_is_detached(&row.request_id));+ assert!(+ window(&row, before)+ <= chrono::Duration::from_std(SUBAGENT_APPROVAL_TTL).unwrap()+ + chrono::Duration::seconds(5),+ "got {}",+ window(&row, before)+ );+ decide_parked(&gate, &row.request_id, ApprovalDecision::ApproveOnce);+ assert!(matches!(handle.await.unwrap(), GateOutcome::Allow));+}++#[tokio::test]+async fn an_expired_park_tells_the_model_nobody_answered() {+ let (gate, _dir, env) = expiry_gate().await;+ let gate = Arc::new(gate);+ let g = gate.clone();+ let handle = tokio::spawn(async move {+ turn_origin::with_origin(+ async_subagent_origin("thread-expiry"),+ g.intercept("media_generate_video", "generate a clip", serde_json::json!({})),+ )+ .await+ });+ let _ = wait_parked(&gate).await;+ drop(env);+ let GateOutcome::Deny { reason } = handle.await.unwrap() else {+ panic!("an unanswered park is denied");+ };+ assert!(is_unanswered_approval_reason(&reason), "{reason}");+ assert!(reason.contains("ask again"), "{reason}");+ // The status classifier still reads it as an expired approval.+ assert_eq!(+ crate::tools::status::classify(&reason, false).class,+ crate::tools::status::ToolFailureClass::ApprovalExpired,+ "{reason}"+ );+}diff --git a/crates/openhuman-core/src/security/approval/gate_tests.rs b/crates/openhuman-core/src/security/approval/gate_tests.rsindex 3704352a6d..81107d4186 100644--- a/crates/openhuman-core/src/security/approval/gate_tests.rs+++ b/crates/openhuman-core/src/security/approval/gate_tests.rs@@ -206,6 +206,8 @@ mod core_flow_tests;mod forced_tests;#[path = "gate_origin_intercept_tests.rs"]mod origin_intercept_tests;+#[path = "gate_subagent_tests.rs"]+mod subagent_tests;#[path = "gate_triage_tests.rs"]mod triage_tests;#[path = "gate_ttl_and_triage_tests.rs"]