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(e2e): cover 39 uncovered controllers across webhooks, socket, channel and the notification platform
M3gA-Mind1112169b4eb5
diff --git a/tests/raw_coverage/channel_socket_e2e.rs b/tests/raw_coverage/channel_socket_e2e.rsnew file mode 100644index 0000000000..bc357b2f4b--- /dev/null+++ b/tests/raw_coverage/channel_socket_e2e.rs@@ -0,0 +1,677 @@+//! End-to-end coverage for the `socket` namespace (5 controllers, 0% before this file) and the+//! three uncovered `channel` queue controllers.+//!+//! ## Why the socket cases look the way they do+//!+//! `socket_*` operates on a **process-global** `SocketManager` (`OnceLock`), and this file is a+//! module of the aggregated `raw_coverage_all` binary — so it shares that manager with+//! `connectivity_raw_coverage_e2e.rs`, which asserts `socket_state == "disconnected"`, and with+//! `webhooks_ingress_e2e.rs`, which hangs its router off it. Every case here therefore:+//!+//! * holds `crate::SHARED_ENV_LOCK` for its whole body — the same lock the connectivity suite+//! holds across its socket-state assertion, which is what keeps the two from interleaving;+//! * offers a manager via `set_global_socket_manager` but reads back whatever is installed,+//! since the `OnceLock` may already be owned by a sibling suite;+//! * leaves the manager **disconnected** on the way out, so the next suite sees the state it+//! expects.+//!+//! No case dials a real backend: `connect` spawns a background reconnect loop, so the one case+//! that connects points at a closed loopback port and tears the loop down immediately.+//!+//! Run with:+//! ~/tinyhuman/ci-slot.sh cargo test --test raw_coverage_all \+//! --features "$(bash scripts/ci/product-features.sh)" channel_socket++use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode};+use axum::routing::get;+use axum::{Json, Router};+use serde_json::{json, Value};+use tempfile::tempdir;++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token};+use openhuman_core::core::jsonrpc::build_core_http_router;+use openhuman_core::openhuman::platform::socket::{+ global_socket_manager, set_global_socket_manager, SocketManager,+};++// ── env serialisation ────────────────────────────────────────────────────────++static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++fn socket_e2e_env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++const TEST_JWT: &str = "e2e-channel-socket-jwt";++/// The bearer every request in this file sends.+///+/// **Read back, never asserted.** `RPC_TOKEN` in `core::auth` is a process-global `OnceLock` and+/// this file shares its process with every other aggregated suite, several of which also call+/// `init_rpc_token`. Whichever runs first fixes the token for the whole binary and every later+/// `init_rpc_token` is a documented no-op — so a suite that hard-codes its own literal and sends+/// that would 401 whenever it lost the race. Initialising and then asking `get_rpc_token()` for+/// the value that actually took is correct either way round.+fn rpc_bearer() -> &'static str {+ static BEARER: OnceLock<&'static str> = OnceLock::new();+ BEARER.get_or_init(|| {+ let token_dir = std::env::temp_dir().join("openhuman-channel-socket-e2e-auth");+ std::fs::create_dir_all(&token_dir).expect("rpc token dir");+ init_rpc_token(&token_dir).expect("init rpc token for channel_socket_e2e");+ get_rpc_token().expect("an RPC token is initialised for this process")+ })+}++fn ensure_rpc_auth() {+ let _ = rpc_bearer();+}++/// Ensure a global `SocketManager` exists and return the one that is actually installed.+///+/// The `OnceLock` may already be owned by a sibling suite in this binary; `set` is then a logged+/// no-op, so the return value — not the argument — is the object the RPC handlers will resolve.+fn installed_socket_manager() -> &'static Arc<SocketManager> {+ set_global_socket_manager(Arc::new(SocketManager::new()));+ global_socket_manager().expect("a global SocketManager after set_global_socket_manager")+}++struct EnvGuard {+ key: &'static str,+ prev: Option<String>,+}++impl EnvGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let prev = std::env::var(key).ok();+ std::env::set_var(key, path.as_os_str());+ Self { key, prev }+ }++ fn unset(key: &'static str) -> Self {+ let prev = std::env::var(key).ok();+ std::env::remove_var(key);+ Self { key, prev }+ }+}++impl Drop for EnvGuard {+ fn drop(&mut self) {+ match &self.prev {+ Some(v) => std::env::set_var(self.key, v),+ None => std::env::remove_var(self.key),+ }+ }+}++// ── minimal mock backend ─────────────────────────────────────────────────────++async fn mock_current_user(headers: HeaderMap) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ let authed = headers+ .get(AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .map(|v| v == format!("Bearer {TEST_JWT}"))+ .unwrap_or(false);+ if !authed {+ return Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "unauthorized" })),+ ));+ }+ Ok(Json(json!({+ "success": true,+ "data": { "_id": "channel-socket-e2e-user", "username": "channel-socket-e2e" }+ })))+}++fn mock_backend_router() -> Router {+ Router::new()+ .route("/settings", get(mock_current_user))+ .route("/auth/me", get(mock_current_user))+}++async fn serve_ephemeral(app: Router) -> (SocketAddr, tokio::task::JoinHandle<()>) {+ ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind ephemeral port");+ let addr = listener.local_addr().expect("local addr");+ let handle = tokio::spawn(async move {+ axum::serve(listener, app).await.ok();+ });+ (addr, handle)+}++/// Bind an ephemeral port, read it, then drop the listener — so the address is well-formed and+/// reliably *closed*. `socket_connect` against it fails at TCP, which is what keeps the spawned+/// reconnect loop from ever reaching a real handshake.+async fn closed_loopback_addr() -> SocketAddr {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind for a closed port");+ let addr = listener.local_addr().expect("local addr");+ drop(listener);+ addr+}++fn write_test_config(openhuman_dir: &Path, api_origin: &str) {+ let cfg = format!(+ r#"api_url = "{api_origin}"+default_model = "e2e-mock-model"+default_temperature = 0.7+chat_onboarding_completed = true++[secrets]+encrypt = false+"#+ );+ fn write_cfg(dir: &Path, cfg: &str) {+ std::fs::create_dir_all(dir).expect("mkdir config dir");+ std::fs::write(dir.join("config.toml"), cfg).expect("write config.toml");+ }+ write_cfg(openhuman_dir, &cfg);+ write_cfg(&openhuman_dir.join("users").join("local"), &cfg);+ write_cfg(+ &openhuman_dir.join("users").join("channel-socket-e2e-user"),+ &cfg,+ );+}++async fn post_json_rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("reqwest client");+ let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let resp = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", rpc_bearer()))+ .json(&body)+ .send()+ .await+ .unwrap_or_else(|e| panic!("POST {url}: {e}"));+ assert!(+ resp.status().is_success(),+ "HTTP error {} calling {method}",+ resp.status()+ );+ resp.json::<Value>()+ .await+ .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))+}++fn assert_no_jsonrpc_error<'a>(v: &'a Value, ctx: &str) -> &'a Value {+ if let Some(err) = v.get("error") {+ panic!("{ctx}: unexpected JSON-RPC error: {err}");+ }+ v.get("result")+ .unwrap_or_else(|| panic!("{ctx}: missing result field: {v}"))+}++fn jsonrpc_error_message(v: &Value, ctx: &str) -> String {+ let err = v+ .get("error")+ .unwrap_or_else(|| panic!("{ctx}: expected a JSON-RPC error, got: {v}"));+ err.get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{ctx}: error had no message: {err}"))+ .to_string()+}++fn peel(v: &Value) -> &Value {+ if v.get("logs").is_some() {+ v.get("result").unwrap_or(v)+ } else {+ v+ }+}++/// Boilerplate every case shares: temp HOME, mock backend, config, core RPC server.+struct Harness {+ rpc_base: String,+ mock_join: tokio::task::JoinHandle<()>,+ rpc_join: tokio::task::JoinHandle<()>,+ _home: EnvGuard,+ _ws: EnvGuard,+ _backend: EnvGuard,+ _vite: EnvGuard,+ _tmp: tempfile::TempDir,+}++impl Harness {+ async fn start() -> Self {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path().to_path_buf();+ let openhuman_home = home.join(".openhuman");+ let _home = EnvGuard::set_to_path("HOME", &home);+ let _ws = EnvGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend = EnvGuard::unset("BACKEND_URL");+ let _vite = EnvGuard::unset("VITE_BACKEND_URL");++ let (mock_addr, mock_join) = serve_ephemeral(mock_backend_router()).await;+ write_test_config(&openhuman_home, &format!("http://{mock_addr}"));++ let (rpc_addr, rpc_join) = serve_ephemeral(build_core_http_router(false)).await;+ Self {+ rpc_base: format!("http://{rpc_addr}"),+ mock_join,+ rpc_join,+ _home,+ _ws,+ _backend,+ _vite,+ _tmp: tmp,+ }+ }++ fn stop(self) {+ self.mock_join.abort();+ self.rpc_join.abort();+ }+}++// ── socket namespace ─────────────────────────────────────────────────────────++/// `socket_state` reports the manager's real state, and both its param-validation guards fire+/// before anything touches the network.+///+/// Covers: `openhuman.socket_state`, `openhuman.socket_connect`, `openhuman.socket_emit`.+#[tokio::test]+async fn socket_state_and_parameter_guards() {+ let _env_lock = socket_e2e_env_lock();+ let manager = installed_socket_manager();+ // Start from a known state regardless of what a sibling suite left behind.+ manager.disconnect().await.expect("baseline disconnect");++ let h = Harness::start().await;++ let state = post_json_rpc(&h.rpc_base, 8001, "openhuman.socket_state", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&state, "socket_state"));+ assert_eq!(+ result.get("status").and_then(Value::as_str),+ Some("disconnected"),+ "socket_state serialises ConnectionStatus through serde (lowercase): {result}"+ );+ assert!(+ result.get("socket_id").map(Value::is_null).unwrap_or(false),+ "a disconnected manager has no socket id: {result}"+ );++ // `connect` requires both params, and reports which one is missing.+ let no_url = post_json_rpc(+ &h.rpc_base,+ 8002,+ "openhuman.socket_connect",+ json!({ "token": "t" }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&no_url, "socket_connect without url")+ .contains("missing required param 'url'"),+ "socket_connect must name the missing param"+ );++ let no_token = post_json_rpc(+ &h.rpc_base,+ 8003,+ "openhuman.socket_connect",+ json!({ "url": "ws://127.0.0.1:1" }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&no_token, "socket_connect without token")+ .contains("missing required param 'token'"),+ "socket_connect must name the missing param"+ );++ // An empty token is refused *before* a reconnect loop is spawned — the guard that keeps an+ // unauthenticated core from producing a 401 retry storm.+ let empty_token = post_json_rpc(+ &h.rpc_base,+ 8004,+ "openhuman.socket_connect",+ json!({ "url": "ws://127.0.0.1:1", "token": " " }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&empty_token, "socket_connect with a blank token")+ .contains("empty session token"),+ "a whitespace-only token must be rejected, not optimistically reported as Connecting"+ );++ let still_down = post_json_rpc(&h.rpc_base, 8005, "openhuman.socket_state", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&still_down, "socket_state after guards"));+ assert_eq!(+ result.get("status").and_then(Value::as_str),+ Some("disconnected"),+ "a rejected connect must not have moved the manager out of Disconnected: {result}"+ );++ // `emit` on a manager that has never connected has no channel to write to.+ let emit_offline = post_json_rpc(+ &h.rpc_base,+ 8006,+ "openhuman.socket_emit",+ json!({ "event": "test:event", "data": { "k": "v" } }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&emit_offline, "socket_emit while disconnected").contains("Not connected"),+ "emitting with no connection must be an error, not a silent success"+ );++ let emit_no_event = post_json_rpc(+ &h.rpc_base,+ 8007,+ "openhuman.socket_emit",+ json!({ "data": { "k": "v" } }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&emit_no_event, "socket_emit without event")+ .contains("missing required param 'event'"),+ "socket_emit must name the missing param"+ );++ manager.disconnect().await.expect("teardown disconnect");+ h.stop();+}++/// `socket_connect` → `socket_disconnect` moves the manager through Connecting and back.+///+/// The target is a loopback port that was bound and released, so the spawned `ws_loop` fails at+/// TCP and never reaches a handshake; `disconnect` then tears it down. This is the whole+/// observable lifecycle of the two controllers without a backend.+///+/// Covers: `openhuman.socket_connect`, `openhuman.socket_disconnect`, `openhuman.socket_state`.+#[tokio::test]+async fn socket_connect_then_disconnect_round_trips_state() {+ let _env_lock = socket_e2e_env_lock();+ let manager = installed_socket_manager();+ manager.disconnect().await.expect("baseline disconnect");++ let h = Harness::start().await;+ let dead = closed_loopback_addr().await;++ let connected = post_json_rpc(+ &h.rpc_base,+ 8101,+ "openhuman.socket_connect",+ json!({ "url": format!("ws://{dead}"), "token": "e2e-socket-token" }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&connected, "socket_connect"));+ assert_eq!(+ result.get("status").and_then(Value::as_str),+ Some("Connecting"),+ "connect returns as soon as the loop is spawned, in the Connecting state. NOTE the \+ capitalisation: this handler formats the status with `{{:?}}` while `socket_state` \+ serialises it through serde (lowercase `connecting`). See \+ bugs/e2e-wave-socket-status-casing-split.md: {result}"+ );++ let disconnected = post_json_rpc(&h.rpc_base, 8102, "openhuman.socket_disconnect", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&disconnected, "socket_disconnect"));+ assert_eq!(+ result.get("status").and_then(Value::as_str),+ Some("Disconnected"),+ "disconnect must report the manager back at rest: {result}"+ );++ let state = post_json_rpc(&h.rpc_base, 8103, "openhuman.socket_state", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&state, "socket_state after disconnect"));+ assert_eq!(+ result.get("status").and_then(Value::as_str),+ Some("disconnected"),+ "state must agree with disconnect's own report (modulo the casing split): {result}"+ );+ assert!(+ result.get("socket_id").map(Value::is_null).unwrap_or(false),+ "disconnect clears the socket id: {result}"+ );++ manager.disconnect().await.expect("teardown disconnect");+ h.stop();+}++/// `socket_connect_with_session` refuses before it dials when no session JWT is stored, and+/// resolves the stored one when there is.+///+/// Covers: `openhuman.socket_connect_with_session`.+#[tokio::test]+async fn socket_connect_with_session_requires_a_stored_session() {+ let _env_lock = socket_e2e_env_lock();+ let manager = installed_socket_manager();+ manager.disconnect().await.expect("baseline disconnect");++ let h = Harness::start().await;++ // No session stored yet: the credential lookup, not the socket, is what fails.+ let no_session = post_json_rpc(+ &h.rpc_base,+ 8201,+ "openhuman.socket_connect_with_session",+ json!({}),+ )+ .await;+ let message = jsonrpc_error_message(&no_session, "socket_connect_with_session, signed out");+ assert!(+ message.contains("no session token stored"),+ "the error must say the user has to log in first, got: {message}"+ );++ let state = post_json_rpc(&h.rpc_base, 8202, "openhuman.socket_state", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&state, "socket_state"));+ assert_eq!(+ result.get("status").and_then(Value::as_str),+ Some("disconnected"),+ "the refused connect must not have spawned a loop: {result}"+ );++ // With a session stored, the same call gets past the credential guard and spawns the loop+ // against the mock origin — which speaks HTTP, not Socket.IO, so it never handshakes.+ let store = post_json_rpc(+ &h.rpc_base,+ 8203,+ "openhuman.auth_store_session",+ json!({ "token": TEST_JWT, "user_id": "channel-socket-e2e-user" }),+ )+ .await;+ assert_no_jsonrpc_error(&store, "auth_store_session");++ let with_session = post_json_rpc(+ &h.rpc_base,+ 8204,+ "openhuman.socket_connect_with_session",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(+ &with_session,+ "socket_connect_with_session, signed in",+ ));+ assert_eq!(+ result.get("status").and_then(Value::as_str),+ Some("Connecting"),+ "a stored session must get past the guard and start the loop: {result}"+ );++ let stopped = post_json_rpc(&h.rpc_base, 8205, "openhuman.socket_disconnect", json!({})).await;+ assert_eq!(+ peel(assert_no_jsonrpc_error(&stopped, "socket_disconnect"))+ .get("status")+ .and_then(Value::as_str),+ Some("Disconnected")+ );++ manager.disconnect().await.expect("teardown disconnect");+ h.stop();+}++// ── channel queue controllers ────────────────────────────────────────────────++/// The three queue/cancel controllers on a thread with no in-flight turn.+///+/// This is the branch every one of them takes whenever the UI polls a quiet thread — the common+/// case, and the one whose *content* nobody was checking: each returns a fully-populated payload+/// (`active`/`cleared`/`cancelled` false, all counters zero) rather than an error or an empty+/// object, and each echoes the **trimmed** thread id back.+///+/// Covers: `openhuman.channel_web_queue_status`, `openhuman.channel_web_queue_clear`,+/// `openhuman.channel_web_cancel`.+#[tokio::test]+async fn channel_queue_controllers_report_an_idle_thread() {+ let _env_lock = socket_e2e_env_lock();+ let h = Harness::start().await;++ // Leading/trailing whitespace is deliberate: the handlers trim before echoing, and a caller+ // that keys UI state on the returned id needs that to be the canonical form.+ let padded = " e2e-idle-thread ";+ let canonical = "e2e-idle-thread";++ let status = post_json_rpc(+ &h.rpc_base,+ 8301,+ "openhuman.channel_web_queue_status",+ json!({ "thread_id": padded }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&status, "channel_web_queue_status"));+ assert_eq!(+ result.get("thread_id").and_then(Value::as_str),+ Some(canonical),+ "queue_status must echo the trimmed thread id: {result}"+ );+ assert_eq!(+ result.get("active").and_then(Value::as_bool),+ Some(false),+ "no in-flight turn ⇒ active=false: {result}"+ );+ for counter in ["steers", "followups", "collects", "total"] {+ assert_eq!(+ result.get(counter).and_then(Value::as_u64),+ Some(0),+ "an idle thread must report {counter}=0, and must report it at all: {result}"+ );+ }+ assert!(+ result.get("request_id").is_none(),+ "the idle branch omits request_id entirely rather than sending a null: {result}"+ );++ let cleared = post_json_rpc(+ &h.rpc_base,+ 8302,+ "openhuman.channel_web_queue_clear",+ json!({ "thread_id": padded }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&cleared, "channel_web_queue_clear"));+ assert_eq!(+ result.get("thread_id").and_then(Value::as_str),+ Some(canonical)+ );+ assert_eq!(+ result.get("cleared").and_then(Value::as_bool),+ Some(false),+ "clearing a thread with no queue must report cleared=false, not a cheerful true: {result}"+ );+ assert_eq!(result.get("dropped").and_then(Value::as_u64), Some(0));++ let cancelled = post_json_rpc(+ &h.rpc_base,+ 8303,+ "openhuman.channel_web_cancel",+ json!({ "client_id": " e2e-client ", "thread_id": padded }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&cancelled, "channel_web_cancel"));+ assert_eq!(+ result.get("cancelled").and_then(Value::as_bool),+ Some(false),+ "cancelling an idle thread must report that nothing was cancelled: {result}"+ );+ assert_eq!(+ result.get("client_id").and_then(Value::as_str),+ Some("e2e-client"),+ "cancel must echo the trimmed client id: {result}"+ );+ assert_eq!(+ result.get("thread_id").and_then(Value::as_str),+ Some(canonical)+ );+ assert!(+ result+ .get("request_id")+ .map(Value::is_null)+ .unwrap_or(false),+ "nothing was cancelled ⇒ request_id is null: {result}"+ );++ // A request-scoped cancel for a turn that does not exist is also a no-op, not an error —+ // the stale-cancel path from #4760.+ let scoped = post_json_rpc(+ &h.rpc_base,+ 8304,+ "openhuman.channel_web_cancel",+ json!({ "client_id": "e2e-client", "thread_id": canonical, "request_id": "req-that-never-ran" }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&scoped, "channel_web_cancel scoped"));+ assert_eq!(result.get("cancelled").and_then(Value::as_bool), Some(false));++ h.stop();+}++/// Every queue controller rejects a params object missing a required field, before it touches+/// the in-flight map.+///+/// The refusal comes from `core::all::validate_params`, which type- and presence-checks against+/// the declared `ControllerSchema` *before* dispatch — so the message names the field and its+/// schema comment rather than surfacing a serde error from the handler.+#[tokio::test]+async fn channel_queue_controllers_reject_missing_thread_id() {+ let _env_lock = socket_e2e_env_lock();+ let h = Harness::start().await;++ for (id, method, params) in [+ (8401, "openhuman.channel_web_queue_status", json!({})),+ (8402, "openhuman.channel_web_queue_clear", json!({})),+ (+ 8403,+ "openhuman.channel_web_cancel",+ json!({ "client_id": "c" }),+ ),+ ] {+ let response = post_json_rpc(&h.rpc_base, id, method, params).await;+ let message = jsonrpc_error_message(&response, method);+ assert!(+ message.contains("missing required param 'thread_id'"),+ "{method} must name the missing field, got: {message}"+ );+ }++ // `channel_web_cancel` needs a client_id too — the pair is what scopes a cancel.+ let no_client = post_json_rpc(+ &h.rpc_base,+ 8404,+ "openhuman.channel_web_cancel",+ json!({ "thread_id": "t" }),+ )+ .await;+ let message = jsonrpc_error_message(&no_client, "channel_web_cancel without client_id");+ assert!(+ message.contains("missing required param 'client_id'"),+ "cancel must require the client id that scopes it, got: {message}"+ );++ h.stop();+}diff --git a/tests/raw_coverage/notification_platform_e2e.rs b/tests/raw_coverage/notification_platform_e2e.rsnew file mode 100644index 0000000000..4882525bf8--- /dev/null+++ b/tests/raw_coverage/notification_platform_e2e.rs@@ -0,0 +1,1534 @@+//! End-to-end coverage for the notification centre and the small platform namespaces that had no+//! e2e target at all: `notification` (7 uncovered), `health` (2), `doctor` (2), `service`'s+//! daemon-host pair, `provider_surfaces` (2), `slack_memory` (2) and `announcements` (1).+//!+//! Everything here goes over the real JSON-RPC surface (`build_core_http_router`) against an+//! in-process axum mock for the hosted backend. Nothing reaches the network.+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target, so it shares one process+//! with ~76 sibling suites and libtest runs them concurrently. Every case that mutates+//! process-global env (`HOME`, `BACKEND_URL`, …) holds `crate::SHARED_ENV_LOCK`, and the two+//! process-global registries touched here — the health component registry and the+//! `provider_surfaces` respond queue — are addressed with keys unique to this file so a sibling+//! suite's rows cannot make an assertion here pass or fail by accident.+//!+//! Run with:+//! ~/tinyhuman/ci-slot.sh cargo test --test raw_coverage_all \+//! --features "$(bash scripts/ci/product-features.sh)" notification_platform++use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++use axum::extract::State;+use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode};+use axum::routing::get;+use axum::{Json, Router};+use serde_json::{json, Value};+use tempfile::tempdir;++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token};+use openhuman_core::core::jsonrpc::build_core_http_router;+use openhuman_core::openhuman::config::rpc::load_config_with_timeout;+use openhuman_core::openhuman::desktop::notifications::store as notification_store;+use openhuman_core::openhuman::desktop::notifications::types::{+ CoreNotificationCategory, CoreNotificationEvent,+};+use openhuman_core::openhuman::platform::health::{mark_component_error, mark_component_ok};++// ── env serialisation ────────────────────────────────────────────────────────++static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++fn platform_e2e_env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++const TEST_JWT: &str = "e2e-notification-platform-jwt";+const TEST_USER: &str = "notification-platform-e2e-user";++/// The bearer every request in this file sends.+///+/// **Read back, never asserted.** `RPC_TOKEN` in `core::auth` is a process-global `OnceLock` and+/// this file shares its process with every other aggregated suite, several of which also call+/// `init_rpc_token`. Whichever runs first fixes the token for the whole binary and every later+/// `init_rpc_token` is a documented no-op — so a suite that hard-codes its own literal and sends+/// that would 401 whenever it lost the race. Initialising and then asking `get_rpc_token()` for+/// the value that actually took is correct either way round.+fn rpc_bearer() -> &'static str {+ static BEARER: OnceLock<&'static str> = OnceLock::new();+ BEARER.get_or_init(|| {+ let token_dir = std::env::temp_dir().join("openhuman-notification-platform-e2e-auth");+ std::fs::create_dir_all(&token_dir).expect("rpc token dir");+ init_rpc_token(&token_dir).expect("init rpc token for notification_platform_e2e");+ get_rpc_token().expect("an RPC token is initialised for this process")+ })+}++fn ensure_rpc_auth() {+ let _ = rpc_bearer();+}++struct EnvGuard {+ key: &'static str,+ prev: Option<String>,+}++impl EnvGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let prev = std::env::var(key).ok();+ std::env::set_var(key, path.as_os_str());+ Self { key, prev }+ }++ fn unset(key: &'static str) -> Self {+ let prev = std::env::var(key).ok();+ std::env::remove_var(key);+ Self { key, prev }+ }+}++impl Drop for EnvGuard {+ fn drop(&mut self) {+ match &self.prev {+ Some(v) => std::env::set_var(self.key, v),+ None => std::env::remove_var(self.key),+ }+ }+}++// ── mock backend ─────────────────────────────────────────────────────────────++/// What the mock should answer on `GET /announcements/latest`.+#[derive(Clone, Copy, PartialEq, Eq)]+enum AnnouncementMode {+ /// Return a real announcement object.+ Present,+ /// Return 404 — the "no announcement for this user" case the adapter folds into `null`.+ NotFound,+}++#[derive(Clone)]+struct BackendState {+ announcement: AnnouncementMode,+ /// Rows served by `GET /agent-integrations/composio/connections`.+ connections: Arc<Value>,+}++fn unauthorized() -> (StatusCode, Json<Value>) {+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "unauthorized" })),+ )+}++fn is_authed(headers: &HeaderMap) -> bool {+ headers+ .get(AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .map(|v| v == format!("Bearer {TEST_JWT}"))+ .unwrap_or(false)+}++async fn mock_current_user(headers: HeaderMap) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ Ok(Json(json!({+ "success": true,+ "data": { "_id": TEST_USER, "username": "notification-platform-e2e" }+ })))+}++async fn mock_announcements_latest(+ State(state): State<BackendState>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ match state.announcement {+ AnnouncementMode::Present => Ok(Json(json!({+ "success": true,+ "data": {+ "id": "ann-1",+ "title": "Scheduled maintenance",+ "body": "The backend is being upgraded.",+ "severity": "info"+ }+ }))),+ AnnouncementMode::NotFound => Err((+ StatusCode::NOT_FOUND,+ Json(json!({ "success": false, "error": "no announcement" })),+ )),+ }+}++async fn mock_composio_connections(+ State(state): State<BackendState>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ Ok(Json(json!({ "success": true, "data": (*state.connections).clone() })))+}++fn mock_backend_router(state: BackendState) -> Router {+ Router::new()+ .route("/settings", get(mock_current_user))+ .route("/auth/me", get(mock_current_user))+ .route(+ "/announcements/latest",+ get(mock_announcements_latest).with_state(state.clone()),+ )+ .route(+ "/agent-integrations/composio/connections",+ get(mock_composio_connections).with_state(state),+ )+}++// ── infrastructure ───────────────────────────────────────────────────────────++async fn serve_ephemeral(app: Router) -> (SocketAddr, tokio::task::JoinHandle<()>) {+ ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind ephemeral port");+ let addr = listener.local_addr().expect("local addr");+ let handle = tokio::spawn(async move {+ axum::serve(listener, app).await.ok();+ });+ (addr, handle)+}++fn write_test_config(openhuman_dir: &Path, api_origin: &str) {+ let cfg = format!(+ r#"api_url = "{api_origin}"+default_model = "e2e-mock-model"+default_temperature = 0.7+chat_onboarding_completed = true++[secrets]+encrypt = false+"#+ );+ fn write_cfg(dir: &Path, cfg: &str) {+ std::fs::create_dir_all(dir).expect("mkdir config dir");+ std::fs::write(dir.join("config.toml"), cfg).expect("write config.toml");+ }+ write_cfg(openhuman_dir, &cfg);+ write_cfg(&openhuman_dir.join("users").join("local"), &cfg);+ write_cfg(&openhuman_dir.join("users").join(TEST_USER), &cfg);+}++async fn post_json_rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(120))+ .build()+ .expect("reqwest client");+ let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let resp = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", rpc_bearer()))+ .json(&body)+ .send()+ .await+ .unwrap_or_else(|e| panic!("POST {url}: {e}"));+ assert!(+ resp.status().is_success(),+ "HTTP error {} calling {method}",+ resp.status()+ );+ resp.json::<Value>()+ .await+ .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))+}++fn assert_no_jsonrpc_error<'a>(v: &'a Value, ctx: &str) -> &'a Value {+ if let Some(err) = v.get("error") {+ panic!("{ctx}: unexpected JSON-RPC error: {err}");+ }+ v.get("result")+ .unwrap_or_else(|| panic!("{ctx}: missing result field: {v}"))+}++fn jsonrpc_error_message(v: &Value, ctx: &str) -> String {+ let err = v+ .get("error")+ .unwrap_or_else(|| panic!("{ctx}: expected a JSON-RPC error, got: {v}"));+ err.get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{ctx}: error had no message: {err}"))+ .to_string()+}++fn peel(v: &Value) -> &Value {+ if v.get("logs").is_some() {+ v.get("result").unwrap_or(v)+ } else {+ v+ }+}++struct Harness {+ rpc_base: String,+ openhuman_home: std::path::PathBuf,+ mock_join: tokio::task::JoinHandle<()>,+ rpc_join: tokio::task::JoinHandle<()>,+ _home: EnvGuard,+ _ws: EnvGuard,+ _backend: EnvGuard,+ _vite: EnvGuard,+ _tmp: tempfile::TempDir,+}++impl Harness {+ async fn start(state: BackendState) -> Self {+ let tmp = tempdir().expect("tempdir");+ let home = tmp.path().to_path_buf();+ let openhuman_home = home.join(".openhuman");+ let _home = EnvGuard::set_to_path("HOME", &home);+ let _ws = EnvGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend = EnvGuard::unset("BACKEND_URL");+ let _vite = EnvGuard::unset("VITE_BACKEND_URL");++ let (mock_addr, mock_join) = serve_ephemeral(mock_backend_router(state)).await;+ write_test_config(&openhuman_home, &format!("http://{mock_addr}"));++ let (rpc_addr, rpc_join) = serve_ephemeral(build_core_http_router(false)).await;+ Self {+ rpc_base: format!("http://{rpc_addr}"),+ openhuman_home,+ mock_join,+ rpc_join,+ _home,+ _ws,+ _backend,+ _vite,+ _tmp: tmp,+ }+ }++ async fn sign_in(&self) {+ let store = post_json_rpc(+ &self.rpc_base,+ 1,+ "openhuman.auth_store_session",+ json!({ "token": TEST_JWT, "user_id": TEST_USER }),+ )+ .await;+ assert_no_jsonrpc_error(&store, "auth_store_session");+ }++ fn stop(self) {+ self.mock_join.abort();+ self.rpc_join.abort();+ }+}++fn default_state() -> BackendState {+ BackendState {+ announcement: AnnouncementMode::Present,+ connections: Arc::new(json!({ "connections": [] })),+ }+}++// ── notification centre ──────────────────────────────────────────────────────++/// The full integration-notification lifecycle over RPC: ingest → list → stats → mark read →+/// dismiss → mark acted, with the not-found branch of each mutator checked too.+///+/// `notification_settings_set` / `_get` / `_ingest` already had coverage in `json_rpc_e2e.rs`+/// (only for the *disabled-provider skip* path); everything downstream of a successful ingest —+/// which is the whole notification centre — did not.+///+/// Covers: `openhuman.notification_list`, `openhuman.notification_stats`,+/// `openhuman.notification_mark_read`, `openhuman.notification_dismiss`,+/// `openhuman.notification_mark_acted`.+#[tokio::test]+async fn notification_centre_lifecycle_over_rpc() {+ let _env_lock = platform_e2e_env_lock();+ let h = Harness::start(default_state()).await;++ // Enable the provider so ingest stores rather than skipping.+ let enabled = post_json_rpc(+ &h.rpc_base,+ 9001,+ "openhuman.notification_settings_set",+ json!({+ "provider": "gmail",+ "enabled": true,+ "importance_threshold": 0.0,+ "route_to_orchestrator": false+ }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&enabled, "notification_settings_set")+ .get("ok")+ .and_then(Value::as_bool),+ Some(true)+ );++ let ingested = post_json_rpc(+ &h.rpc_base,+ 9002,+ "openhuman.notification_ingest",+ json!({+ "provider": "gmail",+ "account_id": "acct-e2e",+ "title": "Quarterly report",+ "body": "The Q3 numbers are attached.",+ "raw_payload": { "messageId": "m-1" }+ }),+ )+ .await;+ let result = assert_no_jsonrpc_error(&ingested, "notification_ingest");+ assert_eq!(+ result.get("skipped").and_then(Value::as_bool),+ Some(false),+ "an enabled provider must not skip: {result}"+ );+ let id = result+ .get("id")+ .and_then(Value::as_str)+ .expect("ingest returns the new record id")+ .to_string();+ assert!(!id.is_empty());++ // ── list surfaces the stored record with the fields it was ingested with.+ let listed = post_json_rpc(+ &h.rpc_base,+ 9003,+ "openhuman.notification_list",+ json!({ "provider": "gmail", "limit": 10 }),+ )+ .await;+ let result = assert_no_jsonrpc_error(&listed, "notification_list");+ let items = result+ .get("items")+ .and_then(Value::as_array)+ .expect("items array");+ let row = items+ .iter()+ .find(|i| i.get("id").and_then(Value::as_str) == Some(id.as_str()))+ .unwrap_or_else(|| panic!("the ingested notification must be listed: {result}"));+ assert_eq!(+ row.get("title").and_then(Value::as_str),+ Some("Quarterly report"),+ "list must return the stored title, not a placeholder: {row}"+ );+ assert_eq!(+ row.get("body").and_then(Value::as_str),+ Some("The Q3 numbers are attached.")+ );+ assert_eq!(row.get("provider").and_then(Value::as_str), Some("gmail"));+ assert_eq!(row.get("account_id").and_then(Value::as_str), Some("acct-e2e"));+ assert_eq!(+ row.get("raw_payload").and_then(|p| p.get("messageId")),+ Some(&json!("m-1")),+ "the raw payload must round-trip through SQLite intact: {row}"+ );+ assert_eq!(+ row.get("status").and_then(Value::as_str),+ Some("unread"),+ "a freshly ingested notification is unread: {row}"+ );+ assert!(+ result+ .get("unread_count")+ .and_then(Value::as_i64)+ .unwrap_or(0)+ >= 1,+ "unread_count must account for the record just ingested: {result}"+ );++ // ── a provider filter that matches nothing returns an empty page, not everything.+ let other = post_json_rpc(+ &h.rpc_base,+ 9004,+ "openhuman.notification_list",+ json!({ "provider": "no-such-provider" }),+ )+ .await;+ let result = assert_no_jsonrpc_error(&other, "notification_list filtered");+ assert_eq!(+ result.get("items").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "the provider filter must actually filter: {result}"+ );++ // ── stats counts the record and buckets it by provider.+ let stats = post_json_rpc(&h.rpc_base, 9005, "openhuman.notification_stats", json!({})).await;+ let result = assert_no_jsonrpc_error(&stats, "notification_stats");+ assert_eq!(+ result.get("total").and_then(Value::as_i64),+ Some(1),+ "one ingested record in a fresh workspace: {result}"+ );+ assert_eq!(result.get("unread").and_then(Value::as_i64), Some(1));+ assert_eq!(+ result.get("by_provider").and_then(|p| p.get("gmail")),+ Some(&json!(1)),+ "stats must bucket by provider slug: {result}"+ );+ assert!(+ result.get("by_action").is_some(),+ "by_action must be present even when nothing has been triaged yet: {result}"+ );++ // ── mark_read flips the status and the unread count.+ let read = post_json_rpc(+ &h.rpc_base,+ 9006,+ "openhuman.notification_mark_read",+ json!({ "id": id }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&read, "notification_mark_read")+ .get("ok")+ .and_then(Value::as_bool),+ Some(true)+ );++ let after_read = post_json_rpc(+ &h.rpc_base,+ 9007,+ "openhuman.notification_list",+ json!({ "provider": "gmail" }),+ )+ .await;+ let result = assert_no_jsonrpc_error(&after_read, "notification_list after mark_read");+ assert_eq!(+ result.get("unread_count").and_then(Value::as_i64),+ Some(0),+ "mark_read must be visible in the unread count: {result}"+ );+ let row = result["items"]+ .as_array()+ .and_then(|items| items.first())+ .expect("the record is still listed after being read");+ assert_eq!(+ row.get("status").and_then(Value::as_str),+ Some("read"),+ "mark_read must persist the status transition: {row}"+ );++ // ── mark_acted and dismiss each report whether a row actually changed.+ let acted = post_json_rpc(+ &h.rpc_base,+ 9008,+ "openhuman.notification_mark_acted",+ json!({ "id": id }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&acted, "notification_mark_acted")+ .get("ok")+ .and_then(Value::as_bool),+ Some(true),+ "acting on an existing notification must report ok=true"+ );++ let acted_missing = post_json_rpc(+ &h.rpc_base,+ 9009,+ "openhuman.notification_mark_acted",+ json!({ "id": "no-such-notification" }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&acted_missing, "notification_mark_acted, missing id")+ .get("ok")+ .and_then(Value::as_bool),+ Some(false),+ "mark_acted must report ok=false for an id that matched no row, not a blanket true"+ );++ let dismissed = post_json_rpc(+ &h.rpc_base,+ 9010,+ "openhuman.notification_dismiss",+ json!({ "id": id }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&dismissed, "notification_dismiss")+ .get("ok")+ .and_then(Value::as_bool),+ Some(true)+ );++ let dismiss_missing = post_json_rpc(+ &h.rpc_base,+ 9011,+ "openhuman.notification_dismiss",+ json!({ "id": "no-such-notification" }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&dismiss_missing, "notification_dismiss, missing id")+ .get("ok")+ .and_then(Value::as_bool),+ Some(false),+ "dismiss must report ok=false for an id that matched no row"+ );++ // ── the id param is required on every mutator.+ for (rpc_id, method) in [+ (9012, "openhuman.notification_mark_read"),+ (9013, "openhuman.notification_dismiss"),+ (9014, "openhuman.notification_mark_acted"),+ ] {+ let response = post_json_rpc(&h.rpc_base, rpc_id, method, json!({})).await;+ let message = jsonrpc_error_message(&response, method);+ assert!(+ message.contains("missing required param 'id'"),+ "{method} must name the missing param, got: {message}"+ );+ }++ h.stop();+}++/// The persisted core-notification sync-down (#3805): list → mark read → list again.+///+/// Core notifications have no ingest RPC — the only writer is the bus subscriber — so the row is+/// seeded through `store::insert_core_notification` using the *same* `Config` the RPC handlers+/// load, then read back over the wire.+///+/// Covers: `openhuman.notification_core_list`, `openhuman.notification_core_mark_read`.+#[tokio::test]+async fn notification_core_sync_down_and_mark_read() {+ let _env_lock = platform_e2e_env_lock();+ let h = Harness::start(default_state()).await;++ // Empty workspace first: the contract is an empty page, not an error.+ let empty = post_json_rpc(+ &h.rpc_base,+ 9101,+ "openhuman.notification_core_list",+ json!({}),+ )+ .await;+ let result = assert_no_jsonrpc_error(&empty, "notification_core_list (empty)");+ assert_eq!(+ result.get("items").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "a fresh workspace has no core notifications: {result}"+ );+ assert_eq!(result.get("unread_count").and_then(Value::as_i64), Some(0));++ let config = load_config_with_timeout()+ .await+ .expect("the same config the RPC handlers resolve");++ let unread_event = CoreNotificationEvent {+ id: "e2e-core-unread".to_string(),+ category: CoreNotificationCategory::Agents,+ title: "Sub-agent finished".to_string(),+ body: "The research run completed.".to_string(),+ deep_link: Some("/threads/t-1".to_string()),+ timestamp_ms: 1_700_000_002_000,+ actions: None,+ workspace: None,+ workspace_revision: None,+ };+ let read_later_event = CoreNotificationEvent {+ id: "e2e-core-second".to_string(),+ category: CoreNotificationCategory::System,+ title: "Update available".to_string(),+ body: "A new core build is ready.".to_string(),+ deep_link: None,+ timestamp_ms: 1_700_000_001_000,+ actions: None,+ workspace: None,+ workspace_revision: None,+ };+ assert!(+ notification_store::insert_core_notification(&config, &unread_event)+ .expect("seed core notification"),+ "the first insert of an id must report that it wrote a row"+ );+ assert!(+ notification_store::insert_core_notification(&config, &read_later_event)+ .expect("seed second core notification")+ );+ assert!(+ !notification_store::insert_core_notification(&config, &unread_event)+ .expect("re-insert core notification"),+ "the id is the primary key, so a re-publish must dedupe rather than duplicate"+ );++ let listed = post_json_rpc(+ &h.rpc_base,+ 9102,+ "openhuman.notification_core_list",+ json!({}),+ )+ .await;+ let result = assert_no_jsonrpc_error(&listed, "notification_core_list");+ let items = result+ .get("items")+ .and_then(Value::as_array)+ .expect("items array");+ assert_eq!(items.len(), 2, "both seeded rows sync down: {result}");+ assert_eq!(+ items[0].get("id").and_then(Value::as_str),+ Some("e2e-core-unread"),+ "rows come back newest-first by timestamp_ms: {result}"+ );+ assert_eq!(+ items[0].get("title").and_then(Value::as_str),+ Some("Sub-agent finished")+ );+ assert_eq!(+ items[0].get("category").and_then(Value::as_str),+ Some("agents"),+ "the category serialises lowercase for the frontend notification centre: {}",+ items[0]+ );+ assert_eq!(+ items[0].get("deep_link").and_then(Value::as_str),+ Some("/threads/t-1"),+ "the deep link must survive the JSON round-trip through SQLite: {}",+ items[0]+ );+ assert_eq!(result.get("unread_count").and_then(Value::as_i64), Some(2));++ // ── mark one read: it drops out of the default (unread-only) page.+ let marked = post_json_rpc(+ &h.rpc_base,+ 9103,+ "openhuman.notification_core_mark_read",+ json!({ "id": "e2e-core-unread" }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&marked, "notification_core_mark_read")+ .get("ok")+ .and_then(Value::as_bool),+ Some(true)+ );++ let after = post_json_rpc(+ &h.rpc_base,+ 9104,+ "openhuman.notification_core_list",+ json!({}),+ )+ .await;+ let result = assert_no_jsonrpc_error(&after, "notification_core_list after mark_read");+ let items = result+ .get("items")+ .and_then(Value::as_array)+ .expect("items array");+ assert_eq!(+ items.len(),+ 1,+ "only_unread defaults to true, so the read row must be gone: {result}"+ );+ assert_eq!(+ items[0].get("id").and_then(Value::as_str),+ Some("e2e-core-second")+ );+ assert_eq!(result.get("unread_count").and_then(Value::as_i64), Some(1));++ // ── only_unread=false brings the read row back.+ let all = post_json_rpc(+ &h.rpc_base,+ 9105,+ "openhuman.notification_core_list",+ json!({ "only_unread": false }),+ )+ .await;+ let result = assert_no_jsonrpc_error(&all, "notification_core_list, only_unread=false");+ assert_eq!(+ result.get("items").and_then(Value::as_array).map(Vec::len),+ Some(2),+ "only_unread=false must include read rows: {result}"+ );+ assert_eq!(+ result.get("unread_count").and_then(Value::as_i64),+ Some(1),+ "unread_count is a count of unread rows regardless of what the page returned: {result}"+ );++ // ── limit is honoured.+ let limited = post_json_rpc(+ &h.rpc_base,+ 9106,+ "openhuman.notification_core_list",+ json!({ "only_unread": false, "limit": 1 }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&limited, "notification_core_list, limit=1")+ .get("items")+ .and_then(Value::as_array)+ .map(Vec::len),+ Some(1),+ "limit must bound the page"+ );++ // ── an unknown id changes nothing and says so.+ let missing = post_json_rpc(+ &h.rpc_base,+ 9107,+ "openhuman.notification_core_mark_read",+ json!({ "id": "e2e-core-does-not-exist" }),+ )+ .await;+ assert_eq!(+ assert_no_jsonrpc_error(&missing, "notification_core_mark_read, missing id")+ .get("ok")+ .and_then(Value::as_bool),+ Some(false),+ "marking a non-existent core notification must report ok=false"+ );++ let no_id = post_json_rpc(+ &h.rpc_base,+ 9108,+ "openhuman.notification_core_mark_read",+ json!({}),+ )+ .await;+ assert!(+ jsonrpc_error_message(&no_id, "notification_core_mark_read without id")+ .contains("missing required param 'id'")+ );++ h.stop();+}++// ── health ───────────────────────────────────────────────────────────────────++/// `health_snapshot` reflects what the component registry was told, and `health_system_info`+/// reports this process.+///+/// The component registry is process-global and shared with every other suite in this binary, so+/// the assertions are on components this file names uniquely — never on the size of the map.+///+/// Covers: `openhuman.health_snapshot`, `openhuman.health_system_info`.+#[tokio::test]+async fn health_snapshot_and_system_info_report_this_process() {+ let _env_lock = platform_e2e_env_lock();+ let h = Harness::start(default_state()).await;++ mark_component_ok("e2e_platform_probe_ok");+ mark_component_error("e2e_platform_probe_bad", "synthetic failure for the e2e probe");++ let snapshot = post_json_rpc(&h.rpc_base, 9201, "openhuman.health_snapshot", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&snapshot, "health_snapshot"));++ let components = result+ .get("components")+ .and_then(Value::as_object)+ .unwrap_or_else(|| panic!("snapshot must carry a components map: {result}"));++ let ok = components+ .get("e2e_platform_probe_ok")+ .unwrap_or_else(|| panic!("a component marked ok must appear in the snapshot: {result}"));+ assert_eq!(+ ok.get("status").and_then(Value::as_str),+ Some("ok"),+ "mark_component_ok must surface as status=ok: {ok}"+ );+ assert!(+ ok.get("last_ok").map(|v| v.is_string()).unwrap_or(false),+ "an ok component records when it was last ok: {ok}"+ );+ assert!(+ ok.get("last_error").map(Value::is_null).unwrap_or(false),+ "marking ok must clear any previous error: {ok}"+ );++ let bad = components+ .get("e2e_platform_probe_bad")+ .unwrap_or_else(|| panic!("a component marked error must appear: {result}"));+ assert_eq!(bad.get("status").and_then(Value::as_str), Some("error"));+ assert_eq!(+ bad.get("last_error").and_then(Value::as_str),+ Some("synthetic failure for the e2e probe"),+ "the error message must be carried verbatim, not swallowed: {bad}"+ );++ let snapshot_pid = result+ .get("pid")+ .and_then(Value::as_u64)+ .unwrap_or_else(|| panic!("snapshot must carry a pid: {result}"));+ assert_eq!(+ snapshot_pid,+ u64::from(std::process::id()),+ "the snapshot describes *this* process"+ );+ assert!(+ result.get("uptime_seconds").and_then(Value::as_u64).is_some(),+ "snapshot must carry uptime_seconds: {result}"+ );+ assert!(+ result+ .get("updated_at")+ .and_then(Value::as_str)+ .map(|t| chrono::DateTime::parse_from_rfc3339(t).is_ok())+ .unwrap_or(false),+ "updated_at must be RFC3339: {result}"+ );++ let info = post_json_rpc(&h.rpc_base, 9202, "openhuman.health_system_info", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&info, "health_system_info"));+ assert_eq!(+ result.get("os").and_then(Value::as_str),+ Some(std::env::consts::OS),+ "system_info must report the real target OS: {result}"+ );+ assert_eq!(+ result.get("arch").and_then(Value::as_str),+ Some(std::env::consts::ARCH)+ );+ assert_eq!(+ result.get("version").and_then(Value::as_str),+ Some(env!("CARGO_PKG_VERSION")),+ "system_info reports the core crate version this binary was built from: {result}"+ );+ // The declared schema says `pid: String`; the handler serialises a `u32`. Asserting the real+ // wire type pins the mismatch rather than hiding it — see+ // bugs/e2e-wave-health-system-info-pid-type.md.+ assert_eq!(+ result.get("pid").and_then(Value::as_u64),+ Some(u64::from(std::process::id())),+ "system_info must report this process's pid: {result}"+ );++ h.stop();+}++// ── doctor ───────────────────────────────────────────────────────────────────++/// `doctor_report` returns a self-consistent diagnostics report, and `doctor_models` reports one+/// entry per registered provider.+///+/// Covers: `openhuman.doctor_report`, `openhuman.doctor_models`.+#[tokio::test]+async fn doctor_report_and_models_are_internally_consistent() {+ let _env_lock = platform_e2e_env_lock();+ let h = Harness::start(default_state()).await;++ let report = post_json_rpc(&h.rpc_base, 9301, "openhuman.doctor_report", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&report, "doctor_report"));++ let items = result+ .get("items")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("doctor_report must return items: {result}"));+ assert!(+ !items.is_empty(),+ "the doctor always runs at least the config and workspace checks: {result}"+ );+ for item in items {+ assert!(+ matches!(+ item.get("severity").and_then(Value::as_str),+ Some("Ok" | "Warn" | "Error")+ ),+ "every item carries one of the three severities: {item}"+ );+ assert!(+ item.get("category")+ .and_then(Value::as_str)+ .map(|c| !c.is_empty())+ .unwrap_or(false),+ "every item is attributed to a category: {item}"+ );+ assert!(+ item.get("message")+ .and_then(Value::as_str)+ .map(|m| !m.is_empty())+ .unwrap_or(false),+ "every item carries a human-readable message: {item}"+ );+ }+ assert!(+ items+ .iter()+ .any(|i| i.get("category").and_then(Value::as_str) == Some("config")),+ "the config check always runs: {result}"+ );+ assert!(+ items+ .iter()+ .any(|i| i.get("category").and_then(Value::as_str) == Some("workspace")),+ "the workspace check always runs: {result}"+ );++ // The summary is derived from the items — if the tally drifts, this is what catches it.+ let summary = result+ .get("summary")+ .unwrap_or_else(|| panic!("doctor_report must return a summary: {result}"));+ let count_of = |severity: &str| {+ items+ .iter()+ .filter(|i| i.get("severity").and_then(Value::as_str) == Some(severity))+ .count() as u64+ };+ assert_eq!(+ summary.get("ok").and_then(Value::as_u64),+ Some(count_of("Ok")),+ "summary.ok must equal the number of Ok items: {result}"+ );+ assert_eq!(+ summary.get("warnings").and_then(Value::as_u64),+ Some(count_of("Warn")),+ "summary.warnings must equal the number of Warn items: {result}"+ );+ assert_eq!(+ summary.get("errors").and_then(Value::as_u64),+ Some(count_of("Error")),+ "summary.errors must equal the number of Error items: {result}"+ );++ // ── models: one entry per registered inference provider, summary consistent with them.+ let models = post_json_rpc(+ &h.rpc_base,+ 9302,+ "openhuman.doctor_models",+ json!({ "use_cache": false }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&models, "doctor_models"));+ let entries = result+ .get("entries")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("doctor_models must return entries: {result}"));+ assert!(+ !entries.is_empty(),+ "the provider registry is never empty, and an empty target list is a hard error: {result}"+ );+ for entry in entries {+ assert!(+ entry+ .get("provider")+ .and_then(Value::as_str)+ .map(|p| !p.is_empty())+ .unwrap_or(false),+ "every probe entry names its provider: {entry}"+ );+ assert!(+ matches!(+ entry.get("outcome").and_then(Value::as_str),+ Some("Ok" | "Skipped" | "AuthOrAccess" | "Error")+ ),+ "every probe entry carries a known outcome: {entry}"+ );+ }+ let summary = result+ .get("summary")+ .unwrap_or_else(|| panic!("doctor_models must return a summary: {result}"));+ let total: u64 = ["ok", "skipped", "auth_or_access", "errors"]+ .iter()+ .map(|k| summary.get(*k).and_then(Value::as_u64).unwrap_or_else(|| {+ panic!("summary must carry {k}: {result}")+ }))+ .sum();+ assert_eq!(+ total,+ entries.len() as u64,+ "the summary buckets must add up to the number of entries: {result}"+ );++ // `use_cache` is optional and defaults to true; a non-bool must be rejected, not coerced.+ // The refusal comes from `core::all::validate_params`, which type-checks every present param+ // against its declared `TypeSchema` before dispatch.+ let bad_param = post_json_rpc(+ &h.rpc_base,+ 9303,+ "openhuman.doctor_models",+ json!({ "use_cache": "yes please" }),+ )+ .await;+ let message = jsonrpc_error_message(&bad_param, "doctor_models with a non-bool use_cache");+ assert!(+ message.contains("invalid type for param 'use_cache'")+ && message.contains("expected bool")+ && message.contains("got string"),+ "a wrongly-typed optional param must be rejected naming the expected and actual types, \+ got: {message}"+ );++ h.stop();+}++// ── service: daemon-host preferences ─────────────────────────────────────────++/// `service_daemon_host_get` / `_set` round-trip through `daemon_host_config.json`.+///+/// Covers: `openhuman.service_daemon_host_get`, `openhuman.service_daemon_host_set`.+#[tokio::test]+async fn service_daemon_host_preferences_round_trip_to_disk() {+ let _env_lock = platform_e2e_env_lock();+ let h = Harness::start(default_state()).await;++ let initial = post_json_rpc(+ &h.rpc_base,+ 9401,+ "openhuman.service_daemon_host_get",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&initial, "service_daemon_host_get"));+ assert_eq!(+ result.get("showTray").and_then(Value::as_bool),+ Some(true),+ "with no file on disk the default is tray-visible, and the field is camelCase: {result}"+ );++ // The request param is snake_case (`show_tray`) while the response field is camelCase+ // (`showTray`) — `DaemonHostConfig` carries `rename_all = \"camelCase\"` but+ // `DaemonHostSetParams` does not. Pinning both spellings here keeps that asymmetry visible.+ let set = post_json_rpc(+ &h.rpc_base,+ 9402,+ "openhuman.service_daemon_host_set",+ json!({ "show_tray": false }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&set, "service_daemon_host_set"));+ assert_eq!(+ result.get("showTray").and_then(Value::as_bool),+ Some(false),+ "set must echo the value it stored: {result}"+ );++ // `daemon_host_set` writes to `config.config_path.parent()` — the *resolved* config+ // directory, which under a pre-login user is `.openhuman/users/local/`, not `.openhuman/`.+ // Resolving it here through the same loader the op uses asserts the real contract ("next to+ // config.toml") instead of a guess at where that lands.+ let config = load_config_with_timeout()+ .await+ .expect("the same config the daemon-host op resolves");+ let config_dir = config+ .config_path+ .parent()+ .expect("config.toml has a parent directory");+ assert!(+ config_dir.starts_with(&h.openhuman_home),+ "the resolved config dir must be inside this test's temp HOME, got {}",+ config_dir.display()+ );+ let persisted = config_dir.join("daemon_host_config.json");+ assert!(+ persisted.exists(),+ "the preference must be written next to config.toml, at {}",+ persisted.display()+ );+ let on_disk: Value = serde_json::from_str(+ &std::fs::read_to_string(&persisted).expect("read daemon_host_config.json"),+ )+ .expect("daemon_host_config.json is valid JSON");+ assert_eq!(+ on_disk.get("showTray").and_then(Value::as_bool),+ Some(false),+ "the on-disk file uses the camelCase key: {on_disk}"+ );++ let reread = post_json_rpc(+ &h.rpc_base,+ 9403,+ "openhuman.service_daemon_host_get",+ json!({}),+ )+ .await;+ assert_eq!(+ peel(assert_no_jsonrpc_error(&reread, "service_daemon_host_get after set"))+ .get("showTray")+ .and_then(Value::as_bool),+ Some(false),+ "get must read back what set wrote, not the default"+ );++ // `show_tray` is required — there is no implicit default on the write path.+ let missing = post_json_rpc(+ &h.rpc_base,+ 9404,+ "openhuman.service_daemon_host_set",+ json!({}),+ )+ .await;+ assert!(+ jsonrpc_error_message(&missing, "service_daemon_host_set without show_tray")+ .contains("show_tray"),+ "the error must name the missing field"+ );++ h.stop();+}++// ── provider surfaces ────────────────────────────────────────────────────────++/// The local respond queue: ingest an event, see it in the queue, re-ingest and see it upserted+/// rather than duplicated.+///+/// The queue is a process-global `Vec` shared with every suite in this binary, so the assertions+/// are on rows keyed to this file (`provider = "e2e-surface"`), never on the queue's length.+///+/// Covers: `openhuman.provider_surfaces_ingest_event`,+/// `openhuman.provider_surfaces_list_queue`.+#[tokio::test]+async fn provider_surfaces_respond_queue_upserts_by_event_identity() {+ let _env_lock = platform_e2e_env_lock();+ let h = Harness::start(default_state()).await;++ let event = json!({+ "provider": "e2e-surface",+ "account_id": "acct-7",+ "event_kind": "message",+ "entity_id": "msg-1",+ "thread_id": "thr-1",+ "title": "Ping",+ "snippet": "are you around?",+ "sender_name": "A Colleague",+ "timestamp": "2026-09-07T10:00:00Z",+ "requires_attention": true+ });++ let ingested = post_json_rpc(+ &h.rpc_base,+ 9501,+ "openhuman.provider_surfaces_ingest_event",+ event.clone(),+ )+ .await;+ let result = assert_no_jsonrpc_error(&ingested, "provider_surfaces_ingest_event");+ let item = result+ .get("data")+ .unwrap_or_else(|| panic!("ingest returns an ApiEnvelope with a data member: {result}"));+ assert_eq!(+ item.get("id").and_then(Value::as_str),+ Some("e2e-surface:acct-7:message:msg-1"),+ "the queue id is derived from provider:account:kind:entity — that composite is what \+ makes a re-delivery an upsert instead of a duplicate: {item}"+ );+ assert_eq!(+ item.get("status").and_then(Value::as_str),+ Some("pending"),+ "a newly queued item starts pending: {item}"+ );+ assert_eq!(+ item.get("requires_attention").and_then(Value::as_bool),+ Some(true)+ );+ assert_eq!(item.get("title").and_then(Value::as_str), Some("Ping"));+ assert!(+ result+ .get("meta")+ .and_then(|m| m.get("request_id"))+ .and_then(Value::as_str)+ .map(|id| !id.is_empty())+ .unwrap_or(false),+ "the envelope carries a request id: {result}"+ );+ assert!(+ result.get("error").map(Value::is_null).unwrap_or(true),+ "a successful ingest leaves the envelope's error member null: {result}"+ );++ // ── re-ingest with a changed title: same identity ⇒ one row, updated in place.+ let mut updated_event = event.clone();+ updated_event["title"] = json!("Ping (edited)");+ updated_event["requires_attention"] = json!(false);+ let reingested = post_json_rpc(+ &h.rpc_base,+ 9502,+ "openhuman.provider_surfaces_ingest_event",+ updated_event,+ )+ .await;+ assert_no_jsonrpc_error(&reingested, "provider_surfaces_ingest_event (upsert)");++ let listed = post_json_rpc(+ &h.rpc_base,+ 9503,+ "openhuman.provider_surfaces_list_queue",+ json!({}),+ )+ .await;+ let result = assert_no_jsonrpc_error(&listed, "provider_surfaces_list_queue");+ let items = result+ .get("data")+ .and_then(|d| d.get("items"))+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("list_queue returns data.items: {result}"));+ let ours: Vec<_> = items+ .iter()+ .filter(|i| i.get("provider").and_then(Value::as_str) == Some("e2e-surface"))+ .collect();+ assert_eq!(+ ours.len(),+ 1,+ "re-ingesting the same provider/account/kind/entity must upsert, not append: {result}"+ );+ assert_eq!(+ ours[0].get("title").and_then(Value::as_str),+ Some("Ping (edited)"),+ "the upsert must carry the newer field values: {}",+ ours[0]+ );+ assert_eq!(+ ours[0].get("requires_attention").and_then(Value::as_bool),+ Some(false),+ "the upsert must overwrite requires_attention, not OR it: {}",+ ours[0]+ );+ assert_eq!(+ result+ .get("data")+ .and_then(|d| d.get("count"))+ .and_then(Value::as_u64),+ Some(items.len() as u64),+ "the reported count must match the items actually returned: {result}"+ );++ // ── the event contract is strict on both sides: unknown fields and missing ones both fail.+ let mut unknown_field = event.clone();+ unknown_field["not_a_real_field"] = json!("surprise");+ let rejected = post_json_rpc(+ &h.rpc_base,+ 9504,+ "openhuman.provider_surfaces_ingest_event",+ unknown_field,+ )+ .await;+ let message = jsonrpc_error_message(&rejected, "ingest_event with an unknown field");+ assert!(+ message.contains("not_a_real_field"),+ "an undeclared key must be refused naming it — `core::all::validate_params` rejects it \+ against the schema, and `ProviderEvent`'s `deny_unknown_fields` is the second line of \+ defence behind that; got: {message}"+ );++ let mut missing_timestamp = event.clone();+ missing_timestamp+ .as_object_mut()+ .expect("object")+ .remove("timestamp");+ let rejected = post_json_rpc(+ &h.rpc_base,+ 9505,+ "openhuman.provider_surfaces_ingest_event",+ missing_timestamp,+ )+ .await;+ assert!(+ jsonrpc_error_message(&rejected, "ingest_event without timestamp").contains("timestamp"),+ "a missing required field must name itself"+ );++ h.stop();+}++// ── slack_memory ─────────────────────────────────────────────────────────────++/// `slack_memory_sync_status` filters the Composio connection list down to active Slack rows and+/// reports the degraded detail fields at zero; `slack_memory_sync_trigger` refuses an id that is+/// not in that set.+///+/// Covers: `openhuman.slack_memory_sync_status`, `openhuman.slack_memory_sync_trigger`.+#[tokio::test]+async fn slack_memory_sync_status_filters_to_active_slack_connections() {+ let _env_lock = platform_e2e_env_lock();++ // Three rows that between them exercise every branch of the filter: an active slack one, an+ // active connection for a *different* toolkit, and a slack one that is not active.+ let state = BackendState {+ announcement: AnnouncementMode::Present,+ connections: Arc::new(json!({+ "connections": [+ { "id": "conn-slack-live", "toolkit": " Slack ", "status": "ACTIVE" },+ { "id": "conn-gmail-live", "toolkit": "gmail", "status": "ACTIVE" },+ { "id": "conn-slack-pending", "toolkit": "slack", "status": "PENDING" }+ ]+ })),+ };+ let h = Harness::start(state).await;+ h.sign_in().await;++ let status = post_json_rpc(+ &h.rpc_base,+ 9601,+ "openhuman.slack_memory_sync_status",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&status, "slack_memory_sync_status"));+ let rows = result+ .get("connections")+ .and_then(Value::as_array)+ .unwrap_or_else(|| panic!("sync_status returns a connections array: {result}"));+ assert_eq!(+ rows.len(),+ 1,+ "only the active Slack connection is a sync candidate — the gmail row and the pending \+ slack row must both be filtered out: {result}"+ );+ let row = &rows[0];+ assert_eq!(+ row.get("connection_id").and_then(Value::as_str),+ Some("conn-slack-live"),+ "the toolkit match is case- and whitespace-insensitive (` Slack ` matched): {row}"+ );+ // The per-connection detail this endpoint used to report has no source since tinymemory+ // v1.13.4; the fields are kept on the wire at their zero value rather than removed. Pinning+ // that keeps a future "it started reporting real cursors again" from going unnoticed.+ assert_eq!(+ row.get("per_channel_cursors").and_then(Value::as_str),+ Some("{}"),+ "cursor detail is no longer available and is reported as an empty JSON object: {row}"+ );+ assert_eq!(row.get("synced_ids_count").and_then(Value::as_u64), Some(0));+ assert_eq!(+ row.get("requests_used_today").and_then(Value::as_u64),+ Some(0)+ );+ assert_eq!(+ row.get("daily_request_limit").and_then(Value::as_u64),+ Some(0)+ );++ // ── a trigger scoped to a connection that is not a candidate fails, naming the id.+ let unknown = post_json_rpc(+ &h.rpc_base,+ 9602,+ "openhuman.slack_memory_sync_trigger",+ json!({ "connection_id": "conn-slack-pending" }),+ )+ .await;+ let message = jsonrpc_error_message(&unknown, "sync_trigger for a non-active connection");+ assert!(+ message.contains("no active Slack connection with id=conn-slack-pending"),+ "the error must name the id it could not find, got: {message}"+ );++ // The gmail connection is active but the wrong toolkit — same refusal, which is what proves+ // the filter is on toolkit *and* status rather than either alone.+ let wrong_toolkit = post_json_rpc(+ &h.rpc_base,+ 9603,+ "openhuman.slack_memory_sync_trigger",+ json!({ "connection_id": "conn-gmail-live" }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&wrong_toolkit, "sync_trigger for a gmail connection")+ .contains("no active Slack connection with id=conn-gmail-live")+ );++ h.stop();+}++/// Both `slack_memory` controllers refuse before the network hop when the user is signed out.+#[tokio::test]+async fn slack_memory_controllers_require_a_backend_session() {+ let _env_lock = platform_e2e_env_lock();+ let h = Harness::start(default_state()).await;+ // Deliberately no sign_in().++ for (id, method) in [+ (9701, "openhuman.slack_memory_sync_status"),+ (9702, "openhuman.slack_memory_sync_trigger"),+ ] {+ let response = post_json_rpc(&h.rpc_base, id, method, json!({})).await;+ let message = jsonrpc_error_message(&response, method);+ assert!(+ message.contains("[slack_ingest] list_connections")+ && message.contains("no backend session token"),+ "{method} must fail at the client factory with an actionable message, got: {message}"+ );+ }++ h.stop();+}++// ── announcements ────────────────────────────────────────────────────────────++/// `announcements_get_latest` passes a backend announcement through verbatim, folds the backend's+/// 404 into `null`, and refuses when signed out.+///+/// The 404 → `null` fold is the whole point of the controller (it exists because the honest error+/// flooded Sentry with an unactionable signal), and it had no test at any level of the stack.+///+/// Covers: `openhuman.announcements_get_latest`.+#[tokio::test]+async fn announcements_get_latest_passes_through_and_folds_404_to_null() {+ let _env_lock = platform_e2e_env_lock();++ // ── signed out: refused locally, before the backend is dialled.+ let h = Harness::start(default_state()).await;+ let signed_out = post_json_rpc(+ &h.rpc_base,+ 9801,+ "openhuman.announcements_get_latest",+ json!({}),+ )+ .await;+ assert!(+ jsonrpc_error_message(&signed_out, "announcements_get_latest, signed out")+ .contains("no backend session token"),+ "the controller requires a live session"+ );++ // ── signed in, announcement present: the backend object is surfaced verbatim.+ h.sign_in().await;+ let present = post_json_rpc(+ &h.rpc_base,+ 9802,+ "openhuman.announcements_get_latest",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&present, "announcements_get_latest"));+ assert_eq!(+ result.get("id").and_then(Value::as_str),+ Some("ann-1"),+ "the backend payload must pass through unwrapped: {result}"+ );+ assert_eq!(+ result.get("title").and_then(Value::as_str),+ Some("Scheduled maintenance")+ );+ assert_eq!(result.get("severity").and_then(Value::as_str), Some("info"));+ h.stop();++ // ── signed in, backend 404: folded into `null`, not surfaced as an error.+ let h = Harness::start(BackendState {+ announcement: AnnouncementMode::NotFound,+ connections: Arc::new(json!({ "connections": [] })),+ })+ .await;+ h.sign_in().await;+ let absent = post_json_rpc(+ &h.rpc_base,+ 9803,+ "openhuman.announcements_get_latest",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(+ &absent,+ "announcements_get_latest, backend 404",+ ));+ assert!(+ result.is_null(),+ "a 404 from /announcements/latest means \"no announcement\" and must degrade to null \+ rather than propagate as an error: {result}"+ );++ h.stop();+}diff --git a/tests/raw_coverage/webhooks_ingress_e2e.rs b/tests/raw_coverage/webhooks_ingress_e2e.rsnew file mode 100644index 0000000000..ca5db505b5--- /dev/null+++ b/tests/raw_coverage/webhooks_ingress_e2e.rs@@ -0,0 +1,1036 @@+//! End-to-end coverage for the `webhooks` RPC namespace (13 controllers, 0% before this file).+//!+//! Two independent halves, because the namespace has two independent backends:+//!+//! 1. **Router-local** (`list_registrations`, `register_echo`, `unregister_echo`,+//! `register_agent`, `trigger_agent`, `list_logs`, `clear_logs`) — served out of the+//! `WebhookRouter` hanging off the global `SocketManager`. These tests install a real+//! `SocketManager` + `WebhookRouter` (persisting to a tempdir) and drive the registry through+//! the JSON-RPC surface, asserting on the registration rows and the debug-log ring that come+//! back.+//!+//! 2. **Backend tunnel CRUD** (`list_tunnels`, `create_tunnel`, `get_tunnel`, `update_tunnel`,+//! `delete_tunnel`, `get_bandwidth`) — thin adapters over `/webhooks/core*` on the hosted+//! backend. These run against an in-process axum mock that records what the core actually+//! sent, so the tests assert on the *request* the adapter built (method, path, body key+//! casing) as well as the response it surfaced.+//!+//! Shape follows `tests/composio_post_oauth_retry_e2e.rs`: an env lock (HOME / BACKEND_URL are+//! process-global), an ephemeral mock backend, an ephemeral core JSON-RPC server, and+//! `auth_store_session` to mint the JWT the tunnel adapters require.+//!+//! This file is a **module** of the aggregated `raw_coverage_all` target (globbed in by+//! `build.rs`), not its own binary — so every suite in that binary shares one process and libtest+//! runs them concurrently. Two consequences are load-bearing here:+//!+//! * env mutation binds to `crate::SHARED_ENV_LOCK`, not a lock private to this file;+//! * `set_global_socket_manager` writes a `OnceLock` that+//! `connectivity_raw_coverage_e2e.rs` also writes. Whoever gets there first owns the+//! manager, so `shared_router` attaches the router to whichever instance won rather than+//! assuming its own was installed.+//!+//! Run with:+//! ~/tinyhuman/ci-slot.sh cargo test --test raw_coverage_all \+//! --features "$(bash scripts/ci/product-features.sh)" webhooks_ingress++use std::collections::HashMap;+use std::net::SocketAddr;+use std::path::Path;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++use axum::extract::{Path as AxumPath, State};+use axum::http::{header::AUTHORIZATION, HeaderMap, StatusCode};+use axum::routing::{get, post};+use axum::{Json, Router};+use serde_json::{json, Value};+use tempfile::tempdir;++use openhuman_core::core::auth::{get_rpc_token, init_rpc_token};+use openhuman_core::core::jsonrpc::build_core_http_router;+use openhuman_core::openhuman::platform::socket::{+ global_socket_manager, set_global_socket_manager, SocketManager,+};+use openhuman_core::openhuman::skills::webhooks::{WebhookRequest, WebhookRouter};++// ── env serialisation ────────────────────────────────────────────────────────+//+// HOME / BACKEND_URL / VITE_BACKEND_URL are process-global and this file shares its process with+// ~76 sibling suites. A lock private to this file would compile, pass in isolation, and race them+// under load — so bind to the crate-wide one.++static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;++fn webhooks_e2e_env_lock() -> std::sync::MutexGuard<'static, ()> {+ ENV_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++const TEST_JWT: &str = "e2e-webhooks-jwt";++/// The bearer every request in this file sends.+///+/// **Read back, never asserted.** `RPC_TOKEN` in `core::auth` is a process-global `OnceLock` and+/// this file shares its process with every other aggregated suite, several of which also call+/// `init_rpc_token`. Whichever runs first fixes the token for the whole binary and every later+/// `init_rpc_token` is a documented no-op — so a suite that hard-codes its own literal and sends+/// that would 401 whenever it lost the race. Initialising and then asking `get_rpc_token()` for+/// the value that actually took is correct either way round.+fn rpc_bearer() -> &'static str {+ static BEARER: OnceLock<&'static str> = OnceLock::new();+ BEARER.get_or_init(|| {+ let token_dir = std::env::temp_dir().join("openhuman-webhooks-e2e-auth");+ std::fs::create_dir_all(&token_dir).expect("rpc token dir");+ init_rpc_token(&token_dir).expect("init rpc token for webhooks_ingress_e2e");+ get_rpc_token().expect("an RPC token is initialised for this process")+ })+}++fn ensure_rpc_auth() {+ let _ = rpc_bearer();+}++/// The `WebhookRouter` the webhook ops resolve through `global_socket_manager()`.+///+/// `set_global_socket_manager` writes a `OnceLock`, and `connectivity_raw_coverage_e2e.rs`+/// installs a bare `SocketManager` of its own into the same slot. Whichever suite runs first+/// wins and the other's `set` is a logged no-op — so this offers a manager, then reads back+/// *whatever* is actually installed and attaches the router to that. `set_webhook_router` takes+/// `&self` and writes an `RwLock`, so this works on a manager we did not create.+///+/// The router is process-wide as a result, so each case below uses tunnel UUIDs unique to itself.+fn shared_router() -> &'static Arc<WebhookRouter> {+ static ROUTER: OnceLock<Arc<WebhookRouter>> = OnceLock::new();+ ROUTER.get_or_init(|| {+ let tmp = tempdir().expect("router persist tempdir");+ let path = tmp.path().join("webhook_routes.json");+ // Outlives the binary; the OS reaps the tmpdir.+ std::mem::forget(tmp);+ let router = Arc::new(WebhookRouter::new(Some(path)));+ set_global_socket_manager(Arc::new(SocketManager::new()));+ let installed = global_socket_manager()+ .expect("a global SocketManager is installed after set_global_socket_manager");+ installed.set_webhook_router(Arc::clone(&router));+ router+ })+}++struct EnvGuard {+ key: &'static str,+ prev: Option<String>,+}++impl EnvGuard {+ fn set_to_path(key: &'static str, path: &Path) -> Self {+ let prev = std::env::var(key).ok();+ std::env::set_var(key, path.as_os_str());+ Self { key, prev }+ }++ fn unset(key: &'static str) -> Self {+ let prev = std::env::var(key).ok();+ std::env::remove_var(key);+ Self { key, prev }+ }+}++impl Drop for EnvGuard {+ fn drop(&mut self) {+ match &self.prev {+ Some(v) => std::env::set_var(self.key, v),+ None => std::env::remove_var(self.key),+ }+ }+}++// ── mock backend ─────────────────────────────────────────────────────────────++/// One recorded inbound request to the mock backend.+#[derive(Clone, Debug)]+struct RecordedCall {+ method: String,+ path: String,+ body: Option<Value>,+}++#[derive(Clone, Default)]+struct BackendState {+ calls: Arc<Mutex<Vec<RecordedCall>>>,+}++impl BackendState {+ fn record(&self, method: &str, path: &str, body: Option<Value>) {+ self.calls+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .push(RecordedCall {+ method: method.to_string(),+ path: path.to_string(),+ body,+ });+ }++ fn calls(&self) -> Vec<RecordedCall> {+ self.calls+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .clone()+ }+}++fn unauthorized() -> (StatusCode, Json<Value>) {+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "unauthorized" })),+ )+}++fn is_authed(headers: &HeaderMap) -> bool {+ headers+ .get(AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .map(|v| v == format!("Bearer {TEST_JWT}"))+ .unwrap_or(false)+}++async fn mock_current_user(headers: HeaderMap) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ Ok(Json(json!({+ "success": true,+ "data": { "_id": "webhooks-e2e-user", "username": "webhooks-e2e" }+ })))+}++fn tunnel_row(id: &str, name: &str, active: bool) -> Value {+ json!({+ "id": id,+ "uuid": format!("uuid-{id}"),+ "name": name,+ "isActive": active,+ "url": format!("https://tunnels.example/{id}"),+ })+}++async fn mock_list_tunnels(+ State(state): State<BackendState>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ state.record("GET", "/webhooks/core", None);+ Ok(Json(json!({+ "success": true,+ "data": { "tunnels": [tunnel_row("tun-1", "first", true)] }+ })))+}++async fn mock_create_tunnel(+ State(state): State<BackendState>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ state.record("POST", "/webhooks/core", Some(body.clone()));+ let name = body+ .get("name")+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ Ok(Json(json!({+ "success": true,+ "data": tunnel_row("tun-created", &name, true)+ })))+}++async fn mock_get_tunnel(+ State(state): State<BackendState>,+ AxumPath(id): AxumPath<String>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ state.record("GET", &format!("/webhooks/core/{id}"), None);+ Ok(Json(json!({+ "success": true,+ "data": tunnel_row(&id, "fetched", true)+ })))+}++async fn mock_patch_tunnel(+ State(state): State<BackendState>,+ AxumPath(id): AxumPath<String>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ state.record("PATCH", &format!("/webhooks/core/{id}"), Some(body.clone()));+ let name = body+ .get("name")+ .and_then(Value::as_str)+ .unwrap_or("unchanged");+ let active = body+ .get("isActive")+ .and_then(Value::as_bool)+ .unwrap_or(true);+ Ok(Json(json!({+ "success": true,+ "data": tunnel_row(&id, name, active)+ })))+}++async fn mock_delete_tunnel(+ State(state): State<BackendState>,+ AxumPath(id): AxumPath<String>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ state.record("DELETE", &format!("/webhooks/core/{id}"), None);+ Ok(Json(json!({ "success": true, "data": { "deleted": true, "id": id } })))+}++async fn mock_bandwidth(+ State(state): State<BackendState>,+ headers: HeaderMap,+) -> Result<Json<Value>, (StatusCode, Json<Value>)> {+ if !is_authed(&headers) {+ return Err(unauthorized());+ }+ state.record("GET", "/webhooks/core/bandwidth", None);+ Ok(Json(json!({+ "success": true,+ "data": { "bytesIn": 4096, "bytesOut": 8192, "limitBytes": 1_048_576 }+ })))+}++fn mock_backend_router(state: BackendState) -> Router {+ Router::new()+ .route("/settings", get(mock_current_user))+ .route("/auth/me", get(mock_current_user))+ // `/webhooks/core/bandwidth` must be declared before the `{id}` capture, otherwise the+ // capture swallows it and `get_bandwidth` silently reads a tunnel row.+ .route(+ "/webhooks/core/bandwidth",+ get(mock_bandwidth).with_state(state.clone()),+ )+ .route(+ "/webhooks/core",+ get(mock_list_tunnels)+ .post(mock_create_tunnel)+ .with_state(state.clone()),+ )+ .route(+ "/webhooks/core/{id}",+ get(mock_get_tunnel)+ .patch(mock_patch_tunnel)+ .delete(mock_delete_tunnel)+ .with_state(state),+ )+}++// ── infrastructure ───────────────────────────────────────────────────────────++async fn serve_ephemeral(app: Router) -> (SocketAddr, tokio::task::JoinHandle<()>) {+ ensure_rpc_auth();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind ephemeral port");+ let addr = listener.local_addr().expect("local addr");+ let handle = tokio::spawn(async move {+ axum::serve(listener, app).await.ok();+ });+ (addr, handle)+}++fn write_test_config(openhuman_dir: &Path, api_origin: &str) {+ let cfg = format!(+ r#"api_url = "{api_origin}"+default_model = "e2e-mock-model"+default_temperature = 0.7+chat_onboarding_completed = true++[secrets]+encrypt = false+"#+ );+ fn write_cfg(dir: &Path, cfg: &str) {+ std::fs::create_dir_all(dir).expect("mkdir config dir");+ std::fs::write(dir.join("config.toml"), cfg).expect("write config.toml");+ }+ write_cfg(openhuman_dir, &cfg);+ write_cfg(&openhuman_dir.join("users").join("local"), &cfg);+ write_cfg(&openhuman_dir.join("users").join("webhooks-e2e-user"), &cfg);+}++async fn post_json_rpc(rpc_base: &str, id: i64, method: &str, params: Value) -> Value {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(60))+ .build()+ .expect("reqwest client");+ let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });+ let url = format!("{}/rpc", rpc_base.trim_end_matches('/'));+ let resp = client+ .post(&url)+ .header(AUTHORIZATION, format!("Bearer {}", rpc_bearer()))+ .json(&body)+ .send()+ .await+ .unwrap_or_else(|e| panic!("POST {url}: {e}"));+ assert!(+ resp.status().is_success(),+ "HTTP error {} calling {method}",+ resp.status()+ );+ resp.json::<Value>()+ .await+ .unwrap_or_else(|e| panic!("json parse for {method}: {e}"))+}++fn assert_no_jsonrpc_error<'a>(v: &'a Value, ctx: &str) -> &'a Value {+ if let Some(err) = v.get("error") {+ panic!("{ctx}: unexpected JSON-RPC error: {err}");+ }+ v.get("result")+ .unwrap_or_else(|| panic!("{ctx}: missing result field: {v}"))+}++fn jsonrpc_error_message(v: &Value, ctx: &str) -> String {+ let err = v+ .get("error")+ .unwrap_or_else(|| panic!("{ctx}: expected a JSON-RPC error, got: {v}"));+ err.get("message")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("{ctx}: error had no message: {err}"))+ .to_string()+}++/// Peel the `{"result": inner, "logs": [...]}` envelope `RpcOutcome` adds when logs are present.+fn peel<'a>(v: &'a Value) -> &'a Value {+ if v.get("logs").is_some() {+ v.get("result").unwrap_or(v)+ } else {+ v+ }+}++/// The registration rows for `tunnel_uuid`, from a `list_registrations`-shaped payload.+fn registration<'a>(result: &'a Value, tunnel_uuid: &str) -> Option<&'a Value> {+ result+ .get("registrations")?+ .as_array()?+ .iter()+ .find(|r| r.get("tunnel_uuid").and_then(Value::as_str) == Some(tunnel_uuid))+}++fn sample_webhook_request(correlation_id: &str, tunnel_uuid: &str) -> WebhookRequest {+ WebhookRequest {+ correlation_id: correlation_id.to_string(),+ tunnel_id: "backend-tunnel-1".to_string(),+ tunnel_uuid: tunnel_uuid.to_string(),+ tunnel_name: "logging-tunnel".to_string(),+ method: "POST".to_string(),+ path: "/hook".to_string(),+ headers: HashMap::new(),+ query: HashMap::new(),+ body: String::new(),+ }+}++// ── router-local registry ────────────────────────────────────────────────────++/// `register_echo` → `list_registrations` → `unregister_echo`, plus the two ownership guards+/// `register_target` enforces.+///+/// Covers: `openhuman.webhooks_register_echo`, `openhuman.webhooks_register_agent`,+/// `openhuman.webhooks_list_registrations`, `openhuman.webhooks_unregister_echo`.+#[tokio::test]+async fn webhooks_registration_lifecycle_and_ownership_guards() {+ let _env_lock = webhooks_e2e_env_lock();+ let _router = shared_router();++ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");+ let _home_guard = EnvGuard::set_to_path("HOME", home);+ let _ws_guard = EnvGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_guard = EnvGuard::unset("BACKEND_URL");+ let _vite_guard = EnvGuard::unset("VITE_BACKEND_URL");++ let state = BackendState::default();+ let (mock_addr, mock_join) = serve_ephemeral(mock_backend_router(state)).await;+ write_test_config(&openhuman_home, &format!("http://{mock_addr}"));++ let (rpc_addr, rpc_join) = serve_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");++ let echo_uuid = "e2e-lifecycle-echo";+ let agent_uuid = "e2e-lifecycle-agent";++ // ── register_echo returns the *updated* registry, not just an ack.+ let registered = post_json_rpc(+ &rpc_base,+ 7001,+ "openhuman.webhooks_register_echo",+ json!({ "tunnel_uuid": echo_uuid, "tunnel_name": "Echo Tunnel", "backend_tunnel_id": "bt-9" }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(®istered, "webhooks_register_echo"));+ let row = registration(result, echo_uuid).expect("echo registration present in response");+ assert_eq!(+ row.get("target_kind").and_then(Value::as_str),+ Some("echo"),+ "register_echo must record target_kind=echo: {row}"+ );+ assert_eq!(row.get("skill_id").and_then(Value::as_str), Some("echo"));+ assert_eq!(+ row.get("tunnel_name").and_then(Value::as_str),+ Some("Echo Tunnel"),+ "the optional tunnel_name must be persisted, not dropped: {row}"+ );+ assert_eq!(+ row.get("backend_tunnel_id").and_then(Value::as_str),+ Some("bt-9")+ );++ // ── an agent registration on an echo-owned tunnel is refused by name.+ let conflict = post_json_rpc(+ &rpc_base,+ 7002,+ "openhuman.webhooks_register_agent",+ json!({ "tunnel_uuid": echo_uuid, "agent_id": "agent-a" }),+ )+ .await;+ let message = jsonrpc_error_message(&conflict, "register_agent over an echo tunnel");+ assert!(+ message.contains(echo_uuid) && message.contains("already owned by"),+ "cross-target registration must be refused naming the owner, got: {message}"+ );++ // ── an agent tunnel binds its agent_id, and refuses a silent rebind.+ let agent = post_json_rpc(+ &rpc_base,+ 7003,+ "openhuman.webhooks_register_agent",+ json!({ "tunnel_uuid": agent_uuid, "agent_id": "agent-a" }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&agent, "webhooks_register_agent"));+ let row = registration(result, agent_uuid).expect("agent registration present");+ assert_eq!(row.get("target_kind").and_then(Value::as_str), Some("agent"));+ assert_eq!(row.get("agent_id").and_then(Value::as_str), Some("agent-a"));++ let rebind = post_json_rpc(+ &rpc_base,+ 7004,+ "openhuman.webhooks_register_agent",+ json!({ "tunnel_uuid": agent_uuid, "agent_id": "agent-b" }),+ )+ .await;+ let message = jsonrpc_error_message(&rebind, "agent rebind");+ assert!(+ message.contains("cannot rebind"),+ "rebinding an agent tunnel to a different agent must be refused, got: {message}"+ );++ // ── list_registrations sees both, with the values register_* stored.+ let listed = post_json_rpc(+ &rpc_base,+ 7005,+ "openhuman.webhooks_list_registrations",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(+ &listed,+ "webhooks_list_registrations",+ ));+ assert!(+ registration(result, echo_uuid).is_some() && registration(result, agent_uuid).is_some(),+ "list_registrations must return both tunnels: {result}"+ );++ // ── unregister_echo removes exactly the echo tunnel.+ let removed = post_json_rpc(+ &rpc_base,+ 7006,+ "openhuman.webhooks_unregister_echo",+ json!({ "tunnel_uuid": echo_uuid }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(+ &removed,+ "webhooks_unregister_echo",+ ));+ assert!(+ registration(result, echo_uuid).is_none(),+ "unregister_echo must drop the echo tunnel: {result}"+ );+ assert!(+ registration(result, agent_uuid).is_some(),+ "unregister_echo must not touch the sibling agent tunnel: {result}"+ );++ // ── a missing required param is a params error, not a panic or a silent success.+ let bad = post_json_rpc(+ &rpc_base,+ 7007,+ "openhuman.webhooks_register_echo",+ json!({ "tunnel_name": "no uuid here" }),+ )+ .await;+ let message = jsonrpc_error_message(&bad, "register_echo without tunnel_uuid");+ assert!(+ message.contains("missing required param 'tunnel_uuid'"),+ "a missing tunnel_uuid must be caught by the pre-dispatch schema validator \+ (`core::all::validate_params`) and name the field, got: {message}"+ );++ mock_join.abort();+ rpc_join.abort();+}++/// The debug-log ring: empty → populated by a recorded request → cleared.+///+/// Covers: `openhuman.webhooks_list_logs`, `openhuman.webhooks_clear_logs`.+#[tokio::test]+async fn webhooks_debug_log_ring_records_and_clears() {+ let _env_lock = webhooks_e2e_env_lock();+ let router = shared_router();++ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");+ let _home_guard = EnvGuard::set_to_path("HOME", home);+ let _ws_guard = EnvGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_guard = EnvGuard::unset("BACKEND_URL");+ let _vite_guard = EnvGuard::unset("VITE_BACKEND_URL");++ let state = BackendState::default();+ let (mock_addr, mock_join) = serve_ephemeral(mock_backend_router(state)).await;+ write_test_config(&openhuman_home, &format!("http://{mock_addr}"));++ let (rpc_addr, rpc_join) = serve_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");++ // Start from a known-empty ring — `clear_logs` reports what it removed.+ post_json_rpc(&rpc_base, 7101, "openhuman.webhooks_clear_logs", json!({})).await;++ let empty = post_json_rpc(+ &rpc_base,+ 7102,+ "openhuman.webhooks_list_logs",+ json!({ "limit": 50 }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&empty, "webhooks_list_logs (empty)"));+ assert_eq!(+ result.get("logs").and_then(Value::as_array).map(Vec::len),+ Some(0),+ "the ring must be empty right after clear_logs: {result}"+ );++ // Drive the same entry point the socket ingress uses.+ router.record_request(+ &sample_webhook_request("corr-e2e-1", "e2e-log-tunnel"),+ Some("echo".to_string()),+ );++ let listed = post_json_rpc(+ &rpc_base,+ 7103,+ "openhuman.webhooks_list_logs",+ json!({ "limit": 50 }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&listed, "webhooks_list_logs"));+ let logs = result+ .get("logs")+ .and_then(Value::as_array)+ .expect("logs array");+ assert_eq!(logs.len(), 1, "one recorded request → one log entry: {result}");+ let entry = &logs[0];+ assert_eq!(+ entry.get("correlation_id").and_then(Value::as_str),+ Some("corr-e2e-1"),+ "the log entry must carry the request's correlation id: {entry}"+ );+ assert_eq!(entry.get("method").and_then(Value::as_str), Some("POST"));+ assert_eq!(entry.get("path").and_then(Value::as_str), Some("/hook"));+ assert_eq!(entry.get("skill_id").and_then(Value::as_str), Some("echo"));+ assert_eq!(+ entry.get("stage").and_then(Value::as_str),+ Some("received"),+ "a request with no response yet must sit at stage=received: {entry}"+ );+ assert!(+ entry.get("status_code").map(Value::is_null).unwrap_or(true),+ "no response recorded yet ⇒ status_code must still be null: {entry}"+ );++ // 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"));+ assert_eq!(+ result.get("cleared").and_then(Value::as_u64),+ Some(1),+ "clear_logs must report the number of entries it removed: {result}"+ );++ let after = post_json_rpc(&rpc_base, 7105, "openhuman.webhooks_list_logs", json!({})).await;+ let result = peel(assert_no_jsonrpc_error(&after, "webhooks_list_logs (after)"));+ assert_eq!(+ result.get("logs").and_then(Value::as_array).map(Vec::len),+ Some(0)+ );++ mock_join.abort();+ rpc_join.abort();+}++/// `trigger_agent` rejects a source slug it does not implement, naming the supported set.+///+/// The three supported slugs all run the triage pipeline (an LLM call), so the failure path is+/// what this file covers; `tests/json_rpc_e2e.rs` owns the model-backed flows.+///+/// Covers: `openhuman.webhooks_trigger_agent`.+#[tokio::test]+async fn webhooks_trigger_agent_rejects_unsupported_source() {+ let _env_lock = webhooks_e2e_env_lock();+ let _router = shared_router();++ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");+ let _home_guard = EnvGuard::set_to_path("HOME", home);+ let _ws_guard = EnvGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_guard = EnvGuard::unset("BACKEND_URL");+ let _vite_guard = EnvGuard::unset("VITE_BACKEND_URL");++ let state = BackendState::default();+ let (mock_addr, mock_join) = serve_ephemeral(mock_backend_router(state)).await;+ write_test_config(&openhuman_home, &format!("http://{mock_addr}"));++ let (rpc_addr, rpc_join) = serve_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");++ let bad_source = post_json_rpc(+ &rpc_base,+ 7201,+ "openhuman.webhooks_trigger_agent",+ json!({ "caller_id": "caller-1", "source": "carrier-pigeon", "reason": "e2e" }),+ )+ .await;+ let message = jsonrpc_error_message(&bad_source, "trigger_agent with a bogus source");+ assert!(+ message.contains("unsupported trigger source `carrier-pigeon`"),+ "the error must name the rejected slug, got: {message}"+ );+ assert!(+ message.contains("webhook") && message.contains("cron") && message.contains("external"),+ "the error must list the supported slugs so a caller can fix it, got: {message}"+ );++ // `caller_id` is the one required field; omitting it must not reach the triage pipeline.+ let missing_caller = post_json_rpc(+ &rpc_base,+ 7202,+ "openhuman.webhooks_trigger_agent",+ json!({ "source": "external" }),+ )+ .await;+ let message = jsonrpc_error_message(&missing_caller, "trigger_agent without caller_id");+ assert!(+ message.contains("missing required param 'caller_id'"),+ "a missing caller_id must be refused before the triage pipeline is reached, got: {message}"+ );++ mock_join.abort();+ rpc_join.abort();+}++// ── backend tunnel CRUD ──────────────────────────────────────────────────────++/// The full backend-tunnel surface against a recording mock: create → get → update → list →+/// bandwidth → delete, asserting on both the response and the request the adapter built.+///+/// Covers: `openhuman.webhooks_create_tunnel`, `openhuman.webhooks_get_tunnel`,+/// `openhuman.webhooks_update_tunnel`, `openhuman.webhooks_list_tunnels`,+/// `openhuman.webhooks_get_bandwidth`, `openhuman.webhooks_delete_tunnel`.+#[tokio::test]+async fn webhooks_backend_tunnel_crud_roundtrip() {+ let _env_lock = webhooks_e2e_env_lock();+ let _router = shared_router();++ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");+ let _home_guard = EnvGuard::set_to_path("HOME", home);+ let _ws_guard = EnvGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_guard = EnvGuard::unset("BACKEND_URL");+ let _vite_guard = EnvGuard::unset("VITE_BACKEND_URL");++ let state = BackendState::default();+ let (mock_addr, mock_join) = serve_ephemeral(mock_backend_router(state.clone())).await;+ write_test_config(&openhuman_home, &format!("http://{mock_addr}"));++ let (rpc_addr, rpc_join) = serve_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");++ let store = post_json_rpc(+ &rpc_base,+ 7300,+ "openhuman.auth_store_session",+ json!({ "token": TEST_JWT, "user_id": "webhooks-e2e-user" }),+ )+ .await;+ assert_no_jsonrpc_error(&store, "auth_store_session");++ // ── create: the name is trimmed and an empty description is dropped, not sent blank.+ let created = post_json_rpc(+ &rpc_base,+ 7301,+ "openhuman.webhooks_create_tunnel",+ json!({ "name": " Payments Hook ", "description": " " }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&created, "webhooks_create_tunnel"));+ assert_eq!(+ result.get("name").and_then(Value::as_str),+ Some("Payments Hook"),+ "the mock echoes the name it received; it must arrive trimmed: {result}"+ );+ let create_call = state+ .calls()+ .into_iter()+ .find(|c| c.method == "POST" && c.path == "/webhooks/core")+ .expect("a POST /webhooks/core was issued");+ let body = create_call.body.expect("create body");+ assert_eq!(body.get("name").and_then(Value::as_str), Some("Payments Hook"));+ assert!(+ body.get("description").is_none(),+ "a whitespace-only description must be omitted from the body, not sent empty: {body}"+ );++ // ── get: the id is percent-encoded into the path.+ let fetched = post_json_rpc(+ &rpc_base,+ 7302,+ "openhuman.webhooks_get_tunnel",+ json!({ "id": " tun a b " }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&fetched, "webhooks_get_tunnel"));+ assert_eq!(+ result.get("name").and_then(Value::as_str),+ Some("fetched"),+ "get_tunnel must surface the backend row: {result}"+ );+ let get_call = state+ .calls()+ .into_iter()+ .find(|c| c.method == "GET" && c.path.starts_with("/webhooks/core/tun"))+ .expect("a GET /webhooks/core/{id} was issued");+ assert_eq!(+ get_call.path, "/webhooks/core/tun a b",+ "the id must be trimmed and percent-encoded — the mock reports the *decoded* capture, so \+ an un-encoded id with spaces would not have reached this route at all"+ );++ // ── update: snake_case params are mapped to the backend's camelCase body keys.+ let updated = post_json_rpc(+ &rpc_base,+ 7303,+ "openhuman.webhooks_update_tunnel",+ // `update_tunnel` is the one controller in this namespace whose declared inputs are+ // camelCase (`isActive`), matching `WebhookUpdateTunnelParams`' `rename_all`. Its+ // siblings take snake_case (`tunnel_uuid`, `backend_tunnel_id`). Asserting the real+ // contract here pins that asymmetry rather than papering over it.+ json!({ "id": "tun-created", "name": "Renamed", "isActive": false }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&updated, "webhooks_update_tunnel"));+ assert_eq!(result.get("name").and_then(Value::as_str), Some("Renamed"));+ assert_eq!(+ result.get("isActive").and_then(Value::as_bool),+ Some(false),+ "the mock reflects the isActive it was sent: {result}"+ );+ let patch_call = state+ .calls()+ .into_iter()+ .find(|c| c.method == "PATCH")+ .expect("a PATCH was issued");+ let body = patch_call.body.expect("patch body");+ assert_eq!(+ body.get("isActive").and_then(Value::as_bool),+ Some(false),+ "the active flag must reach the backend as `isActive`: {body}"+ );+ assert!(+ body.get("is_active").is_none(),+ "a snake_case duplicate must not also be sent: {body}"+ );+ assert!(+ body.get("description").is_none(),+ "an omitted field must be absent from the PATCH body, not sent as null: {body}"+ );++ // ── list+ let listed = post_json_rpc(+ &rpc_base,+ 7304,+ "openhuman.webhooks_list_tunnels",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&listed, "webhooks_list_tunnels"));+ let tunnels = result+ .get("tunnels")+ .and_then(Value::as_array)+ .expect("tunnels array");+ assert_eq!(tunnels.len(), 1, "list_tunnels must surface the backend rows: {result}");+ assert_eq!(tunnels[0].get("id").and_then(Value::as_str), Some("tun-1"));++ // ── bandwidth: its own path, not the `{id}` capture.+ let bandwidth = post_json_rpc(+ &rpc_base,+ 7305,+ "openhuman.webhooks_get_bandwidth",+ json!({}),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&bandwidth, "webhooks_get_bandwidth"));+ assert_eq!(+ result.get("bytesIn").and_then(Value::as_u64),+ Some(4096),+ "get_bandwidth must read /webhooks/core/bandwidth, not a tunnel row: {result}"+ );+ assert_eq!(result.get("bytesOut").and_then(Value::as_u64), Some(8192));++ // ── delete+ let deleted = post_json_rpc(+ &rpc_base,+ 7306,+ "openhuman.webhooks_delete_tunnel",+ json!({ "id": "tun-created" }),+ )+ .await;+ let result = peel(assert_no_jsonrpc_error(&deleted, "webhooks_delete_tunnel"));+ assert_eq!(result.get("deleted").and_then(Value::as_bool), Some(true));+ assert!(+ state+ .calls()+ .iter()+ .any(|c| c.method == "DELETE" && c.path == "/webhooks/core/tun-created"),+ "delete_tunnel must issue DELETE on the id path: {:?}",+ state.calls()+ );++ // ── local validation runs before the network hop.+ let blank_name = post_json_rpc(+ &rpc_base,+ 7307,+ "openhuman.webhooks_create_tunnel",+ json!({ "name": " " }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&blank_name, "create_tunnel with a blank name").contains("name is required"),+ "a whitespace-only name must be rejected locally"+ );++ let blank_id = post_json_rpc(+ &rpc_base,+ 7308,+ "openhuman.webhooks_get_tunnel",+ json!({ "id": " " }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&blank_id, "get_tunnel with a blank id").contains("id is required"),+ "a whitespace-only id must be rejected locally"+ );++ let before = state.calls().len();+ let blank_delete = post_json_rpc(+ &rpc_base,+ 7309,+ "openhuman.webhooks_delete_tunnel",+ json!({ "id": "" }),+ )+ .await;+ assert!(+ jsonrpc_error_message(&blank_delete, "delete_tunnel with a blank id").contains("id is required")+ );+ assert_eq!(+ state.calls().len(),+ before,+ "a locally-rejected request must not reach the backend at all"+ );++ mock_join.abort();+ rpc_join.abort();+}++/// Every backend-tunnel adapter refuses before the network hop when no session is stored.+///+/// This is the guard that keeps an unauthenticated core from firing a doomed request at the+/// hosted backend; it is shared by all six tunnel controllers via `require_token`.+#[tokio::test]+async fn webhooks_tunnel_calls_require_a_stored_session() {+ let _env_lock = webhooks_e2e_env_lock();+ let _router = shared_router();++ let tmp = tempdir().expect("tempdir");+ let home = tmp.path();+ let openhuman_home = home.join(".openhuman");+ let _home_guard = EnvGuard::set_to_path("HOME", home);+ let _ws_guard = EnvGuard::unset("OPENHUMAN_WORKSPACE");+ let _backend_guard = EnvGuard::unset("BACKEND_URL");+ let _vite_guard = EnvGuard::unset("VITE_BACKEND_URL");++ let state = BackendState::default();+ let (mock_addr, mock_join) = serve_ephemeral(mock_backend_router(state.clone())).await;+ write_test_config(&openhuman_home, &format!("http://{mock_addr}"));++ let (rpc_addr, rpc_join) = serve_ephemeral(build_core_http_router(false)).await;+ let rpc_base = format!("http://{rpc_addr}");++ // Deliberately NO auth_store_session.+ for (id, method, params) in [+ (7401, "openhuman.webhooks_list_tunnels", json!({})),+ (7402, "openhuman.webhooks_get_bandwidth", json!({})),+ (+ 7403,+ "openhuman.webhooks_create_tunnel",+ json!({ "name": "unauthenticated" }),+ ),+ ] {+ let response = post_json_rpc(&rpc_base, id, method, params).await;+ let message = jsonrpc_error_message(&response, method);+ assert!(+ message.contains("no backend session token"),+ "{method} must refuse without a stored session, got: {message}"+ );+ }++ assert!(+ state.calls().is_empty(),+ "no tunnel request may reach the backend without a session: {:?}",+ state.calls()+ );++ mock_join.abort();+ rpc_join.abort();+}