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
fix: close agent admission before approval barriers and surface flows atomically
Steven Enamakeldfddbad81809
diff --git a/crates/openhuman-core/src/security/approval/flow_surface.rs b/crates/openhuman-core/src/security/approval/flow_surface.rsnew file mode 100644index 0000000000..e15eaa4b75--- /dev/null+++ b/crates/openhuman-core/src/security/approval/flow_surface.rs@@ -0,0 +1,22 @@+//! Orders request registration and its approval surfaces after workspace resolution.++use super::ApprovalScope;++/// Resolve the workspace before registering and publishing any approval surface.+/// Removal during resolution refuses registration; accepted registration and+/// publication finish together before removal. No barrier is held across the await.+pub(super) async fn register_after_workspace<W, T>(+ scope: Option<&ApprovalScope>,+ workspace: impl std::future::Future<Output = W>,+ register: impl FnOnce(W) -> T,+) -> Result<T, String> {+ let workspace = workspace.await;+ match scope {+ Some(scope) => scope.with_open(|| register(workspace)),+ None => Ok(register(workspace)),+ }+}++#[cfg(test)]+#[path = "flow_surface_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/security/approval/flow_surface_tests.rs b/crates/openhuman-core/src/security/approval/flow_surface_tests.rsnew file mode 100644index 0000000000..9f6233bfd6--- /dev/null+++ b/crates/openhuman-core/src/security/approval/flow_surface_tests.rs@@ -0,0 +1,83 @@+use super::*;+use std::cell::Cell;+use std::future::Future;+use std::sync::Arc;+use std::task::{Context, Poll, Wake, Waker};++struct Noop;+impl Wake for Noop {+ fn wake(self: Arc<Self>) {}+}++#[test]+fn a_closed_instance_registers_nothing_and_publishes_neither_flow_surface() {+ let scope = ApprovalScope::default();+ scope.close("agent_removed");+ let publications = Cell::new(0);+ let mut publication = std::pin::pin!(register_after_workspace(+ Some(&scope),+ std::future::ready(17),+ |_| publications.set(publications.get() + 1),+ ));+ let waker = Waker::from(Arc::new(Noop));+ assert_eq!(+ publication.as_mut().poll(&mut Context::from_waker(&waker)),+ Poll::Ready(Err("agent_removed".to_owned()))+ );+ assert_eq!(publications.get(), 0);+}++#[test]+fn removal_during_workspace_lookup_suppresses_registration_and_all_surfaces() {+ let scope = ApprovalScope::default();+ let ready = Cell::new(false);+ let workspace = std::future::poll_fn(|_| {+ if ready.get() {+ Poll::Ready(17)+ } else {+ Poll::Pending+ }+ });+ let publications = Cell::new(0);+ let mut publication = std::pin::pin!(register_after_workspace(Some(&scope), workspace, |_| {+ publications.set(publications.get() + 1)+ },));+ let waker = Waker::from(Arc::new(Noop));+ let mut cx = Context::from_waker(&waker);+ assert_eq!(publication.as_mut().poll(&mut cx), Poll::Pending);+ assert_eq!(+ publications.get(),+ 0,+ "registration preceded workspace resolution"+ );+ scope.close("agent_removed");+ ready.set(true);+ assert_eq!(+ publication.as_mut().poll(&mut cx),+ Poll::Ready(Err("agent_removed".to_owned()))+ );+ assert_eq!(publications.get(), 0);+}++#[test]+fn a_live_or_unscoped_flow_registers_once_with_its_resolved_workspace() {+ let scope = ApprovalScope::default();+ for scope in [Some(&scope), None] {+ let publications = Cell::new(0);+ let mut publication = std::pin::pin!(register_after_workspace(+ scope,+ std::future::ready(Some(("ws_test", 17))),+ |workspace| {+ assert_eq!(workspace, Some(("ws_test", 17)));+ publications.set(publications.get() + 1);+ 42+ },+ ));+ let waker = Waker::from(Arc::new(Noop));+ assert_eq!(+ publication.as_mut().poll(&mut Context::from_waker(&waker)),+ Poll::Ready(Ok(42))+ );+ assert_eq!(publications.get(), 1);+ }+}diff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rsindex d4d95a3ec9..75eb097e74 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs@@ -503,7 +503,7 @@ impl ApprovalGate {let (tx, rx) = oneshot::channel::<ApprovalDecision>();let scope = crate::core::runtime::CoreContext::current_host_overrides().and_then(|overrides| overrides.approval_scope());- let register = || -> anyhow::Result<()> {+ let register = |workspace| -> anyhow::Result<()> {{let mut waiters = self.waiters.lock();waiters.insert(request_id.clone(), tx);@@ -554,12 +554,55 @@ impl ApprovalGate {expires_at: expires_at.map(|t| t.to_rfc3339()),agent_id: agent_id.clone(),});+ // Publish every surface inside the same registration barrier.+ // Workspace lookup completed before creating a row, so neither+ // removal nor a fast human decision can precede these surfaces.+ if let Some(ApprovalSourceContext::Flow {+ flow_id, run_id, ..+ }) = &source_context+ {+ tracing::info!(request_id = %request_id, flow_id = %flow_id,+ run_id = %run_id, tool = tool_name,+ "[approval::gate] flow-origin park — surfacing flow_approval_request + notification");+ BUS.publish(DomainEvent::FlowApprovalRequested {+ request_id: request_id.clone(),+ flow_id: flow_id.clone(),+ run_id: run_id.clone(),+ tool_name: tool_name.to_string(),+ summary: action_summary.to_string(),+ agent_id: agent_id.clone(),+ });+ publish_flow_gate_notification(+ &request_id,+ flow_id,+ run_id,+ tool_name,+ action_summary,+ workspace,+ );+ }Ok(())};- let registered = match scope.as_ref() {- Some(scope) => scope.with_open(register),- None => Ok(register()),- };+ let registered = super::flow_surface::register_after_workspace(+ scope.as_deref(),+ async {+ if !matches!(&source_context, Some(ApprovalSourceContext::Flow { .. })) {+ return None;+ }+ // Resolve before registration; never hold the barrier across+ // asynchronous workspace I/O. An unbound live notification+ // still surfaces the request when workspace lookup fails.+ match crate::config::active_workspace_snapshot().await {+ Ok((dir, revision)) => Some((crate::config::workspace_handle(&dir), revision)),+ Err(error) => {+ tracing::warn!(request_id = %request_id,+ "[approval::gate] could not resolve the active workspace for the flow approval notification ({error}); publishing it unbound");+ None+ }+ }+ },+ register,+ ).await;match registered {Err(resolution) => {return (@@ -584,61 +627,6 @@ impl ApprovalGate {Ok(Ok(())) => {}}- // Flow-origin surface bridge (flow-approval-surface, PR3): a flow run- // has no chat thread/client to route the generic `ApprovalRequested`- // through (both are `None` above, so the web-channel bridge silently- // drops it — see `web_chat::event_bus`'s- // `ApprovalSurfaceSubscriber`), which is exactly the silent-deadlock- // bug this correlation fixes. Broadcast a dedicated- // `flow_approval_request` socket event (no thread/client required,- // unlike the chat path) plus a `CoreNotification` with the three- // flow-scoped decision actions, so the Workflows UI can surface and- // resolve the park without polling.- if let Some(ApprovalSourceContext::Flow {- flow_id, run_id, ..- }) = &source_context- {- tracing::info!(- request_id = %request_id,- flow_id = %flow_id,- run_id = %run_id,- tool = tool_name,- "[approval::gate] flow-origin park — surfacing flow_approval_request + notification"- );- BUS.publish(DomainEvent::FlowApprovalRequested {- request_id: request_id.clone(),- flow_id: flow_id.clone(),- run_id: run_id.clone(),- tool_name: tool_name.to_string(),- summary: action_summary.to_string(),- agent_id: agent_id.clone(),- });- // The workspace the flow parked in, so the approval banner is- // dropped by a client that has since switched away rather than- // approving this workspace's call from another one. Fails open on- // a resolve failure: an unbound notification still reaches the- // user, whereas not publishing recreates the silent deadlock this- // bridge exists to fix.- let workspace = match crate::config::active_workspace_snapshot().await {- Ok((dir, revision)) => Some((crate::config::workspace_handle(&dir), revision)),- Err(error) => {- tracing::warn!(- request_id = %request_id,- "[approval::gate] could not resolve the active workspace for the flow approval notification ({error}); publishing it unbound"- );- None- }- };- publish_flow_gate_notification(- &request_id,- flow_id,- run_id,- tool_name,- action_summary,- workspace,- );- }-tracing::info!(request_id = %request_id,tool = tool_name,diff --git a/crates/openhuman-core/src/security/approval/mod.rs b/crates/openhuman-core/src/security/approval/mod.rsindex 030be04e7a..b3cb6840ed 100644--- a/crates/openhuman-core/src/security/approval/mod.rs+++ b/crates/openhuman-core/src/security/approval/mod.rs@@ -13,6 +13,7 @@//! list-based `ApprovalManager` that consumed it was removed once the gate//! became the sole control.+mod flow_surface;pub mod gate;pub mod redact;mod registration_scope;diff --git a/crates/openhuman-core/src/security/approval/registration_scope.rs b/crates/openhuman-core/src/security/approval/registration_scope.rsindex 3017d2f70d..a171e42729 100644--- a/crates/openhuman-core/src/security/approval/registration_scope.rs+++ b/crates/openhuman-core/src/security/approval/registration_scope.rs@@ -1,41 +1,39 @@//! Serializes an agent instance's approval registration and decisions with removal.-use std::sync::Mutex;+use std::sync::{Mutex, OnceLock};/// An instance-owned barrier; reusing an agent ID requires a fresh scope.#[derive(Debug, Default)]pub struct ApprovalScope {- closed: Mutex<Option<String>>,+ closed: Mutex<()>,+ reason: OnceLock<String>,}impl ApprovalScope {/// Stop registration and decisions; wait for accepted work to finish./// The first teardown reason remains authoritative.pub fn close(&self, reason: &str) {- let mut closed = self+ // Publish closure before waiting for accepted work. Turn admission and+ // callers waiting to acquire the barrier must already see removal.+ self.reason.get_or_init(|| reason.to_owned());+ let _closed = self.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- if closed.is_none() {- *closed = Some(reason.to_owned());- }}- /// Whether removal has closed this instance's registration and decision barrier.+ /// Whether closing has begun, without waiting for accepted work to finish.pub fn is_closed(&self) -> bool {- self.closed- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .is_some()+ self.reason.get().is_some()}/// Run synchronous registration or a decision while holding the removal barrier.pub(crate) fn with_open<T>(&self, register: impl FnOnce() -> T) -> Result<T, String> {- let closed = self+ let _closed = self.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- if let Some(reason) = closed.as_ref() {+ if let Some(reason) = self.reason.get() {return Err(reason.clone());}// Keep the barrier through persistence and approval event/waiter publication.diff --git a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs b/crates/openhuman-core/src/security/approval/registration_scope_tests.rsindex 7436514b9a..c358c94cea 100644--- a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs+++ b/crates/openhuman-core/src/security/approval/registration_scope_tests.rs@@ -1,6 +1,42 @@use super::ApprovalScope;use std::sync::{mpsc, Arc};+#[test]+fn closing_is_observable_before_an_accepted_registration_finishes() {+ let scope = Arc::new(ApprovalScope::default());+ let (entered_tx, entered_rx) = mpsc::channel();+ let (release_tx, release_rx) = mpsc::channel();+ let registering = scope.clone();+ let registration = std::thread::spawn(move || {+ registering.with_open(|| {+ entered_tx.send(()).unwrap();+ release_rx.recv().unwrap();+ })+ });+ entered_rx.recv().unwrap();+ let removing = scope.clone();+ let removal = std::thread::spawn(move || removing.close("agent_removed"));+ let (observed_tx, observed_rx) = mpsc::channel();+ let observing = scope.clone();+ let observation = std::thread::spawn(move || {+ while !observing.is_closed() {+ std::thread::yield_now();+ }+ observed_tx.send(()).unwrap();+ });+ // The registration stays suspended throughout this observation. A blocking+ // is_closed cannot report removal until the registration is released.+ let visible = observed_rx.recv_timeout(std::time::Duration::from_secs(2));+ release_tx.send(()).unwrap();+ assert_eq!(registration.join().unwrap(), Ok(()));+ removal.join().unwrap();+ observation.join().unwrap();+ assert!(+ visible.is_ok(),+ "removal stayed invisible behind registration"+ );+}+#[test]fn removal_refuses_late_registration_without_creating_a_pending_row() {let scope = ApprovalScope::default();diff --git a/crates/openhuman-embed/src/agent/lifecycle.rs b/crates/openhuman-embed/src/agent/lifecycle.rsindex d112e96360..28d1d3a5bb 100644--- a/crates/openhuman-embed/src/agent/lifecycle.rs+++ b/crates/openhuman-embed/src/agent/lifecycle.rs@@ -32,7 +32,7 @@ impl ApprovalState {.decisions.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- if self.claimed.load(Ordering::SeqCst) {+ if self.scope.is_closed() || self.claimed.load(Ordering::SeqCst) {None} else {Some(decide())@@ -40,13 +40,15 @@ impl ApprovalState {}fn claim_removal(&self, reason: &str) -> bool {+ // Publish closing before either mutex can block. Admission and all+ // approval surfaces share that irreversible, nonblocking observation.+ // Accepted core work finishes before the denial snapshot; accepted+ // facade work finishes before this caller can claim that snapshot.+ self.scope.close(reason);let _decision = self.decisions.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- // The shared gate closes before this claim becomes observable, so- // RPC/chat decisions cannot approve during the later denial snapshot.- self.scope.close(reason);!self.claimed.swap(true, Ordering::SeqCst)}}@@ -109,7 +111,7 @@ impl Lifecycle {let mut watcher = self.removed.subscribe();// Claiming removal closes admission immediately; waking existing turns// waits until their approvals have been settled with the removal reason.- if self.approvals.claimed.load(Ordering::SeqCst) || *watcher.borrow_and_update() {+ if self.approvals.scope.is_closed() || *watcher.borrow_and_update() {log::debug!("[embed][agent] turn refused: agent removed id={agent_id}");return Err(removed());}diff --git a/crates/openhuman-embed/src/agent/lifecycle_tests.rs b/crates/openhuman-embed/src/agent/lifecycle_tests.rsindex 85ce46721a..cc3e3390a2 100644--- a/crates/openhuman-embed/src/agent/lifecycle_tests.rs+++ b/crates/openhuman-embed/src/agent/lifecycle_tests.rs@@ -5,6 +5,54 @@ fn removed(outcome: Result<(), CoreError>) -> bool {matches!(outcome, Err(CoreError::AgentRemoved { ref agent_id, .. }) if agent_id == "a")}+#[tokio::test]+async fn removal_refuses_turns_while_an_accepted_facade_decision_is_still_running() {+ let lifecycle = Arc::new(Lifecycle::new());+ let approvals = lifecycle.approval_state();+ let deciding = approvals.clone();+ let (entered_tx, entered_rx) = std::sync::mpsc::channel();+ let (release_tx, release_rx) = std::sync::mpsc::channel();+ let decision = std::thread::spawn(move || {+ deciding.with_live(|| {+ entered_tx.send(()).unwrap();+ release_rx.recv().unwrap();+ 7+ })+ });+ entered_rx.recv().unwrap();+ let removing = lifecycle.clone();+ let removal = std::thread::spawn(move || removing.mark_removed("agent_removed"));+ // Closing is observable while the facade decision still owns its mutex;+ // the watch notification must wait for that accepted decision to finish.+ let closing = tokio::time::timeout(Duration::from_secs(2), async {+ while !lifecycle.approval_scope().is_closed() {+ tokio::task::yield_now().await;+ }+ })+ .await;+ let ran = AtomicBool::new(false);+ let outcome = lifecycle+ .admit("a", "test", async {+ ran.store(true, Ordering::SeqCst);+ Ok(())+ })+ .await;+ let notified = *lifecycle.removed().borrow();+ release_tx.send(()).unwrap();+ assert_eq!(decision.join().unwrap(), Some(7));+ assert!(removal.join().unwrap());+ assert!(+ closing.is_ok(),+ "closing waited for the facade decision mutex"+ );+ assert!(+ !notified,+ "accepted decision was not allowed to finish before notification"+ );+ assert!(removed(outcome));+ assert!(!ran.load(Ordering::SeqCst));+}+#[tokio::test]async fn a_live_agent_runs_its_turns() {let lifecycle = Lifecycle::new();diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex c0e04119f4..823ade21c3 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -659,7 +659,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent| 16.1.8 | MCP servers declared programmatically | RU | `crates/openhuman-embed/src/harness/mcp_tests.rs` | ✅ | stdio/HTTP transports mutually exclusive, enabled by default, env accumulation, allow/deny filters, auth carried through || 16.1.9 | Skill bundles installed into the workspace | RU | `crates/openhuman-embed/src/harness/skills_tests.rs` | ✅ | Copied not linked (discovery rejects symlinked bundles and manifests by design); symlinks skipped both as bundles and inside them; `Inherit` refuses the copy || 16.1.10 | One runtime per process | RU+RI | `crates/openhuman-embed/src/runtime/builder_tests.rs`, `crates/openhuman-embed/tests/harness_embed.rs` | ✅ | A second `Runtime` (or `Harness`) returns `AlreadyRunning` rather than sharing process-global keyring/event-bus/subscribers; a failed build releases the slot so a retry is possible |-| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs`, `crates/openhuman-embed/tests/agent_lifecycle.rs`, `crates/openhuman-core/src/security/approval/registration_scope_tests.rs`, `crates/openhuman-embed/src/agent/lifecycle_tests.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused; removal settles pending approvals with `agent_removed` before cancelling turns; a claimed removal immediately refuses new admission; instance-owned approval registration closes before the denial snapshot and rejects late registrations without persisting rows; polling and callback approval decisions serialize with the removal claim; the shared gate also refuses direct, agent-scoped and RPC decisions during the denial-snapshot gap |+| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs`, `crates/openhuman-embed/tests/agent_lifecycle.rs`, `crates/openhuman-core/src/security/approval/registration_scope_tests.rs`, `crates/openhuman-core/src/security/approval/flow_surface_tests.rs`, `crates/openhuman-embed/src/agent/lifecycle_tests.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused; removal settles pending approvals with `agent_removed` before cancelling turns; closing immediately refuses new admission even while an accepted registration or facade decision holds its barrier; instance-owned approval registration closes before the denial snapshot and rejects late registrations without persisting rows; polling and callback approval decisions serialize with the removal claim; the shared gate also refuses direct, agent-scoped and RPC decisions during the denial-snapshot gap; flow workspace resolution precedes registration, and registration publishes generic, flow and desktop approval surfaces together under the instance barrier || 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` || 16.1.14 | Host-owned tool policy extension | RI | `crates/openhuman-embed/tests/host_only_tools.rs` | ✅ | Host executors declare read-only requirements through the public `ToolPolicy` facade; HostOnly advertises the exact host catalog and refuses built-in shell/write attempts. Application-specific query validation and data handling belong to the host. || 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/turn_usage.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON; successful charged usage reaches outcome/meter, invalid buyer charges stay unknown, root overlays retain child spend and session context. |