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(orchestration): remove running subagent test modules
Steven Enamakel13241a74e9ec
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rsindex b616864e53..10cee76be0 100644--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tenant_tests.rs@@ -97,25 +97,6 @@ async fn one_profiles_stop_and_delete_never_reach_anothers_thread() {assert_eq!(resolved(&bob).as_deref(), Some(ws_b.path()));}-#[test]-fn a_saas_cancel_reaches_only_the_callers_workspace() {- use super::running_subagents::{caller_workspace_in, CallerWorkspace};- let ws = TestWorkspace::new();- let alice = profile("u-alice", ws.path());- assert!(matches!(- caller_workspace_in(false, None),- CallerWorkspace::All- ));- assert!(matches!(- caller_workspace_in(true, None),- CallerWorkspace::Nothing- ));- match caller_workspace_in(true, Some(&alice)) {- CallerWorkspace::Only(dir) => assert_eq!(dir, ws.path()),- _ => panic!("a scoped SaaS caller reaches its own workspace"),- }-}-/// The explicit context decides, with no ambient scope anywhere: two profiles/// recording and resolving the same thread id concurrently, across awaits and/// from spawned tasks, never see each other's state.diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_cancel_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_cancel_tests.rsdeleted file mode 100644index 73df54dc4e..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_cancel_tests.rs+++ /dev/null@@ -1,108 +0,0 @@-//! Cancelling and stopping registered sub-agents: by task, by thread, and all.--use super::*;--/// A finished run stays registered until the terminal sweep, so a late-/// "Cancel" still finds it. It must come back flagged, so the RPC does not-/// rewrite a completed session as "cancelled by user" — while a run paused on-/// the user is still a real cancel.-#[tokio::test]-async fn cancel_by_task_flags_a_run_that_already_finished() {- let _guard = test_guard_async().await;- let cases = [- (- "task-cbt-done",- DetachedSubagentStatus::Completed {- output: "ok".into(),- iterations: 6,- },- Some(FinishedOutcome::Completed),- ),- (- "task-cbt-failed",- DetachedSubagentStatus::Failed {- error: "boom".into(),- },- Some(FinishedOutcome::Failed),- ),- (- "task-cbt-paused",- DetachedSubagentStatus::AwaitingUser {- question: "which?".into(),- },- None,- ),- ];- for (task_id, status, finished) in cases {- let tx = register_test(task_id, "session-F", run_queue());- tx.send(status).expect("status channel open");- let meta = cancel_by_task(&cx(), task_id).expect("registered task is found");- assert_eq!(meta.already_finished, finished, "{task_id}");- }-}--#[tokio::test]-async fn cancel_all_clears_everything() {- let _guard = test_guard_async().await;- let rq = run_queue();- let _a = register_test_with_thread("task-all-1", "session-A", Some("thread-1"), rq.clone());- // Headless (no parent thread) — aborted, but contributes no thread id.- let _b = register_test_with_thread("task-all-2", "session-B", None, rq);-- let cancelled_threads = cancel_all(&cx());- assert!(- cancelled_threads.contains(&"thread-1".to_string()),- "cancel_all should report the parent thread of the cancelled sub-agent"- );- assert!(- !cancelled_threads.iter().any(|t| t.is_empty()),- "headless sub-agents must not contribute an id"- );-- // Registry is empty now.- assert!(cancel_all(&cx()).is_empty());-}--#[tokio::test]-async fn stop_for_thread_aborts_the_threads_running_children() {- let _guard = test_guard_async().await;- let rq = run_queue();- // A real detached child that would otherwise run forever — the shape the- // Stop button used to leave behind.- let child = tokio::spawn(std::future::pending::<()>());- let (_tx, rx) = status_channel();- register(- &cx(),- "task-stop-1".into(),- "researcher".into(),- "session-stop".into(),- None,- None,- test_workspace(),- Some("thread-stop".into()),- rq.clone(),- child.abort_handle(),- rx,- )- .expect("fixture registration admitted");- // Another thread's child must survive the stop.- let _other =- register_test_with_thread("task-stop-other", "session-stop", Some("thread-keep"), rq);-- let stopped = stop_for_thread(&cx(), "thread-stop");- assert_eq!(stopped, vec!["task-stop-1".to_string()]);-- let joined = tokio::time::timeout(Duration::from_secs(2), child)- .await- .expect("aborted child finishes promptly");- assert!(- joined.expect_err("child was aborted").is_cancelled(),- "stop must abort the detached child task"- );- assert!(- stop_for_thread(&cx(), "thread-stop").is_empty(),- "idempotent"- );-- prune("task-stop-other");-}diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_projection_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_projection_tests.rsdeleted file mode 100644index 0485416736..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_projection_tests.rs+++ /dev/null@@ -1,211 +0,0 @@-use super::*;-use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet, Mode};-use crate::tools::toolpacks::ToolGroups;-use tinyagents_orchestration::subagent::list_subagent_records;--const PARENT: &str = "projection-parent";--fn profile(name: &str, workspace: &std::path::Path) -> Arc<CoreContext> {- CoreContext::for_test(DomainSet::full(), None).derive_with(- ContextOverlay::new(- crate::config::Config {- workspace_dir: workspace.to_path_buf(),- ..crate::config::Config::default()- },- DomainSet::kernel(),- ToolGroups::none(),- )- .profile(name)- .session_agent("projection-agent"),- )-}--fn records(- ctx: &DispatchCtx,- workspace: &std::path::Path,-) -> Vec<tinyagents_tasks::OrchestrationTaskRecord> {- let store = super::super::resolve::scoped_task_store(ctx, workspace)- .expect("profile-scoped task store");- list_subagent_records(store.as_ref())-}--#[tokio::test]-async fn explicit_profile_projects_spawn_completion_and_cancel_without_ambient_scope() {- let name = "explicit_profile_projects_spawn_completion_and_cancel_without_ambient_scope";- let module = module_path!().split_once("::").expect("crate module").1;- let exact = format!("{module}::{name}");- if std::env::var("OPENHUMAN_SUBAGENT_PROJECTION_CHILD").as_deref() != Ok(exact.as_str()) {- let output = std::process::Command::new(std::env::current_exe().expect("test binary"))- .args(["--exact", &exact, "--nocapture", "--test-threads=1"])- .env("OPENHUMAN_SUBAGENT_PROJECTION_CHILD", &exact)- .output()- .expect("run isolated SaaS projection test");- assert!(- output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"),- "isolated test {exact} failed:\n{}\n{}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- return;- }-- crate::core::runtime::mode::lock_mode(Mode::Saas).expect("lock isolated SaaS mode");- assert!(- CoreContext::scoped().is_none(),- "test starts without ambient scope"- );- let _guard = test_guard_async().await;- let workspace = tempfile::tempdir().expect("workspace");- let alice = DispatchCtx::new(profile("projection-alice", workspace.path()));- let bob = DispatchCtx::new(profile("projection-bob", workspace.path()));- let alice_task = uuid::Uuid::new_v4().to_string();- let bob_task = uuid::Uuid::new_v4().to_string();-- let (alice_tx, alice_rx) = status_channel();- let (bob_tx, bob_rx) = status_channel();- register(- &alice,- alice_task.clone(),- "researcher".into(),- PARENT.into(),- None,- None,- workspace.path().to_path_buf(),- None,- run_queue(),- dummy_abort(),- alice_rx,- )- .expect("Alice registration");- CoreContext::sync_scope(alice.resolved().unwrap().clone(), || {- register(- &bob,- bob_task.clone(),- "researcher".into(),- PARENT.into(),- None,- None,- workspace.path().to_path_buf(),- None,- run_queue(),- dummy_abort(),- bob_rx,- )- })- .expect("Bob registration under foreign ambient profile");-- let alice_spawned = records(&alice, workspace.path());- let bob_spawned = records(&bob, workspace.path());- assert!(alice_spawned- .iter()- .any(|row| row.spec.task_id.as_str() == alice_task));- assert!(alice_spawned- .iter()- .all(|row| row.spec.task_id.as_str() != bob_task));- assert!(bob_spawned- .iter()- .any(|row| row.spec.task_id.as_str() == bob_task));- assert!(bob_spawned- .iter()- .all(|row| row.spec.task_id.as_str() != alice_task));-- alice_tx- .send(DetachedSubagentStatus::Completed {- output: "finished".into(),- iterations: 1,- })- .expect("send terminal status");- tokio::time::timeout(std::time::Duration::from_secs(2), async {- loop {- if records(&alice, workspace.path())- .iter()- .any(|row| row.spec.task_id.as_str() == alice_task && row.is_terminal())- {- break;- }- tokio::task::yield_now().await;- }- })- .await- .expect("Alice terminal status projected");-- assert!(cancel_by_task(&alice, &bob_task).is_none());- assert!(cancel_by_task(&bob, &bob_task).is_some());- let alice_after_cancel = records(&alice, workspace.path());- let bob_after_cancel = records(&bob, workspace.path());- assert_eq!(- alice_after_cancel- .iter()- .find(|row| row.spec.task_id.as_str() == alice_task)- .expect("Alice row remains in Alice store")- .status,- OrchestrationTaskStatus::Completed- );- assert_eq!(- bob_after_cancel- .iter()- .find(|row| row.spec.task_id.as_str() == bob_task)- .expect("Bob row remains in Bob store")- .status,- OrchestrationTaskStatus::Cancelled- );- let _ = alice_tx;- let _ = bob_tx;-}--#[tokio::test]-async fn cancellation_projection_uses_the_captured_profile_store() {- let name = "cancellation_projection_uses_the_captured_profile_store";- let module = module_path!().split_once("::").expect("crate module").1;- let exact = format!("{module}::{name}");- if std::env::var("OPENHUMAN_SUBAGENT_PROJECTION_CHILD").as_deref() != Ok(exact.as_str()) {- let output = std::process::Command::new(std::env::current_exe().expect("test binary"))- .args(["--exact", &exact, "--nocapture", "--test-threads=1"])- .env("OPENHUMAN_SUBAGENT_PROJECTION_CHILD", &exact)- .output()- .expect("run isolated SaaS cancellation test");- assert!(- output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"),- "isolated test {exact} failed:\n{}\n{}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- return;- }-- crate::core::runtime::mode::lock_mode(Mode::Saas).expect("lock isolated SaaS mode");- let _guard = test_guard_async().await;- let workspace = tempfile::tempdir().expect("workspace");- let alice_context = profile("cancel-alice", workspace.path());- let bob_context = profile("cancel-bob", workspace.path());- let alice = DispatchCtx::new(alice_context.clone());- let bob = DispatchCtx::new(bob_context.clone());- let task_id = uuid::Uuid::new_v4().to_string();- let (_status, receiver) = status_channel();- CoreContext::sync_scope(alice_context, || {- register(- &alice,- task_id.clone(),- "researcher".into(),- PARENT.into(),- None,- None,- workspace.path().to_path_buf(),- None,- run_queue(),- dummy_abort(),- receiver,- )- })- .expect("Alice registration");-- assert!(CoreContext::sync_scope(bob_context, || cancel_by_task(&alice, &task_id)).is_some());- let alice_row = records(&alice, workspace.path())- .into_iter()- .find(|row| row.spec.task_id.as_str() == task_id)- .expect("Alice cancellation is persisted to Alice's profile store");- assert_eq!(alice_row.status, OrchestrationTaskStatus::Cancelled);- assert!(records(&bob, workspace.path())- .iter()- .all(|row| row.spec.task_id.as_str() != task_id));-}diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tenant_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tenant_tests.rsdeleted file mode 100644index fd05adf410..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tenant_tests.rs+++ /dev/null@@ -1,546 +0,0 @@-use super::*;-use crate::agent::orchestration::running_subagents::resolve::{- resume_ref_for_task_in_workspace, task_id_for_session_in_workspace,-};-use crate::core::runtime::DispatchCtx;-use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet, Mode};-use crate::tools::toolpacks::ToolGroups;--const CHILD: &str = "OPENHUMAN_DETACHED_TENANT_TEST_CHILD";-const PARENT: &str = "same-parent-session";--// Mode is process-owned and irreversible. Each assertion runs in a fresh-// libtest process, without changing the mode of unrelated desktop tests.-fn child(name: &str, mode: Mode) -> bool {- let module = module_path!().split_once("::").expect("crate module").1;- let test = format!("{module}::{name}");- if std::env::var(CHILD).as_deref() == Ok(test.as_str()) {- crate::core::runtime::mode::lock_mode(mode).expect("lock child mode");- return true;- }- let output = std::process::Command::new(std::env::current_exe().expect("test binary"))- .args(["--exact", &test, "--nocapture", "--test-threads=1"])- .env(CHILD, &test)- .output()- .expect("run isolated mode test");- assert!(- output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"),- "isolated test {test} failed: {}\n{}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- false-}--fn profile(name: &str, workspace: &std::path::Path) -> Arc<CoreContext> {- CoreContext::for_test(DomainSet::full(), None).derive_with(- ContextOverlay::new(- crate::config::Config {- workspace_dir: workspace.to_path_buf(),- ..crate::config::Config::default()- },- DomainSet::kernel(),- ToolGroups::none(),- )- .profile(name)- .session_agent("same-agent"),- )-}--struct Worker {- task: String,- session: String,- abort: AbortHandle,- _status: watch::Sender<DetachedSubagentStatus>,-}--impl Worker {- fn register(workspace: &std::path::Path) -> Self {- let task = uuid::Uuid::new_v4().to_string();- let session = uuid::Uuid::new_v4().to_string();- let queue = run_queue();- let (tx, rx) = status_channel();- let task_handle = tokio::spawn(std::future::pending::<()>());- let abort = task_handle.abort_handle();- register(- &DispatchCtx::ambient(),- task.clone(),- "researcher".into(),- PARENT.into(),- None,- Some(session.clone()),- workspace.to_path_buf(),- None,- queue.clone(),- abort.clone(),- rx,- )- .expect("fixture registration admitted");- Self {- task,- session,- abort,- _status: tx,- }- }-}--impl Drop for Worker {- fn drop(&mut self) {- prune(&self.task);- self.abort.abort();- }-}--struct Pair {- _a_dir: tempfile::TempDir,- _b_dir: tempfile::TempDir,- alice: Arc<CoreContext>,- bob: Arc<CoreContext>,- a: Worker,- b: Worker,-}--impl Pair {- fn new() -> Self {- let a_dir = tempfile::tempdir().unwrap();- let b_dir = tempfile::tempdir().unwrap();- let alice = profile("detached-alice", a_dir.path());- let bob = profile("detached-bob", b_dir.path());- let a = CoreContext::sync_scope(alice.clone(), || Worker::register(a_dir.path()));- let b = CoreContext::sync_scope(bob.clone(), || Worker::register(b_dir.path()));- Self {- _a_dir: a_dir,- _b_dir: b_dir,- alice,- bob,- a,- b,- }- }-}--async fn control(function: &str, task: &str) -> serde_json::Value {- let controller = crate::agent_runs::subagent_control::all_registered_controllers()- .into_iter()- .find(|c| c.schema.function == function)- .expect("public controller");- let mut params = serde_json::Map::new();- params.insert("taskId".into(), serde_json::json!(task));- (controller.handler)(DispatchCtx::ambient(), params)- .await- .expect("control response")-}--fn field(value: &serde_json::Value, key: &str) -> Option<bool> {- value- .get("data")- .and_then(|v| v.get(key))- .or_else(|| value.get(key))- .and_then(serde_json::Value::as_bool)-}--async fn dispatched_control(function: &str, task: &str) -> Result<serde_json::Value, String> {- let params = serde_json::json!({ "taskId": task });- crate::core::invoke::invoke_method(- DispatchCtx::process_default(),- crate::core::invoke::default_state(),- &format!("openhuman.subagent_{function}"),- params,- )- .await-}--#[tokio::test]-async fn saas_dispatch_exposes_only_the_callers_detached_worker_controls() {- if !child(- "saas_dispatch_exposes_only_the_callers_detached_worker_controls",- Mode::Saas,- ) {- return;- }- let mut pair = Pair::new();- let admitted = |name: &str, workspace: &std::path::Path| {- CoreContext::for_test(DomainSet::saas(), None).derive_with(- ContextOverlay::new(- crate::config::Config {- workspace_dir: workspace.to_path_buf(),- ..crate::config::Config::default()- },- crate::profiles::host::user_domains(),- ToolGroups::none(),- )- .profile(name)- .session_agent("same-agent"),- )- };- pair.alice = admitted("detached-alice", pair._a_dir.path());- pair.bob = admitted("detached-bob", pair._b_dir.path());- CoreContext::scope(pair.bob.clone(), async {- for (function, field_name) in [("cancel", "cancelled")] {- let foreign = dispatched_control(function, &pair.a.task)- .await- .expect("reviewed user-plane control must dispatch");- assert_eq!(field(&foreign, field_name), Some(false));- }- assert_eq!(- field(- &dispatched_control("cancel", &pair.b.task).await.unwrap(),- "cancelled"- ),- Some(true)- );- assert!(crate::core::all::schema_for_rpc_method("openhuman.config_get_config").is_none());- })- .await;- CoreContext::scope(pair.alice.clone(), async {- assert!(resume_ref_for_task(&DispatchCtx::ambient(), &pair.a.task, PARENT).is_ok());- })- .await;- assert!(dispatched_control("steer", &pair.a.task).await.is_err());- assert!(dispatched_control("cancel", &pair.a.task).await.is_err());-}--#[tokio::test]-async fn unscoped_async_spawn_refuses_before_persisting_a_running_session() {- if !child(- "unscoped_async_spawn_refuses_before_persisting_a_running_session",- Mode::Saas,- ) {- return;- }- use crate::agent::harness::fork_context::ParentExecutionContext;- use crate::agent::orchestration::subagent_sessions::SubagentSessionStore;- use crate::agent::orchestration::tools::{SpawnSubagentDispatch, SpawnSubagentTool};- use tinyagents_harness::tool::ToolDispatch;- let _ = crate::agent_registry::host_definition::AgentDefinitionRegistry::init_global_builtins();- let workspace = tempfile::tempdir().unwrap();- assert!(- crate::storage::installed().is_none(),- "exercise the real file fallback"- );- let parent = ParentExecutionContext {- workspace_descriptor: None,- agent_definition_id: "orchestrator".into(),- allowed_subagent_ids: std::collections::HashSet::from(["task_manager_agent".into()]),- turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model(Arc::new(- tinyagents_harness::testkit::ScriptedModel::replies(vec!["done"]),- )),- all_tools: Arc::new(Vec::new()),- all_tool_specs: Arc::new(Vec::new()),- visible_tool_specs: Arc::new(Vec::new()),- visible_tool_names: Default::default(),- subagent_tool_ceiling_names: Default::default(),- model_name: "test-model".into(),- temperature: 0.0,- workspace_dir: workspace.path().to_path_buf(),- agent_config: crate::config::AgentConfig::default(),- workflows: Arc::new(Vec::new()),- memory_context: Arc::new(None),- session_id: PARENT.into(),- channel: "test".into(),- connected_integrations: Vec::new(),- tool_call_format: tinytools_agent::dialect::ToolCallFormat::Native,- session_key: "scope-refusal-parent".into(),- session_parent_prefix: None,- on_progress: None,- run_queue: None,- host_env: Default::default(),- };- let run = crate::agent::tinyagents::host::OpenHumanRunContext::new()- .with_parent(parent)- .into_tinyagents(- tinyagents_harness::context::RunConfig::new("scope-refusal")- .with_thread("scope-refusal-parent"),- );- let result = SpawnSubagentDispatch::new(Arc::new(SpawnSubagentTool::new()))- .execute(- &(),- tinyagents_harness::ids::CallId::new("scope-refusal-spawn"),- serde_json::json!({"agent_id": "task_manager_agent", "prompt": "deterministic fixture"}),- tinytools::ToolCallOptions::default(),- &run,- )- .await- .expect("tool dispatch reports a refusal as a tool outcome");- // An unscoped SaaS call fails closed on the store itself, so nothing was- // persisted either way.- let sessions = match SubagentSessionStore::new(workspace.path().to_path_buf()).load() {- Ok(sessions) => sessions,- Err(err) => {- assert!(- err.contains("no tenant scope in SaaS mode; refusing to act as the operator"),- "unexpected store error: {err}"- );- Vec::new()- }- };- assert!(- result.is_error,- "unscoped spawn must not report accepted: {}",- result.output()- );- assert!(- result.output().contains("scope"),- "typed refusal must explain missing scope"- );- assert!(- sessions.is_empty(),- "refused spawn must not create durable sessions: {sessions:?}"- );- assert!(snapshot_for_parent(&DispatchCtx::ambient(), PARENT).is_empty());- assert!(- std::fs::read_dir(workspace.path())- .unwrap()- .next()- .is_none(),- "scope refusal must precede session and worker-thread writes"- );-}--#[tokio::test]-async fn same_parent_rosters_are_profile_isolated() {- if !child("same_parent_rosters_are_profile_isolated", Mode::Saas) {- return;- }- let pair = Pair::new();- for (ctx, own) in [(&pair.alice, &pair.a), (&pair.bob, &pair.b)] {- let tasks = CoreContext::sync_scope(ctx.clone(), || {- snapshot_for_parent(&DispatchCtx::ambient(), PARENT)- });- assert_eq!(- tasks.iter().map(|t| t.task_id.as_str()).collect::<Vec<_>>(),- [own.task.as_str()]- );- }-}--#[tokio::test]-async fn same_parent_resolution_and_wait_refuse_foreign_workers() {- if !child(- "same_parent_resolution_and_wait_refuse_foreign_workers",- Mode::Saas,- ) {- return;- }- let pair = Pair::new();- CoreContext::scope(pair.bob.clone(), async {- assert!(matches!(- task_id_for_session(&DispatchCtx::ambient(), &pair.a.session, PARENT),- Err(WaitError::NotOwned)- ));- assert!(matches!(- resume_ref_for_task(&DispatchCtx::ambient(), &pair.a.task, PARENT),- Err(WaitError::NotOwned)- ));- assert_eq!(- task_id_for_session(&DispatchCtx::ambient(), &pair.b.session, PARENT).unwrap(),- pair.b.task- );- })- .await;-}--#[tokio::test]-async fn public_cancellation_refuses_another_profiles_task() {- if !child(- "public_cancellation_refuses_another_profiles_task",- Mode::Saas,- ) {- return;- }- let pair = Pair::new();- CoreContext::scope(pair.bob.clone(), async {- assert_eq!(- field(&control("cancel", &pair.a.task).await, "cancelled"),- Some(false)- );- assert!(resume_ref_for_task(&DispatchCtx::ambient(), &pair.b.task, PARENT).is_ok());- assert_eq!(- field(&control("cancel", &pair.b.task).await, "cancelled"),- Some(true)- );- })- .await;- CoreContext::scope(pair.alice.clone(), async {- assert!(- resume_ref_for_task(&DispatchCtx::ambient(), &pair.a.task, PARENT).is_ok(),- "foreign cancel leaves original worker live"- );- })- .await;-}--#[tokio::test]-async fn missing_saas_scope_cannot_observe_or_control_workers() {- if !child(- "missing_saas_scope_cannot_observe_or_control_workers",- Mode::Saas,- ) {- return;- }- let pair = Pair::new();- assert!(CoreContext::scoped().is_none());- assert!(snapshot_for_parent(&DispatchCtx::ambient(), PARENT).is_empty());- assert!(matches!(- resume_ref_for_task(&DispatchCtx::ambient(), &pair.a.task, PARENT),- Err(WaitError::NotOwned)- ));- assert!(dispatched_control("steer", &pair.a.task).await.is_err());- assert_eq!(- field(&control("cancel", &pair.a.task).await, "cancelled"),- Some(false)- );- CoreContext::sync_scope(pair.alice.clone(), || {- assert!(resume_ref_for_task(&DispatchCtx::ambient(), &pair.a.task, PARENT).is_ok())- });- // A scoped kernel context without an admitted profile is not authority.- CoreContext::scope(CoreContext::for_test(DomainSet::full(), None), async {- assert!(snapshot_for_parent(&DispatchCtx::ambient(), PARENT).is_empty());- assert!(matches!(- resume_ref_for_task(&DispatchCtx::ambient(), &pair.a.task, PARENT),- Err(WaitError::NotOwned)- ));- assert!(dispatched_control("steer", &pair.a.task).await.is_err());- assert_eq!(- field(&control("cancel", &pair.a.task).await, "cancelled"),- Some(false)- );- })- .await;-}--#[tokio::test]-async fn desktop_public_controls_remain_available_without_parent_scope() {- if !child(- "desktop_public_controls_remain_available_without_parent_scope",- Mode::SingleUser,- ) {- return;- }- let directory = tempfile::tempdir().unwrap();- let worker = Worker::register(directory.path());- assert_eq!(- snapshot_for_parent(&DispatchCtx::ambient(), PARENT).len(),- 1- );- assert!(dispatched_control("steer", &worker.task).await.is_err());- assert_eq!(- field(&control("cancel", &worker.task).await, "cancelled"),- Some(true)- );-}--/// The explicit context decides, with no task scope anywhere: a worker is-/// reachable through its own profile's context and refused through another's,-/// across awaits, from spawned tasks and concurrently.-#[tokio::test]-async fn saas_controls_follow_the_explicit_context_not_the_tasks_scope() {- if !child(- "saas_controls_follow_the_explicit_context_not_the_tasks_scope",- Mode::Saas,- ) {- return;- }- let pair = Pair::new();- let alice = DispatchCtx::new(pair.alice.clone());- let bob = DispatchCtx::new(pair.bob.clone());- let (a_task, b_task) = (pair.a.task.clone(), pair.b.task.clone());-- // Not a single `CoreContext::scope` here: with the ambient reader the- // task would be unscoped, which fails closed in SaaS.- assert!(resume_ref_for_task(&alice, &a_task, PARENT).is_ok());- assert!(matches!(- resume_ref_for_task(&bob, &a_task, PARENT),- Err(WaitError::NotOwned)- ));- assert!(cancel_by_task(&bob, &a_task).is_none());- assert!(snapshot_for_parent(&bob, PARENT)- .iter()- .all(|worker| worker.task_id != a_task));-- assert!(- cancel_by_task(&alice, &b_task).is_none(),- "alice cannot cancel bob's worker"- );-- // Concurrent, across awaits, and from spawned tasks: each carries its own.- let spawned = |ctx: DispatchCtx, task: String| {- tokio::spawn(async move {- tokio::task::yield_now().await;- let own = resume_ref_for_task(&ctx, &task, PARENT).is_ok();- tokio::task::yield_now().await;- let foreign = cancel_by_task(&ctx, &task).is_some();- (own, foreign)- })- };- let (a_side, b_side) = tokio::join!(- spawned(alice.clone(), a_task.clone()),- spawned(bob.clone(), b_task.clone())- );- assert_eq!(- a_side.unwrap(),- (true, true),- "alice reaches her own worker"- );- assert_eq!(b_side.unwrap(), (true, true), "bob reaches his own worker");- assert!(snapshot_for_parent(&alice, PARENT)- .iter()- .all(|worker| worker.task_id != a_task));-}--#[tokio::test]-async fn durable_fallback_store_uses_explicit_profile_context_at_shared_workspace() {- if !child(- "durable_fallback_store_uses_explicit_profile_context_at_shared_workspace",- Mode::Saas,- ) {- return;- }- let workspace = tempfile::tempdir().unwrap();- let alice_context = profile("durable-alice", workspace.path());- let bob_context = profile("durable-bob", workspace.path());- let alice = DispatchCtx::new(alice_context.clone());- let bob = DispatchCtx::new(bob_context.clone());- let task_id = uuid::Uuid::new_v4().to_string();- let session_id = uuid::Uuid::new_v4().to_string();-- CoreContext::sync_scope(alice_context, || {- super::super::task_ledger::record_spawned(- &task_id,- "researcher",- PARENT,- None,- Some(&session_id),- workspace.path(),- None,- );- });-- let assert_alice_can_recover = || {- assert_eq!(- task_id_for_session_in_workspace(&alice, &session_id, PARENT, workspace.path())- .unwrap(),- task_id- );- assert_eq!(- resume_ref_for_task_in_workspace(&alice, &task_id, PARENT, workspace.path())- .unwrap()- .task_id,- task_id- );- };-- // No ambient task scope is installed: the explicit Alice context owns the- // durable lookup even though both profiles use the same workspace path.- assert!(CoreContext::scoped().is_none());- assert_alice_can_recover();-- // A foreign ambient scope must not redirect Alice's explicit lookup to- // Bob's profile store.- CoreContext::sync_scope(bob_context, assert_alice_can_recover);- assert!(matches!(- resume_ref_for_task_in_workspace(&bob, &task_id, PARENT, workspace.path()),- Err(WaitError::Unknown)- ));-}diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rsdeleted file mode 100644index e28b44d973..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs+++ /dev/null@@ -1,535 +0,0 @@-use super::*;--/// The context these tests dispatch under: the calling task's own.-fn cx() -> crate::core::runtime::DispatchCtx {- crate::core::runtime::DispatchCtx::ambient()-}--use crate::agent::orchestration::running_subagents::resolve::resume_ref_for_task;-use crate::agent::orchestration::running_subagents::resolve::task_id_for_session;-use crate::agent::orchestration::running_subagents::roster::snapshot_for_parent;-use crate::agent::queued_turn::QueuedTurn;-use std::path::PathBuf;-use std::sync::Arc;-use tinyagents_harness::ids::TaskId;-use tinyagents_harness::run_queue::RunQueue;-use tinyagents_orchestration::subagent::FinishedOutcome;-use tinyagents_orchestration::subagent::{- DetachedSubagentStatus, WaitError, DETACHED_LEDGER_TIMEOUT_MS,-};-use tinyagents_tasks::OrchestrationTaskStatus;-use tokio::sync::watch;-use tokio::task::AbortHandle;--#[path = "running_subagents_cancel_tests.rs"]-mod cancel_tests;--#[path = "running_subagents_wire_tests.rs"]-mod wire_tests;--#[path = "running_subagents_tenant_tests.rs"]-mod tenant_tests;--#[path = "running_subagents_projection_tests.rs"]-mod projection_tests;--/// Serializes every test that touches the global [`REGISTRY`]. We reuse the-/// crate-wide `TEST_ENV_LOCK` (rather than a module-local mutex) because the-/// destructive `cancel_all` path is also reachable from the `threads::ops`-/// tests — those hold the same lock, so this prevents a purge there from-/// wiping entries a test here is mid-way through.-fn test_guard() -> tokio::sync::MutexGuard<'static, ()> {- // Recover from a poisoned guard so one panicking test doesn't cascade.- crate::config::TEST_ENV_LOCK.blocking_lock()-}--async fn test_guard_async() -> tokio::sync::MutexGuard<'static, ()> {- // Recover from a poisoned guard so one panicking test doesn't cascade.- crate::config::TEST_ENV_LOCK.lock().await-}--fn dummy_abort() -> AbortHandle {- tokio::spawn(async {}).abort_handle()-}--fn run_queue() -> Arc<RunQueue<QueuedTurn>> {- Arc::new(RunQueue::new())-}--/// Per-process-run unique workspace for the detached task store.-///-/// The task store is now a durable JSONL file under the given workspace-/// (issue #4249). Pointing tests at the shared `std::env::temp_dir()` leaked-/// records **across** test-process runs: a `task-ledger-1` left `Completed`-/// by a prior run would make `record_spawned`'s insert/`mark_running` no-op-/// (id already terminal), so this run would observe the stale terminal status-/// instead of `Running`. A fresh temp dir per process run keeps the store-/// hermetic; task ids are unique across tests so a single shared dir is safe-/// within a run. The `TempDir` lives for the whole process (cleaned at exit).-fn test_workspace() -> PathBuf {- static WORKSPACE: std::sync::LazyLock<tempfile::TempDir> = std::sync::LazyLock::new(|| {- tempfile::tempdir().expect("create hermetic test task-store workspace")- });- WORKSPACE.path().to_path_buf()-}--/// Register a sub-agent for tests, returning the status sender so the test-/// can drive completion. Keeping the sender alive keeps the channel open.-fn register_test(- task_id: &str,- parent_session: &str,- rq: Arc<RunQueue<QueuedTurn>>,-) -> watch::Sender<DetachedSubagentStatus> {- register_test_with_thread(task_id, parent_session, None, rq)-}--/// Like [`register_test`] but lets a test set the parent thread id so it can-/// exercise [`cancel_for_thread`].-fn register_test_with_thread(- task_id: &str,- parent_session: &str,- parent_thread_id: Option<&str>,- rq: Arc<RunQueue<QueuedTurn>>,-) -> watch::Sender<DetachedSubagentStatus> {- let (tx, rx) = status_channel();- register(- &cx(),- task_id.into(),- "researcher".into(),- parent_session.into(),- None,- None,- test_workspace(),- parent_thread_id.map(Into::into),- rq,- dummy_abort(),- rx,- )- .expect("fixture registration admitted");- tx-}--#[tokio::test]-async fn late_registration_rejects_a_parent_generation_reopened_after_spawn() {- let _guard = test_guard_async().await;- let ctx = cx();- let workspace = tempfile::tempdir().expect("workspace");- let thread_id = "late-register-old-generation";- let old_epoch = crate::agent::orchestration::background_completions::CompletionTarget::new(- ctx.clone(),- workspace.path().to_path_buf(),- "late-register-parent".into(),- Some(thread_id.into()),- )- .expect("initial spawn admitted")- .parent_epoch()- .unwrap();- let router = crate::agent::orchestration::background_completions::router_for_workspace_ctx(- &ctx,- workspace.path(),- );- router- .cancel_parent(thread_id)- .expect("stop old generation");- router.resume_parent(thread_id);- assert!(!router- .parent_generation_admitted(thread_id, old_epoch)- .unwrap());-- let child = tokio::spawn(std::future::pending::<()>());- let (_status_tx, status_rx) = status_channel();- let result = register_with_parent_epoch(- &ctx,- "late-register-old-task".into(),- "researcher".into(),- "late-register-parent".into(),- None,- None,- workspace.path().to_path_buf(),- Some(thread_id.into()),- Some(old_epoch),- run_queue(),- child.abort_handle(),- status_rx,- );- assert!(matches!(result, Err(RegistrationError::ParentLifecycle(_))));- assert!(child.await.unwrap_err().is_cancelled());- assert!(cancel_by_task(&ctx, "late-register-old-task").is_none());-}--#[tokio::test]-async fn task_store_records_spawn_complete_and_cancel() {- let _guard = test_guard_async().await;- // Spawn → the ledger sees a running SubAgent task scoped to the parent.- let tx = register_test("task-ledger-1", "ledger-parent", run_queue());- let running = task_records(Some("ledger-parent"));- assert!(- running- .iter()- .any(|r| r.spec.task_id.as_str() == "task-ledger-1"- && r.spec.parent_run_id.as_ref().map(|id| id.as_str()) == Some("ledger-parent")- && r.spec.root_run_id.as_ref().map(|id| id.as_str()) == Some("ledger-parent")- && r.spec.timeout_ms == Some(DETACHED_LEDGER_TIMEOUT_MS)- && r.status == OrchestrationTaskStatus::Running),- "spawned sub-agent is recorded Running: {running:?}"- );-- // Publish a terminal status → the watcher mirrors Completed into the store.- tx.send(DetachedSubagentStatus::Completed {- output: "done".into(),- iterations: 2,- })- .unwrap();- // Let the watcher task observe the change.- for _ in 0..50 {- tokio::task::yield_now().await;- if task_records(None)- .iter()- .any(|r| r.spec.task_id.as_str() == "task-ledger-1" && r.is_terminal())- {- break;- }- }- let after = task_records(None);- let rec = after- .iter()- .find(|r| r.spec.task_id.as_str() == "task-ledger-1")- .expect("ledger record present");- assert_eq!(rec.status, OrchestrationTaskStatus::Completed);-- // A second sub-agent that gets cancelled is recorded Cancelled.- let _tx2 = register_test("task-ledger-2", "ledger-parent", run_queue());- assert!(cancel_by_task(&cx(), "task-ledger-2").is_some());- let cancelled = task_records(None)- .into_iter()- .find(|r| r.spec.task_id.as_str() == "task-ledger-2")- .expect("cancelled record present");- assert_eq!(cancelled.status, OrchestrationTaskStatus::Cancelled);-- prune("task-ledger-1");-}--#[tokio::test]-async fn task_id_for_session_enforces_parent_ownership() {- let _guard = test_guard_async().await;- let rq = run_queue();- let (tx, rx) = status_channel();- register(- &cx(),- "task-session".into(),- "researcher".into(),- "session-owner".into(),- None,- Some("subsess-1".into()),- test_workspace(),- Some("thread-1".into()),- rq,- dummy_abort(),- rx,- )- .expect("fixture registration admitted");-- assert_eq!(- task_id_for_session(&cx(), "subsess-1", "session-owner").unwrap(),- "task-session"- );- assert!(matches!(- task_id_for_session(&cx(), "subsess-1", "session-other"),- Err(WaitError::NotOwned)- ));- let _ = tx.send(DetachedSubagentStatus::Completed {- output: "done".into(),- iterations: 1,- });- prune("task-session");-}--#[tokio::test]-async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {- let _guard = test_guard_async().await;- let (tx_a, rx_a) = status_channel();- register(- &cx(),- "task-fleet-a".into(),- "researcher".into(),- "fleet-parent".into(),- None,- Some("subsess-a".into()),- test_workspace(),- None,- run_queue(),- dummy_abort(),- rx_a,- )- .expect("fixture registration admitted");- let (tx_b, rx_b) = status_channel();- register(- &cx(),- "task-fleet-b".into(),- "code_executor".into(),- "fleet-parent".into(),- None,- Some("subsess-b".into()),- test_workspace(),- None,- run_queue(),- dummy_abort(),- rx_b,- )- .expect("fixture registration admitted");- // A worker owned by a different parent must not leak into the snapshot.- let (tx_other, rx_other) = status_channel();- register(- &cx(),- "task-fleet-other".into(),- "researcher".into(),- "other-parent".into(),- None,- Some("subsess-other".into()),- test_workspace(),- None,- run_queue(),- dummy_abort(),- rx_other,- )- .expect("fixture registration admitted");-- // `b` pauses awaiting the user; `a` stays running.- tx_b.send(DetachedSubagentStatus::AwaitingUser {- question: "which repo?".into(),- })- .unwrap();-- let snap = snapshot_for_parent(&cx(), "fleet-parent");- assert_eq!(snap.len(), 2, "only this parent's workers: {snap:?}");- // Ordered by agent_id then task_id → code_executor before researcher.- assert_eq!(snap[0].agent_id, "code_executor");- assert_eq!(snap[0].status, "awaiting_user");- assert_eq!(snap[1].agent_id, "researcher");- assert_eq!(snap[1].status, "running");-- let block = active_subagents_context_block(&cx(), "fleet-parent", &test_workspace())- .expect("block present");- assert!(block.contains("[active_subagents]"));- assert!(block.contains("reuse its task_key with spawn_subagent"));- assert!(block.contains("You have 2 sub-agent worker(s)"));- assert!(block.contains("session=subsess-a"));- assert!(block.contains("session=subsess-b · task=task-fleet-b · status=awaiting_user"));- assert!(block.ends_with("[/active_subagents]\n\n"));-- // A parent with no registered workers gets no block (no perturbation).- assert!(active_subagents_context_block(&cx(), "nobody-here", &test_workspace(),).is_none());-- // The shipped orchestrator has no wait/steer/close tools (#5701): the- // guidance must not name them and must say results arrive on their own.- {- let block = active_subagents_context_block(&cx(), "fleet-parent", &test_workspace())- .expect("block present");- for name in [- "wait_subagent",- "steer_subagent",- "close_subagent",- "wait_loop",- ] {- assert!(- !block.contains(name),- "{name} named for a parent without it:\n{block}"- );- }- assert!(block.contains("delivered automatically"));- }-- // Durable-store fallback: a session persisted by an EARLIER turn /- // process lifetime (empty live registry for this parent) must still- // surface in the roster, so a cold-booted orchestrator can resume by- // subagent_session_id instead of re-delegating from scratch.- {- use crate::agent::orchestration::subagent_sessions::{- self, SubagentSessionSelector, SubagentSessionStore, SubagentSessionUpsert,- };- use crate::agent::subagent_host::SubagentRunStatus;- let durable_ws = tempfile::tempdir().expect("durable roster tempdir");- let store = SubagentSessionStore {- workspace_dir: durable_ws.path().to_path_buf(),- };- let session = subagent_sessions::upsert_running(- &store,- SubagentSessionUpsert {- selector: SubagentSessionSelector {- parent_session: "cold-parent".into(),- parent_thread_id: Some("thread-cold".into()),- agent_id: "workflow_builder".into(),- model: None,- sandbox_mode: "None".into(),- action_root: None,- task_key: "daily-x-trending".into(),- },- display_name: Some("Workflow Builder".into()),- task_title: "Daily X trending email workflow".into(),- worker_thread_id: None,- task_id: "task-cold-1".into(),- lifecycle_key: None,- parent_epoch: None,- },- None,- )- .expect("upsert durable session");- subagent_sessions::mark_finished(- &store,- &session.subagent_session_id,- "task-cold-1",- &SubagentRunStatus::Completed,- Vec::new(),- )- .expect("mark idle");-- let block = active_subagents_context_block(&cx(), "cold-parent", durable_ws.path())- .expect("durable-only roster present");- assert!(block.contains(&format!("session={}", session.subagent_session_id)));- assert!(block.contains("status=idle"));- assert!(block.contains("about: Daily X trending email workflow"));- // Other parents' durable sessions must not leak in.- assert!(- active_subagents_context_block(&cx(), "unrelated-parent", durable_ws.path(),).is_none()- );- }-- let _ = tx_a.send(DetachedSubagentStatus::Completed {- output: "x".into(),- iterations: 1,- });- let _ = tx_other.send(DetachedSubagentStatus::Completed {- output: "x".into(),- iterations: 1,- });- prune("task-fleet-a");- prune("task-fleet-b");- prune("task-fleet-other");-}--#[tokio::test]-async fn resume_ref_for_task_includes_resume_fields_and_enforces_ownership() {- let _guard = test_guard_async().await;- let (tx, rx) = status_channel();- register(- &cx(),- "task-resume".into(),- "researcher".into(),- "session-owner".into(),- None,- Some("subsess-resume".into()),- test_workspace(),- Some("thread-1".into()),- run_queue(),- dummy_abort(),- rx,- )- .expect("fixture registration admitted");-- let reference =- resume_ref_for_task(&cx(), "task-resume", "session-owner").expect("resume reference");- assert_eq!(reference.task_id, "task-resume");- assert_eq!(reference.agent_id, "researcher");- assert_eq!(- reference.subagent_session_id.as_deref(),- Some("subsess-resume")- );- assert!(matches!(- resume_ref_for_task(&cx(), "task-resume", "session-other"),- Err(WaitError::NotOwned)- ));-- let _ = tx.send(DetachedSubagentStatus::Completed {- output: "done".into(),- iterations: 1,- });- prune("task-resume");-}--#[tokio::test]-async fn task_id_for_session_prefers_live_task_over_terminal_task() {- let _guard = test_guard_async().await;- let (old_tx, old_rx) = status_channel();- register(- &cx(),- "task-old".into(),- "researcher".into(),- "session-owner".into(),- None,- Some("subsess-live".into()),- test_workspace(),- Some("thread-1".into()),- run_queue(),- dummy_abort(),- old_rx,- )- .expect("fixture registration admitted");- let _ = old_tx.send(DetachedSubagentStatus::Completed {- output: "old".into(),- iterations: 1,- });- let (_new_tx, new_rx) = status_channel();- register(- &cx(),- "task-new".into(),- "researcher".into(),- "session-owner".into(),- None,- Some("subsess-live".into()),- test_workspace(),- Some("thread-1".into()),- run_queue(),- dummy_abort(),- new_rx,- )- .expect("fixture registration admitted");-- assert_eq!(- task_id_for_session(&cx(), "subsess-live", "session-owner").unwrap(),- "task-new"- );- prune("task-old");- prune("task-new");-}--#[tokio::test]-async fn cancel_for_thread_aborts_only_matching_entries() {- let _guard = test_guard_async().await;- let rq = run_queue();- let _a = register_test_with_thread("task-tA-1", "session-A", Some("thread-X"), rq.clone());- let _b = register_test_with_thread("task-tA-2", "session-A", Some("thread-X"), rq.clone());- // Different thread — must survive.- let _c = register_test_with_thread("task-tB", "session-A", Some("thread-Y"), rq.clone());- // Headless (no parent thread) — must survive.- let _d = register_test_with_thread("task-headless", "session-A", None, rq);-- let cancelled = cancel_for_thread(&cx(), "thread-X");- assert_eq!(cancelled, 2, "both thread-X entries should be cancelled");-- // Idempotent: a second pass cancels nothing.- assert_eq!(cancel_for_thread(&cx(), "thread-X"), 0);-- prune("task-tB");- prune("task-headless");-}--#[tokio::test]-async fn cancel_by_task_returns_metadata_and_removes_entry() {- let _guard = test_guard_async().await;- let rq = run_queue();- let _tx = register_test_with_thread("task-cbt", "session-Z", Some("thread-cbt"), rq.clone());- let task_id = TaskId::new("task-cbt");-- let meta = cancel_by_task(&cx(), "task-cbt").expect("known task should cancel");- assert_eq!(- meta.already_finished, None,- "a running task is a real cancel"- );- assert_eq!(meta.agent_id, "researcher");- assert_eq!(meta.parent_session, "session-Z");- assert_eq!(meta.parent_thread_id.as_deref(), Some("thread-cbt"));- // Entry is gone and a second cancel is a no-op.- assert!(cancel_by_task(&cx(), "task-cbt").is_none());- // Unknown ids are simply None.- assert!(cancel_by_task(&cx(), "never-existed").is_none());-}diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_wire_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_wire_tests.rsdeleted file mode 100644index 749f2bd2e9..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_wire_tests.rs+++ /dev/null@@ -1,162 +0,0 @@-//! Literal fixtures for the surviving sub-agent roster and cancellation-//! surfaces, plus the durable task-ledger record shape.--use super::*;-use crate::agent::orchestration::running_subagents::roster::snapshot_for_parent;-use crate::agent::orchestration::running_subagents::task_ledger::task_store_for_workspace;-use tinyagents_harness::ids::TaskId;-use tinyagents_orchestration::subagent::FinishedOutcome;-use tinyagents_tasks::{OrchestrationTaskKind, OrchestrationTaskSpec};--fn spec(id: &str, parent: &str, session: Option<&str>) -> OrchestrationTaskSpec {- let mut spec = OrchestrationTaskSpec::new(- id.to_string(),- OrchestrationTaskKind::SubAgent {- agent: "researcher".to_string(),- },- )- .with_lineage(parent.to_string(), parent.to_string())- .with_metadata("parentSession", parent.to_string());- if let Some(session) = session {- spec = spec.with_metadata("subagentSessionId", session.to_string());- }- spec-}--#[tokio::test]-async fn roster_status_labels_are_literal() {- let _guard = super::test_guard_async().await;- let mut senders = Vec::new();- for id in ["wire-run", "wire-done", "wire-await", "wire-fail"] {- let (tx, rx) = status_channel();- register(- &crate::core::runtime::DispatchCtx::ambient(),- id.into(),- "researcher".into(),- "wire-parent".into(),- None,- None,- super::test_workspace(),- None,- super::run_queue(),- super::dummy_abort(),- rx,- )- .expect("fixture registration admitted");- senders.push((id, tx));- }- for (id, tx) in &senders {- match *id {- "wire-done" => tx- .send(DetachedSubagentStatus::Completed {- output: "o".into(),- iterations: 1,- })- .unwrap(),- "wire-await" => tx- .send(DetachedSubagentStatus::AwaitingUser {- question: "q".into(),- })- .unwrap(),- "wire-fail" => tx- .send(DetachedSubagentStatus::Failed { error: "e".into() })- .unwrap(),- _ => {}- }- }- let labels: Vec<(String, &str)> =- snapshot_for_parent(&crate::core::runtime::DispatchCtx::ambient(), "wire-parent")- .into_iter()- .map(|s| (s.task_id, s.status))- .collect();- assert_eq!(- labels,- vec![- ("wire-await".to_string(), "awaiting_user"),- ("wire-done".to_string(), "completed"),- ("wire-fail".to_string(), "failed"),- ("wire-run".to_string(), "running"),- ]- );- for (id, _) in senders {- prune(id);- }-}--#[test]-fn cancel_outcome_strings_are_literal() {- assert_eq!(FinishedOutcome::Completed.as_str(), "completed");- assert_eq!(FinishedOutcome::Failed.as_str(), "failed");-}--#[tokio::test]-async fn spawn_ledger_record_has_literal_persisted_shape() {- let _guard = super::test_guard_async().await;- let ws = tempfile::tempdir().unwrap();- let (_tx, rx) = status_channel();- register(- &crate::core::runtime::DispatchCtx::ambient(),- "wire-shape-1".into(),- "researcher".into(),- "wire-shape-parent".into(),- Some("rootrun__child".into()),- Some("subsess-9".into()),- ws.path().to_path_buf(),- Some("thread-7".into()),- super::run_queue(),- super::dummy_abort(),- rx,- )- .expect("fixture registration admitted");- let record = super::task_ledger::list_task_records(ws.path())- .into_iter()- .next()- .expect("a ledger record in the storage backend");- let rendered = serde_json::to_value(&record).unwrap().to_string();- for needle in [- r#""parentSession":"wire-shape-parent""#,- r#""rootSession":"rootrun""#,- r#""defaultWaitTimeoutMs":"120000""#,- r#""sessionParentPrefix":"rootrun__child""#,- r#""parentThreadId":"thread-7""#,- r#""subagentSessionId":"subsess-9""#,- r#""workspaceDir":""#,- ] {- assert!(rendered.contains(needle), "{needle} missing in {rendered}");- }- assert!(rendered.contains("sub_agent") || rendered.contains("SubAgent"));- println!("LEDGER_LINE {rendered}");- prune("wire-shape-1");-}--#[test]-fn reconcile_reason_and_resume_labels_are_literal() {- // Asserted through the durable record the reconciler writes.- let ws = tempfile::tempdir().unwrap();- let store = task_store_for_workspace(ws.path());- store- .insert(spec("wire-orphan-run", "wire-orphan-parent", None))- .unwrap();- store.mark_running(&TaskId::new("wire-orphan-run")).unwrap();- store- .insert(spec("wire-orphan-cancel", "wire-orphan-parent", None))- .unwrap();- store- .mark_running(&TaskId::new("wire-orphan-cancel"))- .unwrap();- store- .request_cancel(&TaskId::new("wire-orphan-cancel"))- .unwrap();- assert_eq!(reconcile_orphaned_tasks_on_boot(ws.path()), 2);- let failed = store.get(&TaskId::new("wire-orphan-run")).unwrap();- assert_eq!(- failed.error.as_deref(),- Some("sub-agent orphaned by core restart (was `running`)")- );- let cancelled = store.get(&TaskId::new("wire-orphan-cancel")).unwrap();- assert_eq!(- format!("{:?}", cancelled.status),- "Cancelled",- "cancel-requested orphans settle as cancelled"- );-}