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(webhooks): gate the unregister side-effect tail on a real removal, and stop clamping list_logs' limit to 1
M3gA-Mindd4354cb481d2
diff --git a/src/openhuman/skills/webhooks/README.md b/src/openhuman/skills/webhooks/README.mdindex 5003cad03c..6f7a2a18f5 100644--- a/src/openhuman/skills/webhooks/README.md+++ b/src/openhuman/skills/webhooks/README.md@@ -64,7 +64,7 @@ None. This domain owns no `tools.rs` agent tools.Subscriber (in `bus.rs`): **`WebhookRequestSubscriber`** — `name() = "webhook::request_handler"`, `domains() = ["webhook"]`. Registered at startup (see `channels/runtime/startup.rs`).- **Subscribes**: `DomainEvent::WebhookIncomingRequest` (published by the socket transport in `socket/event_handlers.rs`).-- **Publishes**: `DomainEvent::WebhookRegistered` / `WebhookUnregistered` (from the router on registration changes), `DomainEvent::WebhookReceived` (when routed to a target), `DomainEvent::WebhookProcessed` (always, with status/elapsed/error).+- **Publishes**: `DomainEvent::WebhookRegistered` / `WebhookUnregistered` (from the router on registration changes — `WebhookUnregistered`, the `registration_changed` debug event and the route re-persist all fire **only when a registration was actually removed**; unregistering an absent tunnel is a silent no-op that returns `Ok(false)`, see #6091), `DomainEvent::WebhookReceived` (when routed to a target), `DomainEvent::WebhookProcessed` (always, with status/elapsed/error).Routing outcomes by `target_kind`: `echo` → `build_echo_response` (200); `agent` → decode body, spawn triage, return `202 Accepted` (spawned task emits the real response later, with 60s timeout → 504); `skill` / unknown → `501` (direct skill dispatch not available); no registration → `404`. Responses are emitted over the socket as `webhook:response`.diff --git a/src/openhuman/skills/webhooks/ops.rs b/src/openhuman/skills/webhooks/ops.rsindex 6d837943cc..302ea87d9a 100644--- a/src/openhuman/skills/webhooks/ops.rs+++ b/src/openhuman/skills/webhooks/ops.rs@@ -126,11 +126,21 @@ pub async fn unregister_echo(tunnel_uuid: &str,) -> Result<RpcOutcome<WebhookDebugRegistrationsResult>, String> {let router = get_router().map_err(|e| format!("webhooks.unregister_echo failed: {e}"))?;- router.unregister(tunnel_uuid, "echo")?;+ let removed = router.unregister(tunnel_uuid, "echo")?;let registrations = router.list_all();+ // The wire shape is unchanged (#6091 leaves that a separate contract call):+ // the caller still gets the full registration list and can diff it. What+ // changes is that the log no longer claims a removal that did not happen.+ let log = if removed {+ format!("webhooks.unregister_echo removed tunnel {tunnel_uuid}")+ } else {+ format!(+ "webhooks.unregister_echo: no registration for tunnel {tunnel_uuid}, nothing removed"+ )+ };Ok(RpcOutcome::single_log(WebhookDebugRegistrationsResult { registrations },- format!("webhooks.unregister_echo removed tunnel {tunnel_uuid}"),+ log,))}diff --git a/src/openhuman/skills/webhooks/router.rs b/src/openhuman/skills/webhooks/router.rsindex 0d20ffd829..4ab959fb36 100644--- a/src/openhuman/skills/webhooks/router.rs+++ b/src/openhuman/skills/webhooks/router.rs@@ -220,27 +220,38 @@ impl WebhookRouter {}/// Unregister a tunnel. Only the owning skill can unregister it.- pub fn unregister(&self, tunnel_uuid: &str, skill_id: &str) -> Result<(), String> {+ /// Returns `Ok(true)` when a registration was actually removed and+ /// `Ok(false)` when `tunnel_uuid` had none — the caller's only way to tell+ /// a real removal from a no-op, since both are successful outcomes.+ ///+ /// The `registration_changed` push, the re-persist and the+ /// `WebhookUnregistered` bus event are all gated on a real removal (#6091).+ /// They used to run unconditionally, so unregistering a tunnel that was+ /// never registered announced a state change that never happened. This is+ /// the same gate [`Self::unregister_skill`] already applies with its+ /// `if !removed_tunnels.is_empty()`.+ pub fn unregister(&self, tunnel_uuid: &str, skill_id: &str) -> Result<bool, String> {let mut routes = self.routes.write().map_err(|e| e.to_string())?;- if let Some(existing) = routes.get(tunnel_uuid) {- if existing.skill_id != skill_id {- return Err(format!(- "Tunnel {} is owned by skill '{}'; skill '{}' cannot unregister it",- tunnel_uuid, existing.skill_id, skill_id- ));- }- debug!(- "[webhooks] Unregistering tunnel {} (skill '{}')",- tunnel_uuid, skill_id- );- routes.remove(tunnel_uuid);- } else {+ let Some(existing) = routes.get(tunnel_uuid) else {debug!("[webhooks] Tunnel {} not found for unregister (skill '{}')",tunnel_uuid, skill_id);+ return Ok(false);+ };++ if existing.skill_id != skill_id {+ return Err(format!(+ "Tunnel {} is owned by skill '{}'; skill '{}' cannot unregister it",+ tunnel_uuid, existing.skill_id, skill_id+ ));}+ debug!(+ "[webhooks] Unregistering tunnel {} (skill '{}')",+ tunnel_uuid, skill_id+ );+ routes.remove(tunnel_uuid);drop(routes);self.publish_event("registration_changed", None, Some(tunnel_uuid.to_string()));@@ -251,7 +262,7 @@ impl WebhookRouter {skill_id: skill_id.to_string(),});- Ok(())+ Ok(true)}/// Remove all tunnel registrations for a skill (called on skill stop/crash).@@ -455,8 +466,12 @@ impl WebhookRouter {}/// List recent webhook logs, newest first.+ /// `limit` is a **maximum**, so an explicit `Some(0)` returns nothing. The+ /// absent case is covered by `unwrap_or(100)`; there is deliberately no+ /// `.max(1)` clamp, which could only ever have rewritten a caller's `0`+ /// into a `1` (#6090). `Iterator::take(0)` is well-defined.pub fn list_logs(&self, limit: Option<usize>) -> Vec<WebhookDebugLogEntry> {- let limit = limit.unwrap_or(100).max(1);+ let limit = limit.unwrap_or(100);self.debug_logs.read().map(|logs| logs.iter().take(limit).cloned().collect())diff --git a/src/openhuman/skills/webhooks/router_tests.rs b/src/openhuman/skills/webhooks/router_tests.rsindex 43bf439af0..ecbe766a67 100644--- a/src/openhuman/skills/webhooks/router_tests.rs+++ b/src/openhuman/skills/webhooks/router_tests.rs@@ -291,8 +291,116 @@ fn persist_and_load_roundtrip() {#[test]fn unregister_nonexistent_tunnel_is_noop() {let router = WebhookRouter::new(None);- // Should not error even though tunnel doesn't exist- router.unregister("no-such", "any-skill").unwrap();+ // Should not error even though tunnel doesn't exist, and must report that+ // it removed nothing rather than being indistinguishable from a real+ // removal (#6091).+ assert!(!router.unregister("no-such", "any-skill").unwrap());+}++/// #6091 — unregistering a tunnel that was never registered must not announce a+/// state change.+///+/// `publish_event`, `persist` and the `WebhookUnregistered` bus publish used to+/// run unconditionally after the not-found branch, so a caller with a typo'd+/// UUID made every subscriber believe a registration had been torn down. The+/// `registration_changed` debug event is the observable one from a sync test+/// (the bus needs an async `bus::init`), and all three sit on the same branch,+/// so gating is proven by any one of them.+///+/// `WEBHOOK_DEBUG_EVENTS` is a **process-global** `broadcast::Sender` shared by+/// every `WebhookRouter`, not a per-instance channel, so a sibling test running+/// concurrently also lands events in this receiver. The assertions therefore+/// filter on this test's own tunnel UUIDs rather than on the channel being+/// empty, which would be flaky.+#[test]+fn unregister_of_an_absent_tunnel_announces_nothing() {+ const ABSENT: &str = "uuid-6091-never-registered";+ const PRESENT: &str = "uuid-6091-present";++ let router = WebhookRouter::new(None);+ router.register(PRESENT, "gmail", None, None).unwrap();++ /// Drain everything queued and report which of our two UUIDs were announced.+ fn drain(rx: &mut broadcast::Receiver<WebhookDebugEvent>) -> Vec<String> {+ let mut seen = Vec::new();+ while let Ok(event) = rx.try_recv() {+ if event.event_type != "registration_changed" {+ continue;+ }+ match event.tunnel_uuid.as_deref() {+ Some(uuid) if uuid == ABSENT || uuid == PRESENT => seen.push(uuid.to_string()),+ _ => {}+ }+ }+ seen+ }++ // Subscribe *after* the register so the setup's own event is not counted.+ let mut rx = router.subscribe_debug_events();++ assert!(+ !router.unregister(ABSENT, "echo").unwrap(),+ "unregistering an absent tunnel must report that nothing was removed"+ );+ assert_eq!(+ drain(&mut rx),+ Vec::<String>::new(),+ "an absent tunnel must publish no registration_changed event"+ );+ assert_eq!(+ router.list_all().len(),+ 1,+ "the unrelated registration must be untouched"+ );++ // A real removal still announces, so the gate is not simply switched off.+ assert!(+ router.unregister(PRESENT, "gmail").unwrap(),+ "removing a real registration must report true"+ );+ assert_eq!(+ drain(&mut rx),+ vec![PRESENT.to_string()],+ "a real removal must publish exactly one registration_changed for it"+ );+ assert!(router.list_all().is_empty());+}++/// #6090 — `limit` is a maximum, so an explicit zero returns nothing.+///+/// `list_logs` used to clamp with `.max(1)`, which could only ever rewrite a+/// caller-supplied `0` into a `1`; `limit: 0` and `limit: 1` were+/// indistinguishable while every other value was honoured exactly.+#[test]+fn list_logs_limit_zero_returns_no_entries() {+ let router = WebhookRouter::new(None);+ for i in 0..3 {+ router.record_request(+ &WebhookRequest {+ correlation_id: format!("corr-limit-{i}"),+ tunnel_id: "tunnel-limit".to_string(),+ tunnel_uuid: "uuid-limit".to_string(),+ tunnel_name: "Limit".to_string(),+ method: "POST".to_string(),+ path: "/hooks/limit".to_string(),+ headers: HashMap::new(),+ query: HashMap::new(),+ body: String::new(),+ },+ None,+ );+ }++ assert!(+ router.list_logs(Some(0)).is_empty(),+ "limit 0 is a maximum of zero: {:?}",+ router.list_logs(Some(0)).len()+ );+ // The neighbouring values must keep working — the clamp's removal must not+ // have shifted anything else.+ assert_eq!(router.list_logs(Some(1)).len(), 1);+ assert_eq!(router.list_logs(Some(2)).len(), 2);+ assert_eq!(router.list_logs(None).len(), 3);}#[test]diff --git a/tests/raw_coverage/webhooks_ingress_e2e.rs b/tests/raw_coverage/webhooks_ingress_e2e.rsindex ca5db505b5..fedfa3fe14 100644--- a/tests/raw_coverage/webhooks_ingress_e2e.rs+++ b/tests/raw_coverage/webhooks_ingress_e2e.rs@@ -581,6 +581,31 @@ async fn webhooks_registration_lifecycle_and_ownership_guards() {"unregister_echo must not touch the sibling agent tunnel: {result}");+ // ── #6091: unregistering a tunnel that was never registered must not claim it removed+ // one. The wire shape is deliberately unchanged (the caller still diffs `registrations`),+ // so the log line is the observable signal that the no-op branch was taken.+ let absent = post_json_rpc(+ &rpc_base,+ 7008,+ "openhuman.webhooks_unregister_echo",+ json!({ "tunnel_uuid": "e2e-never-registered-tunnel" }),+ )+ .await;+ let envelope = assert_no_jsonrpc_error(&absent, "webhooks_unregister_echo (absent tunnel)");+ let logs = envelope+ .get("logs")+ .and_then(Value::as_array)+ .expect("unregister_echo carries a log line");+ let line = logs[0].as_str().unwrap_or_default();+ assert!(+ line.contains("nothing removed"),+ "an absent tunnel must be reported as a no-op, not as a removal: {line}"+ );+ assert!(+ registration(peel(envelope), agent_uuid).is_some(),+ "the no-op must leave the unrelated agent tunnel registered: {envelope}"+ );+// ── a missing required param is a params error, not a panic or a silent success.let bad = post_json_rpc(&rpc_base,@@ -678,6 +703,37 @@ async fn webhooks_debug_log_ring_records_and_clears() {"no response recorded yet ⇒ status_code must still be null: {entry}");+ // #6090 — `limit` is a maximum, so an explicit zero returns nothing. The ring holds one+ // entry at this point, so a `.max(1)`-style clamp would return that entry and this fails.+ let zero = post_json_rpc(+ &rpc_base,+ 7106,+ "openhuman.webhooks_list_logs",+ json!({ "limit": 0 }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&zero, "webhooks_list_logs (limit 0)"));+ assert_eq!(+ result.get("logs").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "limit 0 must return no entries, not one: {result}"+ );+ // The neighbouring value must still be honoured, so this cannot pass by returning+ // nothing for every limit.+ let one = post_json_rpc(+ &rpc_base,+ 7107,+ "openhuman.webhooks_list_logs",+ json!({ "limit": 1 }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&one, "webhooks_list_logs (limit 1)"));+ assert_eq!(+ result.get("logs").and_then(Value::as_array).map(Vec::len),+ Some(1),+ "limit 1 must still return the single recorded entry: {result}"+ );+// clear_logs reports the count it removed, and the ring is empty afterwards.let cleared = post_json_rpc(&rpc_base, 7104, "openhuman.webhooks_clear_logs", json!({})).await;let result = peel(assert_no_jsonrpc_error(&cleared, "webhooks_clear_logs"));